<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body link="#355491" alink="#4262a1" vlink="#355491" style="background: #e2e2e2; margin: 0; padding: 20px;">
<div>
        <table cellpadding="0" bgcolor="#FFFFFF" border="0" cellspacing="0" style="border: 1px solid #dadada; margin-bottom: 30px; width: 100%; -moz-border-radius: 6px; -webkit-border-radius: 6px;">
                <tbody>
                        <tr>
                                <td>
                                        <table border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF" style="border: solid 2px #ccc; background: #dadada; width: 100%; -moz-border-radius: 6px; -webkit-border-radius: 6px;">
                                                <tbody>
                                                        <tr>
                                                                <td bgcolor="#000000" valign="middle" height="58px" style="border-bottom: 1px solid #ccc; padding: 20px; -moz-border-radius-topleft: 3px; -moz-border-radius-topright: 3px; -webkit-border-top-right-radius: 5px; -webkit-border-top-left-radius: 5px;">
                                                                        <h1 style="color: #333333; font: bold 22px Arial, Helvetica, sans-serif; margin: 0; display: block !important;">
                                                                        <!-- To have a header image/logo replace the name below with your img tag -->
                                                                        <!-- Email clients will render the images when the message is read so any image -->
                                                                        <!-- must be made available on a public server, so that all recipients can load the image. -->
                                                                        <a href="https://community.jboss.org/index.jspa" style="text-decoration: none; color: #E1E1E1">JBoss Community</a></h1>
                                                                </td>
                                                        </tr>
                                                        <tr>
                                                                <td bgcolor="#FFFFFF" style="font: normal 12px Arial, Helvetica, sans-serif; color:#333333; padding: 20px; -moz-border-radius-bottomleft: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 5px; -webkit-border-bottom-left-radius: 5px;"><h3 style="margin: 10px 0 5px; font-size: 17px; font-weight: normal;">
Programmatic interaction with Human Task
</h3>
<span style="margin-bottom: 10px;">
created by <a href="https://community.jboss.org/people/swaminathan.bhaskar">Swaminathan Bhaskar</a> in <i>jBPM</i> - <a href="https://community.jboss.org/message/741849#741849">View the full discussion</a>
</span>
<hr style="margin: 20px 0; border: none; background-color: #dadada; height: 1px;">
<div class="jive-rendered-content"><p>I am using JBPM 5.2 and am trying to programmatically intyeract with Human task. I just have one user task in my process.</p><p style="min-height: 8pt; height: 8pt; padding: 0px;"> </p><p>Here is my code:</p><pre>                      
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");
     }
}
</pre><p style="min-height: 8pt; height: 8pt; padding: 0px;"> </p><p>When I run the code, encounter the following exception:</p><pre>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)
</pre><p style="min-height: 8pt; height: 8pt; padding: 0px;"> </p><p>Any ideas ? Any help appreciated.</p></div>
<div style="background-color: #f4f4f4; padding: 10px; margin-top: 20px;">
<p style="margin: 0;">Reply to this message by <a href="https://community.jboss.org/message/741849#741849">going to Community</a></p>
        <p style="margin: 0;">Start a new discussion in jBPM at <a href="https://community.jboss.org/choose-container!input.jspa?contentType=1&containerType=14&container=2034">Community</a></p>
</div></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>