java.util.ConcurrentModificationException on cloneEntity - java

I wrote a custom strategy in order to clone an entity TrainTimetable with its collection of slots.
Below an extract of the model :
Entity('TrainTimetable') {
list 'slots' , ref:'Slot', composition:true
}
Entity('Slot') {
reference 'trainTimetable' , ref:'TrainTimetable', reverse:'TrainTimetable-slots'
}
And below the method :
package fr.yc.rail.backend;
import java.util.ArrayList;
import java.util.List;
import org.jspresso.framework.model.entity.IEntity;
import org.jspresso.framework.model.entity.IEntityFactory;
import org.jspresso.framework.model.entity.SmartEntityCloneFactory;
import fr.yc.rail.model.Slot;
import fr.yc.rail.model.TrainTimetable;
public class CloneTrainTimetableFactory extends SmartEntityCloneFactory {
#Override
public <E extends IEntity> E cloneEntity(E entityToClone,
IEntityFactory entityFactory) {
TrainTimetable clonedTrainTimetable = (TrainTimetable) super.cloneEntity(entityToClone, entityFactory);
TrainTimetable trainTimetableToClone = (TrainTimetable) entityToClone;
List<Slot> clonedSlots = new ArrayList<Slot>();
trainTimetableToClone.getSlots().each {
Slot clonedSlot = super.cloneEntity(it, entityFactory);
clonedSlots.add(clonedSlot);
}
clonedTrainTimetable.setSlots(clonedSlots);
return (E) clonedTrainTimetable;
}
}
When the method is called, the code below raises the ConcurrentModificationException error on the second iteration :
trainTimetableToClone.getSlots().each {
Slot clonedSlot = super.cloneEntity(it, entityFactory);
clonedSlots.add(clonedSlot);
}
Below the stack trace :
ERROR <2015-06-09 18:13:11,193> org.jspresso.framework.application.frontend.controller.AbstractFrontendController : An unexpected error occurred for user demo on session 4379dc1b.
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at org.hibernate.collection.internal.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:774)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1378)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1372)
at org.codehaus.groovy.runtime.dgm$149.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:271)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at fr.yc.rail.backend.CloneTrainTimetableFactory.cloneEntity(CloneTrainTimetableFactory.groovy:25)
at org.jspresso.framework.application.backend.action.CloneComponentCollectionAction.cloneElement(CloneComponentCollectionAction.java:61)
at org.jspresso.framework.application.backend.action.AbstractCloneCollectionAction.getAddedComponents(AbstractCloneCollectionAction.java:71)
at org.jspresso.framework.application.backend.action.AbstractAddCollectionToMasterAction.execute(AbstractAddCollectionToMasterAction.java:78)
at org.jspresso.framework.application.backend.AbstractBackendController.execute(AbstractBackendController.java:403)
at org.jspresso.framework.application.frontend.controller.AbstractFrontendController.executeBackend(AbstractFrontendController.java:1536)
at org.jspresso.framework.application.frontend.controller.AbstractFrontendController.execute(AbstractFrontendController.java:576)
at org.jspresso.framework.application.action.AbstractAction.execute(AbstractAction.java:114)
at org.jspresso.framework.application.frontend.controller.AbstractFrontendController.executeFrontend(AbstractFrontendController.java:1549)
at org.jspresso.framework.application.frontend.controller.AbstractFrontendController.execute(AbstractFrontendController.java:578)
at org.jspresso.framework.view.remote.RemoteActionFactory$ActionAdapter.actionPerformed(RemoteActionFactory.java:235)
at org.jspresso.framework.application.frontend.controller.remote.AbstractRemoteController.handleCommand(AbstractRemoteController.java:440)
at org.jspresso.framework.application.frontend.controller.remote.AbstractRemoteController.handleCommands(AbstractRemoteController.java:202)
at org.jspresso.framework.application.startup.remote.RemoteStartup.handleCommands(RemoteStartup.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.sf.qooxdoo.rpc.RemoteCallUtils.callCompatibleMethod(RemoteCallUtils.java:469)
at net.sf.qooxdoo.rpc.RpcServlet.handleRPC(RpcServlet.java:374)
at net.sf.qooxdoo.rpc.RpcServlet.doPost(RpcServlet.java:481)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.jspresso.framework.util.http.HttpRequestHolder.doFilter(HttpRequestHolder.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
The error means that I am iterating on a collection that is changing in size, but I don't know how to get rid of it.

You have a 1-N bi-directional association between TrainTimetable and Slot. This means that whenever you update one side of the association, Jspresso will take care of updating the other side in order to keep model consistency, e.g. :
if you set the trainTimetable property on a slot, the slot will be added to the reverse slots collection of the train timetable.
if you add a slot to the slotsproperty of a train timetable, then the trainTimetable reverse property of the added slot will be updated to the train timetable.
In the following code :
Slot clonedSlot = super.cloneEntity(it, entityFactory);
the clonedSlot will be added to the trainTimeTableToClone slots due to the rules explained before. So the iterated collection actually changes.
In order to fix the problem, making a copy of the collection before iterating it should be enough, i.e. :
trainTimetableToClone.getSlots().collect().each {

Related

java.lang.ClassCastException While Using Projection in hibernate 4

I am using hibernate to fetch only specific fields from and Entity. For that I am using Criteria API and using projections. I am getting ClassCastExcepiton when I try to traverse the list returned by the list() method of the Criteria API.
Please help me in finding out the missing of the below code.
#RequestMapping("/pResult")
public String retrieveLpnOnPagination(Model model) {
for (int i = 1; i <= 9; i += 3) {
List<MyLpn> lpns = lpnService.retrievePaginatedResult(i, 3,new String[]{"lpnId","status","whse"});
for (MyLpn lpn : lpns)
System.out.println(lpn.toString());
System.out.println();
}
return "home";
}
DaoImpl method
public List<MyLpn> retrievePResult(int i, int j, String[] projectionFields) {
Session currentSession = sessionFactory.getCurrentSession();
Criteria createCriteria = currentSession.createCriteria(MyLpn.class);
ProjectionList projectionList = Projections.projectionList();
for (String field : projectionFields)
projectionList.add(Projections.property(field));
createCriteria.setProjection(projectionList);
List<MyLpn> list = createCriteria.list();
for (MyLpn lpn : list)
System.out.println(lpn.toString());
return list;
}
Exception
SEVERE: Servlet.service() for servlet [spring] in context with path [/MyW2014] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.w.model.MyLpn] with root cause
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.w.model.MyLpn
at com.wmos.dao.LpnDaoImpl.retrievePResult(LpnDaoImpl.java:88)
at com.w.service.LpnService.retrievePaginatedResult(LpnService.java:43)
at com.wmos.service.LpnService$$FastClassBySpringCGLIB$$4e814eab.invoke(<generated>)
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 com.wmos.service.LpnService$$EnhancerBySpringCGLIB$$bec224d4.retrievePaginatedResult(<generated>)
at com.wmos.controller.LpnController.retrieveLpnOnPagination(LpnController.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1136)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Thank you.
Try this
createCriteria.setResultTransformer(Transformers.aliasToBean(MyLpn.class));
List<MyLpn> list = createCriteria.list();

Cassandra Exception : #Table annotation not found on the class

I am new to cassandra database. I am trying to map a table to a java class.
My java class:
#Table("user")
public class User implements Serializable
{
#PrimaryKey
#Column(value = "id")
private int id;
#Column(value = "first_name")
private String firstName;
//setters and getters
}
Dao class:
public class UserDaoImpl {
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect("agtr_api");
MappingManager manager = new MappingManager(session);
Mapper<User> mapper = manager.mapper(User.class);
public User getUserById(int id){
User u = mapper.get(id);
return u;
}
}
When i run my application on server, It throws following exception:
SEVERE: Servlet.service() for servlet [spring] in context with path
[/aggregator-api] threw exception [Request processing failed; nested
exception is java.lang.IllegalArgumentException: #Table annotation was
not found on class com.data.User] with root cause
java.lang.IllegalArgumentException: #Table annotation was not found on
class com.data.User at
com.datastax.driver.mapping.AnnotationChecks.getTypeAnnotation(AnnotationChecks.java:43)
at
com.datastax.driver.mapping.AnnotationParser.parseEntity(AnnotationParser.java:76)
at
com.datastax.driver.mapping.MappingManager.getMapper(MappingManager.java:226)
at
com.datastax.driver.mapping.MappingManager.mapper(MappingManager.java:182)
at com.etl.aapi.common.dao.UserDaoImpl.(UserDaoImpl.java:19)
at
com.etl.aapi.common.controller.UserController.a(UserController.java:13)
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:221)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
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:832)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
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)
You can declare also you keyspace name. Try to use the complete syntax as below:
#Table(keyspace = "yourKeyspace", name = "yourTable")
The "#Annotation" error is misleading as you rightly guess and the exception does not directly tell what is the actual error. The underlying problem would always be in your Domain/Model class fields/columns definition such as column name missing, miss match etc, always watch out your Domain/Model class.
Besides, If you use Achilles library and #Table annotation from Achilles, you will not get correct error. As a workaround you can additionally use #Table annotation from DataStax driver which will try to throw you more details in the exception stack trace.

