Spring RESTful, error returning JSON - java

i'm encountering an error while producing JSON from DAO, here is my code
Controller
#RequestMapping(value="/findAdpId/", method=RequestMethod.POST , consumes = "application/json", produces = "application/json")
public #ResponseBody AllCustomerHist findAdpId(#RequestBody AllCustomerHist customer){
String customerId = customer.getCustomerId();
String srctable = customer.getSrctable();
System.out.println("customer ID = "+customerId);
System.out.println("srctable = "+srctable);
List<AllCustomerHist> adpcust = allCustomerHistService.findAdpId(customerId, srctable);
return (AllCustomerHist) adpcust;
}
DAO Class
#SuppressWarnings("unchecked")
public List<AllCustomerHist> findAdpId(String customerId, String srctable) {
// TODO Auto-generated method stub
Criteria criteria = getSession().createCriteria(AllCustomerHist.class)
.setProjection(Projections.projectionList()
.add(Projections.property("adpId"), "adpId"))
.add(Restrictions.eq("customerId", customerId))
.add(Restrictions.eq("srctable", srctable));
return (List<AllCustomerHist>)criteria.list();
}
what i want is, when retrieving JSON like
{
"customerId":"11",
"srctable":"transaction"
}
my DAO class will produce
{
"adpId":["abcd123","defw123"]
}
this is the error log
Exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is java.lang.ClassCastException:
java.util.ArrayList cannot be cast to
com.astra.adp.model.AllCustomerHist
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.ClassCastException: java.util.ArrayList cannot be cast to
com.astra.adp.model.AllCustomerHist
com.astra.adp.controller.CustomerController.findAdpId(CustomerController.java:73)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server
logs.
thank you for the helps!

Related

Ljava.lang.Object; cannot be cast to com.entity.MechanicEntity

I am getting the following error "Ljava.lang.Object; cannot be cast to com.entity.MechanicEntity" when trying to fetch the list of mechanic rows from database and pass to the jsp page.
Mechanic Entity
#Entity
#Table(name="Mechanic")
public class MechanicEntity {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
int mechanicId;
String mechanicType;
int numberOfVehicles;
public int getMechanicId() {
return mechanicId;
}
public void setMechanicId(int mechanicId) {
this.mechanicId = mechanicId;
}
public String getMechanicType() {
return mechanicType;
}
public void setMechanicType(String mechanicType) {
this.mechanicType = mechanicType;
}
public int getNumberOfVehicles() {
return numberOfVehicles;
}
public void setNumberOfVehicles(int numberOfVehicles) {
this.numberOfVehicles = numberOfVehicles;
}
}
RegisterController.java
...
RegisterService service;
#ModelAttribute("MechList")
public Map<Integer,Integer> populateMechId()throws Exception {
List<Mechanic> allMech = service.getAllMechanic();
Map<Integer,Integer> MechanicMap=new HashMap<Integer,Integer>();
for(Mechanic mechanic:allMech){
MechanicMap.put(mechanic.getMechanicId(),mechanic.getMechanicId());
}
return MechanicMap;
} ...
RegisterService.java
...
RegisterDAO dao;
public List<Mechanic> getAllMechanic() throws Exception
{
return dao.getAllMechanic();
}
...
RegisterDAO.java
public List<Mechanic> getAllMechanic() throws Exception
{
List<Mechanic> mlist=new ArrayList<Mechanic>();
Query q=em.createQuery("select m.mechanicId,m.mechanicType from MechanicEntity m");
List<MechanicEntity> l1=q.getResultList();
for(MechanicEntity m:l1)
{
Mechanic mechanic=new Mechanic();
mechanic.setMechanicId(m.getMechanicId());
mlist.add(mechanic);
}
return mlist;
}
registerVehicle.jsp
<form:form name="registerForm1" action="registerVehicle.htm" modelAttribute="serviceregister" method="GET" >
<form:select path="mechanicId">
<form:options items="${MechList}" />
</form:select>
</form:form>
Error:
Type Exception Report
Message org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.entity.MechanicEntity
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.entity.MechanicEntity
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:594)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:495)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.entity.MechanicEntity
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:750)
org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:720)
org.apache.jsp.index_jsp._jspService(index_jsp.java:92)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.entity.MechanicEntity
com.dao.RegisterDAO.getAllMechanic(RegisterDAO.java:19)
com.service.RegisterService.getAllMechanic(RegisterService.java:27)
com.controller.RegisterController.populateMechId(RegisterController.java:40)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:163)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:750)
org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:720)
org.apache.jsp.index_jsp._jspService(index_jsp.java:92)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Please help me rectify it, so the dropdown is displayed when the view loads.
Your code doesn't even compile because of:
Query q=em.createQuery("select m.mechanicId,m.mechanicType from MechanicEntity m");
List<MechanicEntity> l1=q.getResultList();
The problem is that getResultList() return a List<Object> instead of List< MechanicEntity>.
To make it work:
List<MechanicEntity> l1 = createQuery("select m from MechanicEntity m", MechanicEntity.class).getResultList();

