Rest template exchange not accept ParameterizedTypeReference - spring

Oops guys! Beauty? I'm trying to get a byte list[] in my Rest template's response, but my exchange isn't accepting the new ParameterizedTypeReference<List<byte[]>>() {} , could someone help me?
ResponseEntity<List<byte[]>> response = null;
try {
response = restTemplate.exchange(parametros.get("SERVICE_HUB2_BASE_URL") + "/fw/v1/pdf/kms/assinaturas",
HttpMethod.POST, entity, new ParameterizedTypeReference<List<byte[]>>() {});
} catch (HttpServerErrorException e) {
e.printStackTrace();
throw new ClientException(e.getStatusCode().value(), e.getStatusText());
} catch (HttpClientErrorException e) {
e.printStackTrace();
throw new ClientException(e.getStatusCode().value(), e.getStatusText());
} catch (Exception e) {
e.printStackTrace();
}

Hi As per the mouse hower it's pointing to different method.
Please check import statement for rest template.
both ways should be fine .
ResponseEntity<Collection<byte[]>> responseEntityOne = restTemplate.exchange(formattedUrl, HttpMethod.POST, entity,
new ParameterizedTypeReference<Collection<byte[]>>(){});
ResponseEntity<List<byte[]>> responseEntityOne1 = restTemplate.exchange(formattedUrl, HttpMethod.POST, entity,
new ParameterizedTypeReference<List<byte[]>>(){});

Related

How to add new Obect inside List<EntityClass>

I am fetching the record from the database. I want to modify new record with the existing record.
I fetching last 6 months data, I want to modify my result ? If any months records I am not getting from the database.
How I can modify existing result List ?
public List<EntityClassName> fetchByType() throws CustomExpection{
// TODO Auto-generated method stub
List<EntityClassName> result;
try {
result = (List<EntityClassName>) genDao.find(Query.byTpe, CommonUtil.getStartEndDate(), new BeanPropertyRowMapper(EntityClassName.class));
result.forEach(
userData -> {
String type = userData.getType_name();
log.info("Type:"+type);
//userData.setType_name(userData.getType_name()+" PPP");
}
);
log.info("Size:"+result.size());
System.err.println(result);
} catch (Exception e) {
e.printStackTrace();
log.error(
"Something went wrong !!!",
e.getMessage());
throw new CustomExpection("Something went wrong !!!");
}
return result;
}
List<Item> sBarang = new ArrayList<Item>();
Item mItem = new Item(); // <-- instantiate a new Item.
mItem.setCode("101");
mItem.setName("Hammer");
mItem.setQty(10);
sBarang.add(mItem); // <-- add it to your List<Item>.

I am accessing JSON array in streams , looking to handle if that JSON array is not present in the schema

JsonObject response = new JsonObject(IOUtils.resourceToString("/ResponseSample.json",
Charset.defaultCharset()));
JsonObject nameObj=
response.getJsonArray("applications",new JsonArray())
.stream().
map(JsonObject.class::cast)
.filter(x->x.getString("id").equalsIgnoreCase("2022025GSxxxxxx"))
.findFirst()
.get()
.getJsonArray("applicants",new JsonArray())
.getJsonObject(0)
.getJsonArray("names", new JsonArray())
.getJsonObject(0)
.getJsonObject("name",new JsonObject());
System.out.println(nameObj.getString("first","")+"--"+nameObj.getString("last",""));
} catch (IOException ex) {
ex.printStackTrace();
}

java stream is making weird things to generate csv file in Spring Boot

