-3

I am getting NullPointerException and I don't know why it is being here.

TemplateController.java

    @Controller
    @SessionAttributes({"user","initiative"})
    public class TemplateController {
        @Autowired
        private TaskService taskService;

        @Autowired
        private InitiativeService initiativeService;

        @RequestMapping(value = "/addtasktemplate/{taskTemplateObjectId}/{initiativeId}", method = RequestMethod.POST)
        public
        @ResponseBody
        @Transactional(propagation = Propagation.REQUIRED)
        String addTaskTemplateUnderInitiative(@PathVariable Integer taskTemplateObjectId, @PathVariable Integer initiativeId, ModelMap model){
            User user = (User) model.get("user");
            if(user!=null){
                Initiative initiative = (Initiative) model.get("initiative");

                Boolean check = taskService.addTask(initiative.getInitiativeId(), taskTemplateObjectId, user);  //TemplateController.java:67

                if(check){
                    return "successfull";
                }else{
                    return "failure";
                }
            }
            return "Not Eligible";
        }

    }

The function addTask called in function addTaskTemplateUnderInitiative is defined in TaskDaoImpl.java, whose code is: -

TaskDaoImpl.java

    @Repository("TaskDao")
    public class TaskDaoImpl implements TaskDao {

        private EntityManager entitymanager;

        @Autowired
        private ObjectInitiativeDao objectInitiativeDao;

        @Autowired
        private ActionListDao actionListDao;

        @PersistenceContext
        public void setEntitymanager(EntityManager entitymanager) {
            this.entitymanager = entitymanager;
        }

        @Override
        @Transactional(readOnly = false)
        public Boolean createTask(Task task) {
            try{
                entitymanager.persist(task);
                return true;
            }catch(Exception e){
                return false;
            }
        }

        @Override
        @Transactional
        public Boolean addTask(Integer initiativeId, Integer taskTemplateObjectId, User user) {

            ObjectInitiative objectInitiative = objectInitiativeDao.getObjectInitiativeByObjectId(taskTemplateObjectId, false);
            Task task = getTaskById(objectInitiative.getRespectiveId());

            ObjectInitiative newObject = new ObjectInitiative();
            /* Values set for newObject*/
            objectInitiativeDao.createObjectInitiative(newObject);

            Task newTask = new Task();
            /* Values set for newTask */
            createTask(newTask);

            for(ActionList actionList : task.getActionLists()){
                actionListDao.addActionList(newTask.getTaskId(), actionList.getObjectInitiative().getObjectId(), user);   //TaskDaoImpl.java:105
            }

            return true;
        }

        @Override
        @Transactional
        public Task getTaskById(Integer taskId) {
            Task task = entitymanager.find(Task.class, taskId);

            for(ActionList actionList : task.getActionLists()){   //TaskDaoImpl.java:126
                Hibernate.initialize(actionList);
            }
            return task;
        }

    }

Here, again function addActionList called in function addTask is defined in ActionListDaoImpl.java, whose code is: -

ActionListDaoImpl.java

    @Repository("ActionListDao")
    public class ActionListDaoImpl implements ActionListDao {

        private final Logger logger=LoggerFactory.getLogger(getClass());

        private EntityManager entitymanager;

        @Autowired
        private ObjectInitiativeDao objectInitiativeDao;

        @Autowired
        private TaskDao taskDao;

        @Autowired
        private ActionDao actionDao;

        @PersistenceContext
        public void setEntitymanager(EntityManager entitymanager) {
            this.entitymanager = entitymanager;
        }

        @Override
        @Transactional(readOnly = false)
        public Boolean createActionList(ActionList actionList) {
            try {
                entitymanager.persist(actionList);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        @Transactional
        public Boolean addActionList(Integer taskId, Integer actionListTemplateObjectId, User user) {

            ObjectInitiative objectInitiative = objectInitiativeDao.getObjectInitiativeByObjectId(actionListTemplateObjectId, false);
            ActionList actionList = getActionListById(objectInitiative.getRespectiveId());
            Task task = taskDao.getTaskById(taskId);   //ActionListDaoImpl.java:67

            ObjectInitiative newObject = new ObjectInitiative();
            /* Values set for newObject */
            objectInitiativeDao.createObjectInitiative(newObject);

            ActionList newActionList = new ActionList();
            /* Values set for newActionList */
            createActionList(newActionList);

            return true;

        }

        @Override
        @Transactional(readOnly = true)
        public ActionList getActionListById(Integer actionListId) {
            return entitymanager.find(ActionList.class, actionListId);
        }
    }

And, the domains of Task, ObjectInitiative and ActionList are: -

Task.java

    @Entity
    @Table(name = "task")
    @Access(AccessType.FIELD)
    public class Task {

        @Id
        @GenericGenerator(name = "task", strategy = "increment")
        @GeneratedValue(generator = "task")
        private Integer taskId;

        @Column
        private Integer objectId;

        @Column
        private Integer initiativeId;

        @OneToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "initiativeId", insertable = false, updatable = false, unique = true, nullable = false)
        private Initiative initiative;

        @OneToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "objectId", insertable = false, updatable = false, unique = true, nullable = false)
        private ObjectInitiative objectInitiative;

        @OneToMany(mappedBy = "taskId", fetch = FetchType.LAZY)
        private List<ActionList> actionLists;

        /* Getters, Setters and toString() */

    }

