How to mock the optional ResponseEntity code below for code coverage. Could someone please assist? - spring-boot

public ResponseEntity<Optional> getData(#RequestBody RequestModel requestModel) {
try {
List mango = new ArrayList();
mangoRepository.findByMangoTag(
requestModel.getMangoTag(),
requestModel.getMangoProduct(),
requestModel.getSellerType()).forEach(mango::add);
Optional<Mango> res = mango.stream().findFirst();
if (!res.isPresent()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(res, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}

Related

Spring boot RestTemplate close connection for NULL responses results in ConnectionPoolTimeoutExceptions

We have a spring boot Application which makes RESTFul calls to a bunch of backends, one of them returns null reponses at times, and we are observing the connections are not released during these instances because of this code in RestTemplate class:
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
Assert.notNull(url, "'url' must not be null");
Assert.notNull(method, "'method' must not be null");
ClientHttpResponse response = null;
try {
ClientHttpRequest request = createRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
}
response = request.execute();
handleResponse(url, method, response);
if (responseExtractor != null) {
return responseExtractor.extractData(response);
}
else {
return null;
}
}
catch (IOException ex) {
String resource = url.toString();
String query = url.getRawQuery();
resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
throw new ResourceAccessException("I/O error on " + method.name() +
" request for \"" + resource + "\": " + ex.getMessage(), ex);
}
finally {
if (response != null) {
response.close();
}
}
}
Is there a way we can release the connection or consume the contents for when response is null or erring out?
Edited to add code causing errors:
MyHttpClientClass{
private X getResponseBody(RestClient client, URI uri, HttpMethod method, HttpEntity<T> entity, Class<R> responseType, MyErrorHandler errorHandler) {
try
{ String host = this.getHost();
ResponseEntity<X> resp = client.exchange(uri, method, entity, responseType);
return resp.getBody();
} catch (HttpServerErrorException | HttpClientErrorException e)
{ handleHttpException(e, errorHandler);
throw e;
} catch (Exception e) {
log(e);
throw e; } } }
-----------
Class1 implements Callable<T>
{
#Override public T doCall() throws Exception {
try
{ return this.getRestClient().exchange(this.getUri(),
this.getHttpMethod(), this.getEntity(), getResponseType()).getBody(); } catch (HttpClientErrorException ex) { throw ex; } catch (HttpStatusCodeException ex) { if(this.isNeededRetry(ex)) { throw ex; }else { return generateErrorResponse(ex).getBody(); } } catch (RestClientException ex) { throw ex; } catch (Exception ex) { throw ex; } } }
----------
MySpringApplicationClass{
public X get(String api, String params, Class<R> responseType, String path, List<String> pathVariables, MyErrorHandler errorHandler)
{
return getResponseBody(...);
}}

Handling multipart response from spring rest controller

