5 Replies Latest reply on Jun 14, 2012 7:05 PM by swaminathan.bhaskar

    Programmatic interaction with Human Task

    swaminathan.bhaskar

      I am using JBPM 5.2 and am trying to programmatically intyeract with Human task. I just have one user task in my process.

       

      Here is my code:

                            
      public class sample06 {
           public static final String BPMN_RESOURCE = "sample06.bpmn";
           public static final String BPM_PROCESS   = "sample06";
           public static final String BPM_USER      = "joe";
           
           private static TaskServer taskServer = null;
           
           public static final void main(String[] args) {
                try {
                     setupDS();
                     setupTS();
                     
                     TaskClient taskClient = new TaskClient(new MinaTaskClientConnector("sample06", new MinaTaskClientHandler(SystemEventListenerFactory.getSystemEventListener())));
                     taskClient.connect("127.0.0.1", 9123);
                     
                     // Setup JPA persistence
                     EntityManagerFactory emfJBPM = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa");
                     
                     Environment env = KnowledgeBaseFactory.newEnvironment();
                     env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emfJBPM);
                     env.set(EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager());
                     
                     // Load and setup the BPM process
                     KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
                     kbuilder.add(ResourceFactory.newClassPathResource(BPMN_RESOURCE), ResourceType.BPMN2);
                     
                     // Do we have any errors ?
                   if (kbuilder.hasErrors()) {
                       if (kbuilder.getErrors().size() > 0) {
                           for (KnowledgeBuilderError error : kbuilder.getErrors()) {
                               System.out.printf("Error building KnowledgeBase: %s\n", error.getMessage());
                           }
                       }
                       throw new RuntimeException("Error building KnowledgeBase");
                   }
                     
                     KnowledgeBase kbase = kbuilder.newKnowledgeBase();
                     
                     StatefulKnowledgeSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
                     
                     ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new WSHumanTaskHandler());
                     // ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new CommandBasedWSHumanTaskHandler(ksession));
                          
                     System.out.printf("\n-----> Session ID: %d\n", ksession.getId());
                          
                     // Create the process instance
                     ProcessInstance processInstance = ksession.createProcessInstance(BPM_PROCESS, null);
                          
                     System.out.printf("\n-----> Starting new Business process %s \n", processInstance.getProcessId(), processInstance.getId());
                          
                     // Start the BPM process
                     ksession.startProcessInstance(processInstance.getId());
                     
                     List tasks = null;
                     
                     // Use task client to fetch tasks for the owner
                     {
                          BlockingTaskSummaryResponseHandler summaryHandler = new BlockingTaskSummaryResponseHandler();
                          taskClient.getTasksAssignedAsPotentialOwner(BPM_USER, null, summaryHandler);
                          summaryHandler.waitTillDone(1000);
                          tasks = summaryHandler.getResults();
                     }
                     
                     for (TaskSummary task : tasks) {
                          long taskId = task.getId();
                          
                          String taskName = task.getName();
                          
                          // Claim the task
                          {
                               BlockingTaskOperationResponseHandler claimHandler = new BlockingTaskOperationResponseHandler();
                               taskClient.claim(taskId, BPM_USER, claimHandler);
                               claimHandler.waitTillDone(1000);
                               
                               System.out.printf("\n-----> Task %s <%d> claimed\n", taskName, taskId);
                          }
                          
                          // Start the task
                          {
                               BlockingTaskOperationResponseHandler startHandler = new BlockingTaskOperationResponseHandler();
                               taskClient.start(taskId, BPM_USER, startHandler);
                               startHandler.waitTillDone(1000);
                               
                               System.out.printf("\n-----> Task %s <%d> started\n", taskName, taskId);
                          }
                          
                          // Complete the task
                          {
                               BlockingTaskOperationResponseHandler completeHandler = new BlockingTaskOperationResponseHandler();
                               taskClient.complete(taskId, BPM_USER, null, completeHandler);
                               completeHandler.waitTillDone(1000);
                               
                               System.out.printf("\n-----> Task %s <%d> completed\n", taskName, taskId);
                          }
                     }
                          
                     // Did the process instance complete successfully ?
                     if (processInstance.getState() == ProcessInstance.STATE_COMPLETED) {
                          System.out.printf("\n-----> Business process %s  successfully completed\n", processInstance.getProcessId(), processInstance.getId());
                     }
                     
                     taskClient.disconnect();
                     
                     taskServer.stop();
                }
                catch (Exception ex) {
                     ex.printStackTrace(System.err);
                     System.exit(1);
                }
                
                System.exit(0);
           }
           
           public static void setupDS() throws Exception {
                // Setup Datasource
                PoolingDataSource mysqlDS = new PoolingDataSource();
                mysqlDS.setUniqueName("jdbc/MySQL-DS");
                mysqlDS.setClassName("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");
                mysqlDS.setMaxPoolSize(3);
                mysqlDS.setAllowLocalTransactions(true);
                mysqlDS.getDriverProperties().put("user", "*****");
                mysqlDS.getDriverProperties().put("password", "*****");
                mysqlDS.getDriverProperties().put("URL", "jdbc:mysql://localhost:3306/mytestdb");
                mysqlDS.init();
           }
           
           public static void setupTS() throws Exception {
                // Setup Task persistence
                EntityManagerFactory emfTASK = Persistence.createEntityManagerFactory("org.jbpm.task");
                
                // Setup Human Task Service
                
                System.out.printf("\n-----> Ready to start Mina Task service .....\n");
                
                TaskService taskService = new TaskService(emfTASK, SystemEventListenerFactory.getSystemEventListener());
                TaskServiceSession taskSession = taskService.createSession();
                taskSession.addUser(new User(BPM_USER));
                taskServer = new MinaTaskServer(taskService);
                Thread thread = new Thread(taskServer);
                thread.start();
                while (!taskServer.isRunning()) {
                     System.out.print(".");
                     Thread.sleep(50);
                }
                System.out.print("Mina Task service started successfully !!!!!\n");
           }
      }
      

       

      When I run the code, encounter the following exception:

      14/06 16:49:24,245[NioProcessor-4] ERROR hibernate.util.JDBCExceptionReporter.logExceptions  - Cannot add or update a child row: a foreign key constraint fails (`mytestdb`.`peopleassignments_bas`, CONSTRAINT `FK9D8CF4EC2C122ED2` FOREIGN KEY (`entity_id`) REFERENCES `organizationalentity` (`id`))
      14/06 16:49:24,245[NioProcessor-4] ERROR event.def.AbstractFlushingEventListener.performExecutions  - Could not synchronize database state with session
      org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
              at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
              at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
              at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
              at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
              at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
              at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
              at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1141)
              at org.hibernate.action.CollectionRecreateAction.execute(CollectionRecreateAction.java:58)
              at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
              at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
              at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:171)
              at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
              at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
              at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
              at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
              at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
              at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
              at org.jbpm.task.service.TaskServiceSession.doOperationInTransaction(TaskServiceSession.java:971)
              at org.jbpm.task.service.TaskServiceSession.addTask(TaskServiceSession.java:171)
              at org.jbpm.task.service.TaskServerHandler.messageReceived(TaskServerHandler.java:109)
              at org.jbpm.task.service.mina.MinaTaskServerHandler.messageReceived(MinaTaskServerHandler.java:41)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain$TailFilter.messageReceived(DefaultIoFilterChain.java:716)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:46)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:796)
              at org.apache.mina.filter.codec.ProtocolCodecFilter$ProtocolDecoderOutputImpl.flush(ProtocolCodecFilter.java:427)
              at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:245)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:46)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:796)
              at org.apache.mina.filter.logging.LoggingFilter.messageReceived(LoggingFilter.java:177)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:46)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:796)
              at org.apache.mina.core.filterchain.IoFilterAdapter.messageReceived(IoFilterAdapter.java:119)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434)
              at org.apache.mina.core.filterchain.DefaultIoFilterChain.fireMessageReceived(DefaultIoFilterChain.java:426)
              at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:692)
              at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:645)
              at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:634)
              at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$400(AbstractPollingIoProcessor.java:66)
              at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1078)
              at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64)
              at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
              at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
              at java.lang.Thread.run(Unknown Source)
      

       

      Any ideas ? Any help appreciated.

        • 1. Re: Programmatic interaction with Human Task
          salaboy21

          DId you set up an "Administrator" user? an Administrator user is required.

          You need to do:

          taskSession.addUser(new User("Administrator"));

          Cheers

          1 of 1 people found this helpful
          • 2. Re: Programmatic interaction with Human Task
            swaminathan.bhaskar

            Thanks Mauricio ... So adding the Adminstrator took care of the exception. I dont see any tasks being processed ... I would have assumed it would go through the claim, start and complete steps but I dont see any summary of tasks coming back

             

                           
                           List tasks = null;
                           
                           // Use task client to fetch tasks for the owner
                           {
                                BlockingTaskSummaryResponseHandler summaryHandler = new BlockingTaskSummaryResponseHandler();
                                taskClient.getTasksAssignedAsPotentialOwner(BPM_USER, null, summaryHandler);
                                summaryHandler.waitTillDone(5000);
                                tasks = summaryHandler.getResults();
                           }
                           
                           System.out.printf("\n-----> Tasks size = %d\n", tasks.size());
            

             

            -----> Tasks size = 0

             

            Am I doing something wrong ?

            • 3. Re: Programmatic interaction with Human Task
              swaminathan.bhaskar

              I had to use the "en-UK" for language and that got me all the pending tasks.

               

              But when I tried to claim the task, I got an exception:

               

              org.jbpm.task.service.PermissionDeniedException: User '[User:'joe']' does not have permissions to execution operation 'Claim'

               

              If I comment the claim and just do the start and complete it works ... any thoughts on how one should process tasks programatically ?

              • 4. Re: Programmatic interaction with Human Task
                salaboy21

                That's because you cannot claim a task that was already asigned. The task should be assigned to a group of people or to multiple actors. In that state one of the potential owners will be able to claim the task.

                Cheers

                • 5. Re: Programmatic interaction with Human Task
                  swaminathan.bhaskar

                  Thank you very much for your quick response and thanks for clarifying the concepts. This is very helpful.