Spring Hibernate Jpa error: root cause java.lang.IllegalArgumentException: Unknown parameter position: 1

Hi I am getting following error.
java.lang.IllegalArgumentException: Unknown parameter position: 1]
with root cause java.lang.IllegalArgumentException: Unknown parameter
position: 1 at
org.hibernate.query.internal.QueryParameterBindingsImpl.getBinding(QueryParameterBindingsImpl.java:240)
at
org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:503)
at
org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372)
at com.sun.proxy.$Proxy63.setParameter(Unknown Source) at
edu.zipcloud.cloudstreetmarket.core.daos.HistoricalIndexRepositoryImpl.findLastHistoric(HistoricalIndexRepositoryImpl.java:37)
at
edu.zipcloud.cloudstreetmarket.core.daos.HistoricalIndexRepositoryImpl.findLastIntraDay(HistoricalIndexRepositoryImpl.java:31)
at
edu.zipcloud.cloudstreetmarket.core.services.MarketServiceImpl.getLastDayIndexActivity(MarketServiceImpl.java:41)
at
edu.zipcloud.cloudstreetmarket.portal.controllers.DefaultController.fallBack(DefaultController.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
inside method findLastHistoric(HistoricalIndexRepositoryImpl.java:37)
class:
#Repository
public class HistoricalIndexRepositoryImpl implements HistoricalIndexRepository{
#PersistenceContext
private EntityManager em;
#Override
public Iterable<HistoricalIndex> findIntraDay(String code, Date of) {
TypedQuery<HistoricalIndex> sqlQuery = em.createQuery("from HistoricalIndex h where h.index.code = ? and h.fromDate >= ? and h.toDate <= ? ORDER BY h.toDate asc", HistoricalIndex.class);
sqlQuery.setParameter(1, code);
sqlQuery.setParameter(2, DateUtil.getStartOfDay(of));
sqlQuery.setParameter(3, DateUtil.getEndOfDay(of));
return sqlQuery.getResultList();
}
#Override
public Iterable<HistoricalIndex> findLastIntraDay(String code) {
return findIntraDay(code, findLastHistoric(code).getToDate());
}
#Override
public HistoricalIndex findLastHistoric(String code){
TypedQuery<HistoricalIndex> sqlQuery = em.createQuery("from HistoricalIndex h where h.index.code = ? ORDER BY h.toDate desc", HistoricalIndex.class);
sqlQuery.setParameter(1, code);
return sqlQuery.setMaxResults(1).getSingleResult();
}
}
Please help me to resolve this error. If you need other information, let me know.
Regards.
How about this?
TypedQuery<HistoricalIndex> sqlQuery = em.createQuery("from HistoricalIndex h where h.index.code = ?1 ORDER BY h.toDate desc", HistoricalIndex.class);
Check here section 5.3.2. Query creation

Spring JdbcTemplate butchUpdate UPDATE org.springframework.jdbc.BadSqlGrammarException:

I have started learning Spring MVC a few days ago and now I am trying to do a butchUpdate. I have found an article how to do it but I get an exception that is below.I am using HSQLDB in memory database.
Here is my code:
public void updateStockBatch(List<Product> allProducts, int addQuantity, int noOfUnits) {
String SQL = "UPDATE products SET UNITS_IN_STOCK = ? WHERE ID = ?";
jdbcTemplate.batchUpdate(SQL, new BatchPreparedStatementSetter() {
int batchSize = 0;
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
for (Product product : allProducts) {
if (product.getUnitsInStock() < noOfUnits) {
ps.setLong(1, product.getUnitsInStock() + addQuantity);
ps.setString(2, product.getProductId());
batchSize++;
}
}
}
#Override
public int getBatchSize() {
return batchSize;
}
});
}
Type Exception Report
Message Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE products SET UNITS_IN_STOCK = ? WHERE ID = ?]; nested exception is java.sql.SQLException: statement is not in batch mode
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE products SET UNITS_IN_STOCK = ? WHERE ID = ?]; nested exception is java.sql.SQLException: statement is not in batch mode
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE products SET UNITS_IN_STOCK =? WHERE ID = ?]; nested exception is java.sql.SQLException: statement is not in batch mode
org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:662)
org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:950)
com.packt.webstore.domain.repository.impl.InMemoryProductRepository.updateStockBatch(InMemoryProductRepository.java:53)
com.packt.webstore.domain.repository.impl.ProductProductServiceImpl.updateAllStock(ProductProductServiceImpl.java:30)
com.packt.webstore.controller.ProductController.updateStock(ProductController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.sql.SQLException: statement is not in batch mode
org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
org.hsqldb.jdbc.JDBCUtil.sqlExceptionSQL(Unknown Source)
org.hsqldb.jdbc.JDBCPreparedStatement.executeBatch(Unknown Source)
org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:966)
org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:950)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:662)
org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:950)
com.packt.webstore.domain.repository.impl.InMemoryProductRepository.updateStockBatch(InMemoryProductRepository.java:53)
com.packt.webstore.domain.repository.impl.ProductProductServiceImpl.updateAllStock(ProductProductServiceImpl.java:30)
com.packt.webstore.controller.ProductController.updateStock(ProductController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.hsqldb.HsqlException: statement is not in batch mode
org.hsqldb.error.Error.error(Unknown Source)
org.hsqldb.error.Error.error(Unknown Source)
org.hsqldb.jdbc.JDBCUtil.sqlExceptionSQL(Unknown Source)
org.hsqldb.jdbc.JDBCPreparedStatement.executeBatch(Unknown Source)
org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:966)
org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:950)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:662)
org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:950)
com.packt.webstore.domain.repository.impl.InMemoryProductRepository.updateStockBatch(InMemoryProductRepository.java:53)
com.packt.webstore.domain.repository.impl.ProductProductServiceImpl.updateAllStock(ProductProductServiceImpl.java:30)
com.packt.webstore.controller.ProductController.updateStock(ProductController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
You're misunderstanding the way this works. The principle of batchUpdate() is to execute the same parameterized SQL query N times.
The BatchPreparedStatementSetter is first called by JdbcTemplate to know the batch size. Suppose it returns 10. JdbcTemplate will then call setValues() 10 times (with 0, then 1, then 2, etc. until 9).
Your code returns 0 as batch size, which doesn't make sense, and its setValues method sets the same parameters several times on the same statement, which doesn't make sense either.
A correct implementation would be:
public void updateStockBatch(List<Product> allProducts, int addQuantity, int noOfUnits) {
String sql = "UPDATE products SET UNITS_IN_STOCK = ? WHERE ID = ?";
List<Product> productsToUpdate =
allProducts.stream()
.filter(p -> p.getUnitsInStock() < noOfUnits)
.collect(Collectors.toList());
if (!productsToUpdate.isEmpty()) {
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
#Override
public int getBatchSize() {
return productsToUpdate.size();
}
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Product product : productsToUpdate.get(i);
ps.setLong(1, product.getUnitsInStock() + addQuantity);
ps.setString(2, product.getProductId());
}
});
}
}