ActionList.java

    @Entity
    @Table(name = "actionlist")
    @Access(AccessType.FIELD)
    public class ActionList {

        @Id
        @GenericGenerator(name = "actionlist", strategy = "increment")
        @GeneratedValue(generator = "actionlist")
        private Integer actionListId;

        @Column
        private Integer objectId;

        @Column
        private Integer taskId;

        @OneToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "taskId", insertable = false, updatable = false, unique = true, nullable = false)
        private Task task;

        @OneToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "objectId", insertable = false, updatable = false, unique = true, nullable = false)
        private ObjectInitiative objectInitiative;

        /* Getters, Setters and toString() */
    }

ObjectInitiative.java

    @Entity
    @Table(name = "objectinitiative")
    @Access(AccessType.FIELD)
    public class ObjectInitiative {

        @Id
        @GenericGenerator(name = "objectinitiative", strategy = "increment")
        @GeneratedValue(generator = "objectinitiative")
        private Integer objectId;

        /* Getters, Setters and toString() */
    }

Now, I am getting NullPointerException in 'TaskDaoImpl.java' and then in 'ActionListDaoImpl.java' as you can see in log: -

            java.lang.NullPointerException
        at org.abc.def.dao.TaskDaoImpl.getTaskById(TaskDaoImpl.java:126)
        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:483)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        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:204)
        at com.sun.proxy.$Proxy687.getTaskById(Unknown Source)
        at org.abc.def.dao.ActionListDaoImpl.addActionList(ActionListDaoImpl.java:67)
        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:483)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        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:204)
        at com.sun.proxy.$Proxy686.addActionList(Unknown Source)
        at org.abc.def.dao.TaskDaoImpl.addTask(TaskDaoImpl.java:105)
        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:483)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        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:204)
        at com.sun.proxy.$Proxy687.addTask(Unknown Source)
        at org.abc.def.service.TaskServiceImpl.addTask(TaskServiceImpl.java:28)
        at org.abc.def.controller.TemplateController.addTaskTemplateUnderInitiative(TemplateController.java:67)
        at org.abc.def.controller.TemplateController$$FastClassByCGLIB$$4c5d2b90.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
        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.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
        at org.abc.def.web.controller.sim.TemplateController$$EnhancerByCGLIB$$7697f039_2.addTaskTemplateUnderInitiative(<generated>)
        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:483)
        at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
        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:745)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
        at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

Here, as you can see that I am using existing task template, not creating new task. Exception occurs when I fetch the task, but this does not occur when I create a new task (not using existing task template) and then fetch it.

This is all over. I can't get that how to resolve this problem.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • downvote - "Please debug my code" question – Evgeniy Aug 23 '14 at 07:28
  • 1
    Ask yourself: what could possibly be null and thus cause a NPE at line 126 of TaskDaoImpl.java? Not being able to diagnose a NPE and using Spring and Hibernate is like trying to pilot a Boeing when you haven't even learnt to walk yet. – JB Nizet Aug 23 '14 at 07:34
  • @JBNizet If I can not resolve this one, it means you can definitely resolve it. – Prabhat Swami Aug 23 '14 at 07:42
  • Ask yourself: what could possibly be null and thus cause a NPE at line 126 of TaskDaoImpl.java? There are only 2 possibilities. Check each of them, and then ask yourself why it is so. – JB Nizet Aug 23 '14 at 07:46
  • http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – Raedwald Aug 23 '14 at 07:57

2 Answers2

0

I think you should check Null for initiative object of the method addTaskTemplateUnderInitiative in TemplateController.java

@Controller
@SessionAttributes({"user","initiative"})
public class TemplateController {
    @Autowired
    private TaskService taskService;

    @Autowired
    private InitiativeService initiativeService;

    @RequestMapping(value = "/addtasktemplate/{taskTemplateObjectId}/{initiativeId}", method = RequestMethod.POST)
    public
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED)
    String addTaskTemplateUnderInitiative(@PathVariable Integer taskTemplateObjectId, @PathVariable Integer initiativeId, ModelMap model){
        User user = (User) model.get("user");
        if(user!=null){
            Initiative initiative = (Initiative) model.get("initiative");

            if(initiative != null){

                Boolean check = taskService.addTask(initiative.getInitiativeId(), taskTemplateObjectId, user);
                model.addAttribute("initiative", initiativeService.getInitiativeByInitiativeId(initiativeId));

                if(check){
                    return "successfull";
                }else{
                    return "failure";
                }
            } else return "Falid";
        }
        return "Not Eligible";
    }

}
mizanurahma
  • 139
  • 5
0

did you check for below code.

for(ActionList actionList : task.getActionLists()){   //TaskDaoImpl.java:126
                Hibernate.initialize(actionList);
            }

1.) Either your task is null.

2.) If task is not null, task.getActionLists() is null then. For each will give error here

The above could be that there is no mapping data found or somehow Hibernate is not able to fetch the list. Is the list Lazy, if yes then try intializing before for loop. You can make the actionList inside Task as Eager, and it should work perfectly fine, but that is not the solution to your problem.

Issue is mainly because actionList is not able get intialized properly.

Hibernate.initialize(task.getActionLists());
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • I already have tried this one but this is not working. Task is not null and definitely task.getActionLists() will be null as task is recently created and no actionList is added under that task. I am surprised that when I create a task separately (as usual have no actionList) and fetch it, then NPE does not occur. This one is the problem, hope you got it. – Prabhat Swami Aug 23 '14 at 08:51