How to add new Obect inside List<EntityClass> - spring

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>.

Related

org.hibernate.MappingException: Could not locate CollectionPersister for role : com.jbk.Entity.Product.productName

`Whenever, I try to run below method it is giving above error
public static List<Product> productGettingWithSize(int size) {
Session session = factory.openSession();
List<Product> list = null;
try {
Criteria criteria = session.createCriteria(Product.class);
criteria.add(Restrictions.sizeEq("productName", size));
list = criteria.list();
if (list.isEmpty()) {
System.out.println("No Data Found..!!");
} else {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
So, here in this code in DB productName is REDMI so, I m passing 5 as an size but, I m not getting the expected output.
So could anyone help me regarding this code or Can any anyone Tell how to use Restrictions(Size), all method related to size or can anyone send me the documentation where it is been explained explicitly.
Thank You...!!!
Expecting a solution on This..!!`

Rest template exchange not accept ParameterizedTypeReference

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[]>>(){});

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

Does oracle physical connection impact performance while closing it

I am developing an application for my final year project, I need a quick clarification on java JDBC .. I am using Oracle physical connection(no connection pooling). When a user search in search criteria, the query execution is happening in 10 ms and returning the result set to UI is taking up to 1 minute. Code is been attached.
Connection con=null;
OracleConnection ocon = null;
ResultSet rs = null;
Gson gson = new Gson();
String gsonOrdrHeaderEntity="";
JSONObject searchObject = new JSONObject();
JSONObject returnSearchObject = new JSONObject();
CallableStatement callableStatement = null;
ArrayList<SearchEntity> searchArrayList = new ArrayList<>();
try{
con= DatasourceConfiguration.openConnection();
ocon = (OracleConnection)con.unwrap(OracleConnection.class);
callableStatement= con.prepareCall("call SEARCHPKG.QUERY(?,?,?,?,?)");
callableStatement.setString(1,entity.getSearch1());
callableStatement.setString(2,entity.getSearch2());
callableStatement.setString(3,entity.getSearch3());
callableStatement.setString(4,entity.getSearch4());
callableStatement.registerOutParameter(5, OracleTypes.CURSOR);
callableStatement.execute();
rs = ((OracleCallableStatement) callableStatement).getCursor(39);
if(rs != null)
while(rs.next()) {
OrderHeaderEntity searchEntity = new OrderHeaderEntity();
searchEntity.setSearch1(rs.getString(1));
searchEntity.setSearch2(rs.getString(3));
searchEntity.setSearch3(rs.getString(4));
searchEntity.setSearch4(rs.getString(5));
/**
* Description : Since there are will multiple order in a single search, we are adding the row to an array and iterating over it
*/
searchArrayList.add(searchEntity);
}
}catch(SQLException e){
logger.info("SQLException while performing search: "+e.getMessage());
throw e;
}catch(Exception e){
logger.info("Exception while performing search: "+e.getMessage());
}finally {
try {
if(rs != null) {rs.close();}
} catch (Exception e2) {
logger.info("Error while closing the search resultSet : "+e2.getMessage());
}
try {
if(callableStatement!=null) {callableStatement.close();}
} catch (Exception e2) {
logger.info("Error while closing the search callableStatment :"+e2.getMessage());
}
finally {
}
try {
if(con!=null) {con.close();}
} catch (Exception e2) {
logger.info("Error while the search connection :"+e2.getMessage());
}
}
}
/**
* #Description : mapping result set with JAVA object
*/
logger.info("Inside ProcedureCall >> search Proc>> converted to JSON successfully");
gsonOrdrHeaderEntity= gson.toJson(searchArrayList);
searchObject.put("order_header", gsonOrdrHeaderEntity);
returnSearchObject.put("status", "success");
returnSearchObject.put("message","Order Header Retrieved Successfully");
returnSearchObject.put("data", searchObject);
return returnSearchObject.toString();

Transform Optional String and return Date in Java 8?

I am currently parsing a nullable String to a Date. I try to use Optional to avoid using if statement. Here is what I have written so far :
Client client = new Client();
Optional.ofNullable(methodThatMayReturnStringOrNull())
.ifPresent((s) -> {
try {
client.setBirthDate(DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
Is it possible to transform this lambda so I can make it a method similar to the following but java 8 style?
private Date parse(String complexString) {
Date birthDate = null;
if (complexString != null) {
try {
birthDate = DateUtils.parseDate(
StringUtils.substring(complexString, 0, 10),
new String[]{"yyyy-MM-dd"});
} catch (final ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
}
return birthDate;
}
Not sure how far you want to go, but you can start with
Optional<Date> date = Optional.ofNullable(methodThatMayReturnStringOrNull())
.map((s) -> {
try {
return DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
You might also consider using flatMap instead of map and returning empty optional instead of throwing exception on error - depends on how you want to progress you flow.
On completely unrelated note, get rid of Date and use either joda or new java time classes ;)

Resources