org.apache.commons.mail.EmailException: Missing final '#domain'( by: javax.mail.internet.AddressException: Missing final '#domain' in string ``1'')

I'm trying to use javamail in my web application.
MailService:
#Service
public class MailServiceImpl implements MailService {
Email email = new SimpleEmail();
private MailServiceImpl() {
email.setCharset("utf-8");
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("1", "1"));
email.setSSL(true);
}
#Override
public void sendMail(String to, String subject, String body) {
try {
email.setFrom("1");
email.setSubject(subject);
email.setMsg(body);
email.addTo(to);
email.send();
email.getToAddresses().clear();
} catch (EmailException e) {
e.printStackTrace();
}
}
}
Logs:
org.apache.commons.mail.EmailException: Missing final '#domain'
at org.apache.commons.mail.Email.createInternetAddress(Email.java:605)
at org.apache.commons.mail.Email.setFrom(Email.java:668)
at org.apache.commons.mail.Email.setFrom(Email.java:651)
at org.apache.commons.mail.Email.setFrom(Email.java:631)
at by.netcracker.artemyev.service.impl.MailServiceImpl.sendMail(MailServiceImpl.java:28)
at by.netcracker.artemyev.service.impl.UserServiceImpl.addUser(UserServiceImpl.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy39.addUser(Unknown Source)
at by.netcracker.artemyev.web.UserController.registrationUser(UserController.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1354)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.mail.internet.AddressException: Missing final '#domain' in string ``1''
at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:915)
at javax.mail.internet.InternetAddress.validate(InternetAddress.java:856)
at org.apache.commons.mail.Email.createInternetAddress(Email.java:601)
... 58 more
I eneter: artyomartemyev962015#gmail.com and then give: Missing final '#domain'.
What does it mean? Every recipient's address is valid and sender address is verified and valid.
Question: How fix?
The from address does not have a domain:
email.setFrom("1");
Use something that does have a domain as the from address:
email.setFrom("1#example.com");
It's necessary to check that there is no kind of space before the "#".