How to handle System.IO.IOException in Java

I'm using jni4net to bridge between Java program & a C# dll file which controls a hardware device. The device and PC are connected by a network cable and I'm trying to handle the cable unplugged case while Java program is retrieving data from the hardware device via C# dll, frequently.
When unplugged the network cable, following exception is thrown by C# which is to be caught at Java side. But it's not happening even though I've tried catching with 'Exception', 'system.io.IOException' or 'Throwable' in Java.
What am I doing wrong? Is there other way around? Any input would be greatly appreciated. Thanks!
Code:
MyHardware f = new MyHardware();
f.Connection(DEVICE_IP);
if (f.ConnectionStatus()) {
try {
net.sf.jni4net.Ref<java.lang.String> refAmount = new Ref<String>(null),
refVolume = new Ref<String>(null), refPpu = new Ref<String>(null);
net.sf.jni4net.Ref<java.lang.Integer> refGrade = new Ref<Integer>(null),
refHose = new Ref<Integer>(hoseId);
f.GetLastSnapshot(Id, refAmount, refVolume, refPpu, refGrade, refHose);
} catch (Throwable t) {
logger.error("Error connecting device.");
}
}
Exception:
System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at MyHardwareThread.send(MyHardwareMsg msg)
at MyHardwareThread.sendReceive(MyHardwareMsg msg)
at MyHardwareClass.MyHardware.GetLastSnapshot(Int32 p_iPump, String& p_strAmount, String& p_strVolume, String& p_strPPU, Int32& p_iGrade, Int32& p_iHose)
at MyHardwareClass.__MyHardware.GetLastSnapshot20(IntPtr __envp, JniLocalHandle __obj, Int32 p_iPump, JniLocalHandle p_strAmount, JniLocalHandle p_strVolume, JniLocalHandle p_strPPU, JniLocalHandle p_iGrade, JniLocalHandle p_iHose)
at MyHardwareclass.MyHardware.GetLastSnapshot(Native Method)
at com.mno.MyHardware.pos.controller.pos.PosController.getLastSnapshot(PosController.java:774)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Unhandled Exception: System.InvalidOperationException: Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint. BeginConnect must be called on a thread that won't exit until the operation has been completed.
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
at MyHardwareThread.connect()
at MyHardwareThread.mainLoop()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

