Spring REST GET with HttpServletRequest

REST client:


import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.ns.model.UdsTransactionRequest;
import com.ns.model.UfsReferenceNumber;
import com.ns.model.notification.UfsPipeline;
import com.ns.service.ServiceResponse;

	@SuppressWarnings("unchecked")
	private void testGet2() {

		RestTemplate restTemplate = new RestTemplate();

		Long txId = 123456789L;
		String[] array = {"6B","EL","SO","RN","KK"};

		String url = "http://localhost:8080/transaction/references/pipeline/{txId}/?types={types}";

		ServiceResponse<UfsReferenceNumber> response = restTemplate.getForObject(url, ServiceResponse.class, txId, StringUtils.join(array, ","));

		List<UfsReferenceNumber> results = response.getData();
		if (results != null && !results.isEmpty()) {
			for (UfsReferenceNumber a : results) {
				System.out.println("---------------- ID: " + a.getId().getRefNum());
			}
		}
		System.out.println("---------------- END testGet2------------------");
	}

This gives the URL:

http://localhost:8080/transaction/references/pipeline/123456789/?types=6B,EL,SO,RN,KK

The “request.getParameter(“types”);” gets the values from URL “types=6B,EL,SO,RN,KK”.

REST endpoint:

@RequestMapping(value = "/references/pipeline/{txId}/", method = RequestMethod.GET)
public ServiceResponse<UfsReferenceNumber> getReferences(@PathVariable String txId, HttpServletRequest request) {
	ServiceResponse<UfsReferenceNumber> response = new ServiceResponse<>();
	String typesCsv = request.getParameter("types");
	List<String> types = null;
	List<UfsReferenceNumber> references = null;
	if (null != typesCsv && 0 != typesCsv.length()) {
		types = Arrays.asList(typesCsv.split(","));
	}
	try {
		references = repo.getTxnReferenceNumbers(new Long(txId), types);
		if (null != references && !references.isEmpty()) {
			response.setData(references);
		}
	} catch (Exception e) {
	}
	return response;
}

Spring REST PUT form data

Postman image:

REST client:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

	@SuppressWarnings("unchecked")
	private void testPost() {

		String url = "http://localhost:8080/uds-transaction-1.3.0/pipeline/list/";
		RestTemplate restTemplate = new RestTemplate();

		List<Long> list = new ArrayList<Long>();
		list.add(new Long(30284039614L));
		list.add(new Long(30262601669L));
		list.add(new Long(30262662522L));

		UdsTransactionRequest req = new UdsTransactionRequest();
		req.setTrxIdsLong(list);

		HttpEntity<UdsTransactionRequest> request = new HttpEntity<>(req);

		ServiceResponse<UfsPipeline> response = restTemplate.postForObject(url, request, ServiceResponse.class);

		List<UfsPipeline> results = response.getData();
		if (results != null && !results.isEmpty()) {
			for (UfsPipeline a : results) {
				System.out.println("---------------- txNo: " + a.getTxNo());
			}
		}
	}

Endpoint:

	@RequestMapping(value = "/pipeline/list/", produces = "application/json", method = RequestMethod.POST)
	public ServiceResponse<UfsPipeline> getOfficeDocumentEndPoint(@RequestBody UdsTransactionRequest req) {
		ServiceResponse<UfsPipeline> response = new ServiceResponse<>();
		try {
			List<UfsPipeline> list = pipelineRepo.getPipelinesByKeys(req.getTrxIdsLong());
			response.setData(list);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			response.addError(e);
		}
		return response;
	}

Support class:

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.ns.model.DataCacheMeta;
import com.ns.model.notification.UfsPipeline;

@JsonInclude(Include.NON_NULL)
public class ServiceResponse<T extends ResponseData> implements Serializable {

	public static final String OK = "ok";
	public static final String ERROR = "error";

	private static final long serialVersionUID = 4579157541957745675L;
	private List<ResponseError> errors;
	private List<T> data;
	private String status = OK;

	public void addError(Exception e) {
		if (null == errors) {
			errors = new ArrayList<>();
		}
		ResponseError error = new ResponseError(null, ResponseError.ERROR, e.getMessage());
		errors.add(error);
		setStatus(ServiceResponse.ERROR);
	}

	public void addData(T dataElement) {
		if (null == data) {
			data = new ArrayList<>();
		}
		data.add(dataElement);
	}

	@JsonSubTypes({@JsonSubTypes.Type(value = ResponseError.class, name = "error")})
	public List<ResponseError> getErrors() {
		return errors;
	}

	public void setErrors(List<ResponseError> errors) {
		this.errors = errors;
	}

	@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
	@JsonSubTypes({ @JsonSubTypes.Type(value = DataCacheMeta.class, name = "DataCacheMeta"),
			@JsonSubTypes.Type(value = UfsPipeline.class, name = "UfsPipeline")
	})
	public List<T> getData() {
		return data;
	}

	public void setData(List<T> data) {
		this.data = data;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}
}

Spring REST PUT byte array

POM.xml

<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.0.RELEASE</version>
</dependency>

API


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