I can't find the result in lambda expression

I sended this json to my tomcat service
{
"room": "Platinum",
"products": [{
"name": "Agua",
"quantity": 2
}],
"observation": "",
"date": "2016-08-15 12:00:00",
"status": 0
}
This code consume my json and set data in DB.
#Transactional
#RequestMapping(value = "/get-order", method = RequestMethod.POST, produces = PRODUCES_JSON)
public ResponseEntity getOrder(#RequestBody String content)
throws ParseException, UnsupportedEncodingException {
try {
String result = java.net.URLDecoder.decode(content, "UTF-8");
JSONObject json = new JSONObject(result);
Order order = createOrder(json);
#SuppressWarnings("unchecked")
List products = em.createNamedQuery(Product.QUERY_LIST).getResultList();
JSONArray productsJsonArray = json.getJSONArray(JSON_PRODUCTS);
for (int i = 0; i product = products.stream().filter(p -> p.getName().equals(name)).findAny();
order.addProduct(product.get(), quantity);
}
em.persist(order);
return buildGetOrderResponse(order);
} catch (NoResultException e) {
LOGGER.error(e.getMessage(), e);
return buildErrorResponse(WebServiceError.NOT_FOUND);
}
}
When I running with debug, shows me the error in this line order.addProduct(product.get(), quantity);
but the code return this in log error:
ago 26, 2016 5:08:12 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/easy-coffee] threw exception [Request processing failed; nested exception is java.util.NoSuchElementException: No value present] with root cause
java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at br.com.fourward.easycoffee.webservices.ConsummationWebService.getOrder(ConsummationWebService.java:89)
at br.com.fourward.easycoffee.webservices.ConsummationWebService$$FastClassBySpringCGLIB$$afa221ad.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at br.com.fourward.easycoffee.webservices.ConsummationWebService$$EnhancerBySpringCGLIB$$60d13b8.getOrder()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I need a little help with this, I'm new in jpa ... thank you guys
According to the Java documentation, Optional.get() (that you use as parameter of addProduct method) returns a value or NoSuchElementException if there is no value. You should only call addProduct() if product.isPresent() returns true.

Categories