NullPointerException unstoppable

I am currently working on a small addresstable with vaadin, just to get to know vaadin a little. I have run into a problem, where I want to sort the entries of my table manually. The problem is, that I get a NullPointerException when i try to do this:
item.getItemProperty(Columns.NAME).getValue()
I have tried a few things here. I checked item and item isn't null, neither is item.getItemProperty(Columns.NAME) null. So when I try to make an if I still get a NullPointerException
if(item.getItemProperty(Columns.NAME).getValue() == null){}
The value is null and I understand that, but I want to give this value to an other item and I have no idea how to.
SEVERE: Servlet.service() for servlet [com.example.addresstable.AddresstableUI$Servlet] in context with path [/Addresstable] threw exception [com.vaadin.server.ServiceException: java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.vaadin.data.util.IndexedContainer$IndexedContainerProperty.getValue(IndexedContainer.java:898)
at com.example.addresstable.AddressTable.addAddressToTable(AddressTable.java:114)
at com.example.addresstable.AddresstableUI.init(AddresstableUI.java:26)
at com.vaadin.ui.UI.doInit(UI.java:639)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:222)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1402)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:305)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
IndexedContainer's Items are IndexedContainerItem.
When call it's getItemProperty the result is never null:
#Override
public Property getItemProperty(Object id) {
return new IndexedContainerProperty(itemId, id);
}
But when you call Property's getValue it may be null if there is no itemId or propertyId:
#Override
public T getValue() {
return (T) items.get(itemId).get(propertyId);
}
Probably it is a Vaadin bug: link
EDIT
If you want to check the container contains the item, you can do this:
public class MyIndexedContainer extends IndexedContainer {
#Override
public Item getUnfilteredItem(Object itemId) { // make it public
return super.getUnfilteredItem(itemId);
}
}
then
Table table = new Table();
MyIndexedContainer mic = new MyIndexedContainer();
table.setContainerDataSource(mic);
//...
// check that the container contains the item
if (mic.getUnfilteredItem(item) != null) {
//...
}