I am having controller method like this
#PostMapping(path = "/downloadAttachment",
produces = "application/octet-stream")
public ResponseEntity<?> downloadAttachment(#Valid #RequestBody Attachment attachmentModel) {
refreshProp(false);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try {
String byteRes = null;
JSONArray responseFromDownloadAttachment =
databaseOperations.downloadAttachment(attachmentModel);
if (responseFromDownloadAttachment.length() == 0) {
return new ResponseEntity<>("", HttpStatus.NO_CONTENT);
}
else {
for (int blobRes = 0; blobRes < responseFromDownloadAttachment.length(); blobRes++) {
JSONObject blobObj = responseFromDownloadAttachment.getJSONObject(blobRes);
if (blobObj != null) {
byteRes = (String) blobObj.getString("file");
}
}
}
byte[] byteArrray = byteRes.getBytes();
return new ResponseEntity<>(byteArrray, HttpStatus.OK);
} catch (Exception e) {
log.error("Exception occurred!" + e);
e.printStackTrace();
JSONObject errObj = new JSONObject();
errObj.put("status", "E");
errObj.put("message", e);
return new ResponseEntity<>(errObj.toString(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
I am sending byte array as response.But i am not sure which type of file i will be getting from service layer.It can be in any form like xlsx,txt,png,jpg or any multimedia.I am setting headers to octet-stream and also produces to octet-stream.Can i use octet-stream to handle these type of responses?

Spring Boot Java Request GET Request Mapping URL problems

How to turn this 【http://myurl.com/test/api/v1/data/?:getlicense=1234】
to this way 【http://myurl.com/test/api/v1/data/:getlicense/1234】
The code below using postman GET http://myurl.com/test/api/v1/data/?:getlicense=1234 will return result success.
Below is my code:
#RequestMapping(value="/api/v1/data/" ,produces=MediaType.APPLICATION_JSON_VALUE,headers="Accept=*/*",method = { RequestMethod.GET })
public Map ReturnData(#RequestParam(":getlicense") String getdata) {
Map returns = new HashMap();
try {
queryData qD= new queryData ();
qD.setData(getdata);
returns = result.getdataList(qD);
} catch (Exception e) {
e.printStackTrace();
}
return returns;
}
please help me, thank you.
You have to convert your RequestParam to a PathVariable
#GetMapping("/api/v1/data/licenses/{id}")
public Map returnData(#PathVariable(value = "id") String id) {
Map returns = new HashMap();
try {
queryData qD= new queryData ();
qD.setData(id);
returns = result.getdataList(qD);
} catch (Exception e) {
e.printStackTrace();
}
return returns;
}
Please find below solution
#RequestMapping(value="/api/v1/data/licenses/{id}" ,produces=MediaType.APPLICATION_JSON_VALUE,headers="Accept=*/*",method = { RequestMethod.GET })
public Map ReturnData(#PathVariable(value = "id") String id) {
Map returns = new HashMap();
try {
queryData qD= new queryData ();
qD.setData(id);
returns = result.getdataList(qD);
} catch (Exception e) {
e.printStackTrace();
}
return returns;
}

Spring boot HeaderWriterFilter overrides header created in controller

When I add a header to the responseEntity in the Controller, it is not added to the response. I debug the code, an when it reach the "HeaderWriterFilter" it adds default header, but it has no track of the one added in the Controller.
#RequestMapping(
value = "/get-file",
method = RequestMethod.GET
)
public ResponseEntity<Resource> download(Principal principal, Long fileId) throws IOException {
if (principal == null) {
throw new UsernameNotFoundException("User not found.");
}
try {
User loggedInUser = ((LoggedInUserDetails) ((UsernamePasswordAuthenticationToken) principal).getPrincipal()).getLoggedInUser();
// Get file
File file = this.fileService.getById(loggedInUser, fileId);
if (file == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
// Get file for download
java.io.File physicalFile = new java.io.File(file.getUrl());
if (file == null) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
InputStreamResource resource = new InputStreamResource(new FileInputStream(physicalFile));
HttpHeaders headers = new HttpHeaders();
headers.add("test", "test.yaml");
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.contentLength(physicalFile.length())
.body(resource);
}
catch (FileNotFoundException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
The problem was a missing header in WebSecurityConfig. I solved the problem adding
configuration.setExposedHeaders(Arrays.asList("fileName"));
in CorsConfigurationSource.

android volley JsonArrayRequest return nothing

in the below code my arrayList will be empty after JsonArrayRequest block.
I set break point at this line: "int size = arrayList.size();"
every thing is OK until "while" loop finishes. after that allayList is empty.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,(String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count=0;
int responseLength = response.length();
responseLength--;
while (count<responseLength)
{
try {
JSONObject jsonObject = response.getJSONObject(count);
Contact contact = new Contact(jsonObject.getString("title"),
jsonObject.getString("email"),
jsonObject.getString("description"),
jsonObject.getString("date"),
jsonObject.getBoolean("status"));
arrayList.add(contact);
int size = arrayList.size();
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
int size = arrayList.size();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error....",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}
);
int size = arrayList.size();
VolleySingleton.getmInstance(context).addToRequestQueue(jsonArrayRequest);
return arrayList;
I will show what i did using CallBack interface:
in onCreate() method:
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.getContacts(new BackgroundTask.arrayListCallBack() {
#Override
public void onSuccess(ArrayList<Contact> contacts) {
RecyclerView.Adapter adapter = new RecyclerAdapter(MainActivity.this, contacts);
recyclerView.setAdapter(adapter);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_LONG).show();
}
});
and in the BackgroundTask class:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, server_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
Contact contact = new Contact(jsonObject.getString("name"), jsonObject.getString("section"));
contacts.add(contact);
Log.d("process request", "....."+jsonObject.getString("name"));
count++;
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage()+"\nError in Response", Toast.LENGTH_LONG).show();
}
callBack.onSuccess(contacts);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(context, error.getMessage()+"\nError in Connection", Toast.LENGTH_LONG).show();
callBack.onFail("There's error ...");
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}
public interface arrayListCallBack {
void onSuccess(ArrayList<Contact> contacts);
void onFail(String error);
}

Resources