5 Replies Latest reply on Jun 14, 2012 7:05 PM by Swaminathan Bhaskar

    Programmatic interaction with Human Task

    Swaminathan Bhaskar Newbie

      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.