how to handle NullPointerException on ArrayList

My code is throwing a NullPointerException, when i select an null Arraylist
this is the stack trace:
javax.el.ELException: /jsf/projet/phases/viewPhases.xhtml #27,170 value="#{PhaseComponent.listPhaseTaches(PhaseComponent.phase.idphase)}": java.lang.NullPointerException
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:111)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:554)
at org.primefaces.component.datatable.DataTable.getValue(DataTable.java:910)
at org.primefaces.component.api.UIData.getDataModel(UIData.java:615)
at javax.faces.component.UIData.getRowCount(UIData.java:339)
at org.primefaces.component.api.UIData.calculateFirst(UIData.java:161)
at org.primefaces.component.datatable.DataTableRenderer.preEncode(DataTableRenderer.java:107)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:81)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:879)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:74)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:57)
at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:204)
at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:121)
at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:58)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:879)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:164)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:849)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:70)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:57)
at org.primefaces.component.layout.LayoutUnitRenderer.encodeEnd(LayoutUnitRenderer.java:51)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:879)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:389)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:309)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at com.gestion.projet.web.jsf.PhaseComponentImpl.listPhaseTaches(PhaseComponentImpl.java:268)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy56.listPhaseTaches(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy9.listPhaseTaches(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:183)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at com.sun.el.parser.AstValue.getValue(AstValue.java:111)
at com.sun.el.parser.AstValue.getValue(AstValue.java:163)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:106)
... 56 more
an this is the method that i want to handle the exception it returns an ArrayList :
public List<Tache> listPhaseTaches(Integer idphaseKey) {
return new java.util.ArrayList<Tache>(phaseDAO.findPhaseByPrimaryKey(idphaseKey).getTaches());
}
The problem is I don't know what i should do for handling NullPointerException for a method that returns an Arraylist
List list = someMethod();
if(list!=null){
//your logic
}
else{
return new List<T>();
}
Make sure that you return not-null value
you can handle this like
List list = someMethod();
if(list!=null){
//your logic
}
else{
}
your error lies either at phaseDAO is null or phaseDAO.findPhaseByPrimaryKey(idphaseKey) this returns null OR phaseDAO.findPhaseByPrimaryKey(idphaseKey).getTaches() this returns null
Use this >>
public List<Tache> listPhaseTaches(Integer idphaseKey) {
if(phaseDAO!=null){
if(phaseDAO.findPhaseByPrimaryKey(idphaseKey)!=null){
if(phaseDAO.findPhaseByPrimaryKey(idphaseKey)!=null){
return new ArrayList(phaseDAO.findPhaseByPrimaryKey(idphaseKey));
}
}
}
return null;
}
Provide the following null checks:
phaseDAO != null
phaseDAO.findPhaseByPrimaryKey(idphaseKey) != null
phaseDAO.findPhaseByPrimaryKey(idphaseKey).getTaches() != null

Categories

Resources