private void test() {

	byte[] bytes = readBytesFromFile(path);
	// Prepare acceptable media type
	List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
	acceptableMediaTypes.add(MediaType.ALL);

	String uri = "http://localhost:8080/upload/{company}/{terminal}/{user}/{docType}/{docNum}/{trx}/?addendum=false&index=0&channel=ui";
	RestTemplate restTemplate = new RestTemplate();
	restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

	// Prepare header
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(acceptableMediaTypes);
	HttpEntity<byte[]> entity = new HttpEntity<byte[]>(bytes, headers);

	Map<String, String> param = new HashMap<String, String>();
	param.put("company", "750");
	param.put("terminal", "7501");
	param.put("user", "cmanshande");
	param.put("docType", "HAWS");
	param.put("docNum", "20222608918");
	param.put("trx", "750110714862");

	// Send the request as PUT
	restTemplate.exchange(uri, HttpMethod.PUT, entity, byte[].class, param);
}

Client

@RequestMapping(value = "/upload/{company}/{terminal}/{user}/{docType}/{txId}/**", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<String> processUpload(
		@RequestBody byte[] content,
		@PathVariable String company, 
		@PathVariable String terminal,
		@PathVariable String user, 
		@PathVariable String docType,
		@PathVariable String txId, 
		HttpServletRequest httpRequest) {
.
.
.
.
}

Web Service

title-image-ws7
In large organization, it can be common to share the data between different systems.

For example, the first system get the “Not authorized transactions” from the other system, and authorize them.

This example shows communicating two different websites through Web Service. The each website uses the different Database. Moreover, they are different kind of database; RDB and NoSQL DB.

They are completely different system but they can share the same data.
webservice-flow-img2

Website 1:

  • URL: http://localhost:8080/ns2015mvcmongo001
  • DB: Mongo DB
  • Send a request to Website 2, and received the response (JSON) and store them in Mongo DB.

Website 2:

  • URL: http://localhost:8080/NS2015V07
  • DB: My SQL
  • Receive the request from Website 1, and get the data from DB (My SQL) and send a response (JSON object) back to Website 1.

2015-06-06_21h23_52


Summarized (Three steps) as two websites are communicating through HTTP:

  1. The Website 1 request the Return transactions (RMAs) which are not “Authorized” to Website 2.
  2. The Website 2 response to the Website 1 with the transactions (in JSON object)
  3. The Website 2 stored them in Mongo DB

From: http://localhost:8080/ns2015mvcmongo001/welcome_01.html
file_MVCController_img2
Controller (Website 1) calls Request to (Website 2):

<input type="submit" value="WebService" name="webService" />

Button in JSP

@RequestMapping(value = "/welcome_01", params = "webService", method = RequestMethod.POST)
public ModelAndView refreshByWebService() {	
	ModelAndView modelAndView = new ModelAndView("welcome_01");	
	List<JSONObject> jsonList = getRmaHdrList();
	saveRma(jsonList);

	List<RMA_HDR> rmaList = rmaRep.findByRma_exclude("auth");
	modelAndView.addObject("rmaList", rmaList);

	return modelAndView;
}

Step 1.1. Calls “getRmaHdrList()” method

private List<JSONObject> getRmaHdrList() {
	String output = getJsonStrByURL(this.url);
	List<JSONObject> list = new ArrayList<JSONObject>();
	try {
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(output);
		JSONArray array = (JSONArray) obj;
		
		for (int i = 0; i < array.size(); i++) {
			JSONObject json = (JSONObject) array.get(i);
			list.add(json);

			Long id = (Long) json.get("id");
			String rmaNum = (String) json.get("rmaNum");
			String rmaHdrStsCd = (String) json.get("rmaHdrStsCd");

			System.out.println("id: " + id);
			System.out.println("rmaNum: " + rmaNum);
			System.out.println("rmaHdrStsCd: " + rmaHdrStsCd);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}		
	return list;
}

Step 1.2. Calls “getJsonStrByURL(String url)” method

private String getJsonStrByURL(String url) {
	Client client = Client.create();
	WebResource response = client.resource("http://localhost:8080/NS2015V07/ns-home/json");
	ClientResponse clientRes = response.accept("application/json").get(ClientResponse.class);
	if (clientRes.getStatus() != 200) {
		throw new RuntimeException("Failed : HTTP error code : " + clientRes.getStatus());
	}
	return clientRes.getEntity(String.class);
}

Step 1.3. Calls Website 2: “http://localhost:8080/NS2015V07/ns-home/json”


From: http://localhost:8080/NS2015V07/ns-home/json
file_WSController_img2
Controller in Website 2 received a request and send a response back to Website 1:

@RequestMapping(value = "/ns-home/json", method = RequestMethod.GET)
public @ResponseBody List<RmaHdrModel> getAll(HttpServletRequest req) {
	List<RmaHdrModel> list = RmaBL.getRmaHdrListWCdTblNm(req);
	List<JSONObject> entities = new ArrayList<JSONObject>();
	for (RmaHdrModel rma : list) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("id", rma.getId());
		jsonObject.put("rmaNum", rma.getRmaNum());
		jsonObject.put("rmaHdrStsCd", rma.getRmaHdrStsCd());
		entities.add(jsonObject);
	}
	return list;
}

Step 2.1. At line 3, get the record from DB (MySQL).
Step 2.2. At line 6 to 10, create a JSON object and being set to a list.
Step 2.3. At line 12, return a list (JSON) as a response to: http://localhost:8080/ns2015mvcmongo001/welcome_01.html