I'm processing a csv file through my springboot app, the file is to download it, in my case I use streams but there is a problem what I don't know what's wrong in my code because some rows is complete with the columns but next row only write some columns and leftover columns are write below as if were a new row. I hope you understand what I mean. I hope you give a hand, thank you in advance.
This code below is the controller
.....
#RequestMapping(value="/stream/csv/{grupo}/{iduser}", method = RequestMethod.GET)
public void generateCSVUsingStream(#PathVariable("grupo") String grupo,
#PathVariable("iduser") String userId,HttpServletResponse response) {
response.addHeader("Content-Type", "application/csv");
response.addHeader("Content-Disposition", "attachment; filename=\""+userId+"_Reporte_PayCash"+grupo.replaceAll("\\s", "")+".csv");
response.setCharacterEncoding("UTF-8");
try (Stream<ReportePayCashDTO> streamPaycashdatos = capaDatosDao.ReportePayCashStream(userId, grupo);PrintWriter out = response.getWriter();) {
//PrintWriter out = response.getWriter();
out.write(String.join(",", "Cuenta" , "Referencia", "Referencia_paycash","Distrito","Plaza","Cartera"));
out.write("\n");
streamPaycashdatos.forEach(streamdato -> {
out.write(streamdato.getAccount()+","+streamdato.getReferencia()+","+streamdato.getReferenciapaycash()
+","+streamdato.getCartera()+","+streamdato.getState()+","+streamdato.getCity());
out.append("\r\n");
});
out.flush();
out.close();
streamPaycashdatos.close();
} catch (IOException ix) {
throw new RuntimeException("There is an error while downloading file", ix);
}
}
The method on DAO is this
...
#Override
public Stream<ReportePayCashDTO> ReportePayCashStream(String userId, String grupo) {
// TODO Auto-generated method stub
Stream<ReportePayCashDTO > stream = null ;
String query ="";
//more code
try {
stream = getJdbcTemplate().queryForStream(query, (rs, rowNum) -> {
return new ReportePayCashDTO(Utils.valnull(rs.getString("account")),
Utils.valnull(rs.getString("reference")),
Utils.valnull(rs.getString("referencepaycash")),
Utils.valnull(rs.getString("state")),
Utils.valnull(rs.getString("city")),
Utils.valnull(rs.getString("cartera"))
);
});
}catch(Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
return stream;
}
Example: This is what I hoped will write into csv file
55xxxxx02,88xxxx153,1170050202662,TAMAULIPAS,TAMPICO,AmericanExpre
58xxxxx25,88xxx899,1170050202662,TAMAULIPAS,TAMPICO,AmericanClasic
but some rows was written like this
55xxxxx02,88xxxx153,1170050202662
,TAMAULIPAS,TAMPICO,AmericanExpre
58xxxxx25,88xxx899,1170050202662
,TAMAULIPAS,TAMPICO,AmericanClasic

How to handle feign client connection timeout

I have below code to check this error but I am not getting timeout error its going to else condition
Response response = null;
try {
response = client.getResponse(URI.create(uri), headers, reuest);
} catch (Exception ex) {
if(ex instanceof SocketTimeoutException){
throw new ExternalClientException(Errors.TIMEOUT_ERROR);
} else {
throw new ExternalClientException(Errors.UNEXPECTED_ERROR);
}
}
You need to catch feign.RetryableException instead of SocketTimeoutException.
javadoc
Please send all code of class. You need to provide class of "client" variable so people can help.
One more thing, instead of checking instance of exception in "catch" clause, you should use multiple catching like this:
Response response = null;
try {
response = client.getResponse(URI.create(uri), headers, reuest);
} catch (SocketTimeoutException ex1) {
throw new ExternalClientException(Errors.TIMEOUT_ERROR, ex1);
} catch (Exception ex2) {
throw new ExternalClientException(Errors.UNEXPECTED_ERROR, ex2);
}

ElasticSearch Rest API in JAVA

I am trying to write a simple JAVA REST Client through which I want to PUT/GET elasticsearch document information.
PUT is working fine, my json data got added into index.
But the problem is GET, Response Code is 200, but it is not returning any data.
Can anyone please help.
public static String httpGet(String resturl){
String output = null;
try {
URL url = new URL(resturl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
//System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
I am calling as
RestClient.httpGet("http://localhost:9200/gabsindex/employee/_search")
You println call is currently commented out. If you uncomment it, you'll get the response from the server on one single line, something like
{"took":50,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":7056,"max_score":1.0,"hits":[...]}}
If you are trying to follow this approach educationally, this can be ok. Remember, nonetheless, that there are a number of libraries that can be used exactly for this use. You should check out the clients page.

Resources