@Override
 public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
   if (currentWorkItem >= 0) {
     throw new RuntimeException("Existing work item was not completed correctly!");
   }
   currentWorkItem = workItem.getId();
 }
  /**
   * OIG exclusion screening.
   *
   * @param item the work item to abort
   * @param manager the work item manager
   */
  public void executeWorkItem(WorkItem item, WorkItemManager manager) {
    log.log(Level.INFO, "Checking provider exclusion.");
    EnrollmentProcess processModel = (EnrollmentProcess) item.getParameter("model");

    ProviderInformationType provider = XMLUtility.nsGetProvider(processModel);
    ScreeningResultsType screeningResults = XMLUtility.nsGetScreeningResults(processModel);
    ScreeningResultType screeningResultType = new ScreeningResultType();
    screeningResults.getScreeningResult().add(screeningResultType);

    ExternalSourcesScreeningResultType results = null;
    try {
      OIGExclusionSearchClient client = new OIGExclusionSearchClient();
      results = client.verify(XMLUtility.nsGetProvider(processModel));

      VerificationStatusType verificationStatus = XMLUtility.nsGetVerificationStatus(processModel);
      if (!results.getSearchResults().getSearchResultItem().isEmpty()) {
        OIGExclusionServiceMatcher matcher = new OIGExclusionServiceMatcher();
        MatchStatus status = matcher.match(provider, null, results);
        if (status == MatchStatus.EXACT_MATCH) {
          verificationStatus.setNonExclusion("N");
        } else {
          verificationStatus.setNonExclusion("Y");
        }
      } else {
        verificationStatus.setNonExclusion("Y");
      }
    } catch (TransformerException e) {
      log.log(Level.ERROR, e);
      results = new ExternalSourcesScreeningResultType();
      results.setStatus(XMLUtility.newStatus("ERROR"));
    } catch (JAXBException e) {
      log.log(Level.ERROR, e);
      results = new ExternalSourcesScreeningResultType();
      results.setStatus(XMLUtility.newStatus("ERROR"));
    } catch (IOException e) {
      log.log(Level.ERROR, e);
      results = new ExternalSourcesScreeningResultType();
      results.setStatus(XMLUtility.newStatus("ERROR"));
    }

    screeningResultType.setExclusionVerificationResult(results.getSearchResults());
    screeningResultType.setScreeningType("EXCLUDED PROVIDERS");
    screeningResultType.setStatus(XMLUtility.newStatus("SUCCESS"));

    item.getResults().put("model", processModel);
    manager.completeWorkItem(item.getId(), item.getResults());
  }
Example #3
0
 @Override
 public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
   String url = HandlerUtils.getFirstTypedParameter(workItem.getParameters(), String.class);
   try {
     if (url == null) throw new Exception("No URL given");
     DocumentInformation docInfo = docManager.getDocumentInformation(workItem);
     if (docInfo == null) throw new Exception("No document associated with this workflow");
     Theo theo = docInfo.getTheo();
     int theoOutput = theo.openWindow(docInfo, workItem.getProcessInstanceId(), "", url, 700, 600);
     workItem.getResults().put("wndIDOutput", theoOutput);
   } catch (Exception e) {
     log.error(e.getMessage());
     e.printStackTrace();
   } finally {
     manager.completeWorkItem(workItem.getId(), workItem.getResults());
   }
 }
 public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
   Task task = client.getTaskByWorkItemId(workItem.getId());
   if (task != null) {
     try {
       client.skip(task.getId(), "Administrator");
     } catch (PermissionDeniedException e) {
       logger.info(e.getMessage());
     }
   }
 }
 public static void waitTillCompleted(WorkItem workItem, long time) throws Exception {
   int count = 0;
   while (count < 10) {
     if (workItem.getState() != org.drools.process.instance.WorkItem.COMPLETED) {
       if (workItem.getState() != org.drools.process.instance.WorkItem.ABORTED)
         throw new Exception("waitTillCompleted" + workItem.toString() + " is already aborted");
       try {
         Thread.sleep(time);
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     } else {
       break;
     }
     count++;
   }
   if (count == 10) {
     throw new Exception("waitTillCompleted" + workItem.toString() + " Timed out");
   }
 }
  @Override
  public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    to = (String) workItem.getParameter("To");
    from = (String) workItem.getParameter("From");
    subject = (String) workItem.getParameter("Subject");
    body = (String) workItem.getParameter("Body");

    System.out.println("====================================");
    System.out.println("Executing Email task: " + workItem);
    System.out.println("From: " + from);
    System.out.println("To: " + to);
    System.out.println("Subject: " + subject);
    System.out.println("Body: " + body);
    System.out.println("====================================");

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

      // Set Subject: header field
      message.setSubject(subject);

      // Now set the actual message
      message.setText(body);

      // Send message
      Transport.send(message);
      System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
    manager.completeWorkItem(workItem.getId(), workItem.getResults());
  }
  /* (non-Javadoc)
   * @see org.drools.runtime.process.WorkItemHandler#executeWorkItem(org.drools.runtime.process.WorkItem, org.drools.runtime.process.WorkItemManager)
   */
  @Override
  public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    CustomerAddressBP bp = new CustomerAddressBP();
    Customer customer =
        new Customer(
            (String) workItem.getParameter("save_FirstName"),
            (String) workItem.getParameter("save_LastName"),
            (String) workItem.getParameter("save_NickName"),
            (String) workItem.getParameter("save_CustomerNumber"));

    Address address =
        new Address(
            (String) workItem.getParameter("save_AddressLine1"),
            (String) workItem.getParameter("save_AddressLine2"),
            (String) workItem.getParameter("save_City"),
            (String) workItem.getParameter("save_State"),
            (String) workItem.getParameter("save_Zipcode"));

    customer.addAddress(address);

    manager.completeWorkItem(workItem.getId(), null);
  }
  public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    if (this.session == null) {
      if (this.manager == null) {
        this.manager = manager;
      } else {
        if (this.manager != manager) {
          throw new IllegalArgumentException(
              "This WSHumanTaskHandler can only be used for one WorkItemManager");
        }
      }
    }
    connect();
    Task task = new Task();
    String taskName = (String) workItem.getParameter("TaskName");
    if (taskName != null) {
      List<I18NText> names = new ArrayList<I18NText>();
      names.add(new I18NText("en-UK", taskName));
      task.setNames(names);
    }
    String comment = (String) workItem.getParameter("Comment");
    if (comment != null) {
      List<I18NText> descriptions = new ArrayList<I18NText>();
      descriptions.add(new I18NText("en-UK", comment));
      task.setDescriptions(descriptions);
      List<I18NText> subjects = new ArrayList<I18NText>();
      subjects.add(new I18NText("en-UK", comment));
      task.setSubjects(subjects);
    }
    String priorityString = (String) workItem.getParameter("Priority");
    int priority = 0;
    if (priorityString != null) {
      try {
        priority = new Integer(priorityString);
      } catch (NumberFormatException e) {
        // do nothing
      }
    }
    task.setPriority(priority);

    TaskData taskData = new TaskData();
    taskData.setWorkItemId(workItem.getId());
    taskData.setProcessInstanceId(workItem.getProcessInstanceId());
    if (session != null && session.getProcessInstance(workItem.getProcessInstanceId()) != null) {
      taskData.setProcessId(
          session.getProcessInstance(workItem.getProcessInstanceId()).getProcess().getId());
    }
    if (session != null && (session instanceof StatefulKnowledgeSession)) {
      taskData.setProcessSessionId(((StatefulKnowledgeSession) session).getId());
    }
    taskData.setSkipable(!"false".equals(workItem.getParameter("Skippable")));
    // Sub Task Data
    Long parentId = (Long) workItem.getParameter("ParentId");
    if (parentId != null) {
      taskData.setParentId(parentId);
    }

    String subTaskStrategiesCommaSeparated = (String) workItem.getParameter("SubTaskStrategies");
    if (subTaskStrategiesCommaSeparated != null && !subTaskStrategiesCommaSeparated.equals("")) {
      String[] subTaskStrategies = subTaskStrategiesCommaSeparated.split(",");
      List<SubTasksStrategy> strategies = new ArrayList<SubTasksStrategy>();
      for (String subTaskStrategyString : subTaskStrategies) {
        SubTasksStrategy subTaskStrategy =
            SubTasksStrategyFactory.newStrategy(subTaskStrategyString);
        strategies.add(subTaskStrategy);
      }
      task.setSubTaskStrategies(strategies);
    }

    PeopleAssignments assignments = new PeopleAssignments();
    List<OrganizationalEntity> potentialOwners = new ArrayList<OrganizationalEntity>();

    String actorId = (String) workItem.getParameter("ActorId");
    if (actorId != null && actorId.trim().length() > 0) {
      String[] actorIds = actorId.split(",");
      for (String id : actorIds) {
        potentialOwners.add(new User(id.trim()));
      }
      // Set the first user as creator ID??? hmmm might be wrong
      if (potentialOwners.size() > 0) {
        taskData.setCreatedBy((User) potentialOwners.get(0));
      }
    }

    String groupId = (String) workItem.getParameter("GroupId");
    if (groupId != null && groupId.trim().length() > 0) {
      String[] groupIds = groupId.split(",");
      for (String id : groupIds) {
        potentialOwners.add(new Group(id.trim()));
      }
    }

    assignments.setPotentialOwners(potentialOwners);
    List<OrganizationalEntity> businessAdministrators = new ArrayList<OrganizationalEntity>();
    businessAdministrators.add(new User("Administrator"));
    assignments.setBusinessAdministrators(businessAdministrators);
    task.setPeopleAssignments(assignments);

    task.setTaskData(taskData);

    ContentData content = null;
    Object contentObject = workItem.getParameter("Content");
    if (contentObject == null) {
      contentObject = workItem.getParameters();
    }
    if (contentObject != null) {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream out;
      try {
        out = new ObjectOutputStream(bos);
        out.writeObject(contentObject);
        out.close();
        content = new ContentData();
        content.setContent(bos.toByteArray());
        content.setAccessType(AccessType.Inline);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    client.addTask(task, content);
  }
 public void complete() {
   this.manager.completeWorkItem(workItem.getId(), null);
 }
 public Object getWorkItemParameter(String key) {
   return workItem.getParameter(key);
 }
  @Test
  public void testPersistenceWorkItems() throws Exception {
    setUp();

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    Collection<KnowledgePackage> kpkgs = getProcessWorkItems();
    kbase.addKnowledgePackages(kpkgs);

    Properties properties = new Properties();
    properties.setProperty("drools.commandService", SingleSessionCommandService.class.getName());
    properties.setProperty(
        "drools.processInstanceManagerFactory", JPAProcessInstanceManagerFactory.class.getName());
    properties.setProperty(
        "drools.workItemManagerFactory", JPAWorkItemManagerFactory.class.getName());
    properties.setProperty(
        "drools.processSignalManagerFactory", JPASignalManagerFactory.class.getName());
    properties.setProperty("drools.timerService", JpaJDKTimerService.class.getName());
    SessionConfiguration config = new SessionConfiguration(properties);

    SingleSessionCommandService service = new SingleSessionCommandService(kbase, config, env);
    int sessionId = service.getSessionId();

    StartProcessCommand startProcessCommand = new StartProcessCommand();
    startProcessCommand.setProcessId("org.drools.test.TestProcess");
    ProcessInstance processInstance = service.execute(startProcessCommand);
    System.out.println("Started process instance " + processInstance.getId());

    TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    GetProcessInstanceCommand getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    assertNotNull(processInstance);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    CompleteWorkItemCommand completeWorkItemCommand = new CompleteWorkItemCommand();
    completeWorkItemCommand.setWorkItemId(workItem.getId());
    service.execute(completeWorkItemCommand);

    workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    assertNotNull(processInstance);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    completeWorkItemCommand = new CompleteWorkItemCommand();
    completeWorkItemCommand.setWorkItemId(workItem.getId());
    service.execute(completeWorkItemCommand);

    workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    assertNotNull(processInstance);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    completeWorkItemCommand = new CompleteWorkItemCommand();
    completeWorkItemCommand.setWorkItemId(workItem.getId());
    service.execute(completeWorkItemCommand);

    workItem = handler.getWorkItem();
    assertNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    assertNull(processInstance);
    service.dispose();
  }
  @Test
  public void testPersistenceSubProcess() {
    setUp();

    Properties properties = new Properties();
    properties.setProperty("drools.commandService", SingleSessionCommandService.class.getName());
    properties.setProperty(
        "drools.processInstanceManagerFactory", JPAProcessInstanceManagerFactory.class.getName());
    properties.setProperty(
        "drools.workItemManagerFactory", JPAWorkItemManagerFactory.class.getName());
    properties.setProperty(
        "drools.processSignalManagerFactory", JPASignalManagerFactory.class.getName());
    properties.setProperty("drools.timerService", JpaJDKTimerService.class.getName());
    SessionConfiguration config = new SessionConfiguration(properties);

    RuleBase ruleBase = RuleBaseFactory.newRuleBase();
    Package pkg = getProcessSubProcess();
    ruleBase.addPackage(pkg);

    SingleSessionCommandService service = new SingleSessionCommandService(ruleBase, config, env);
    int sessionId = service.getSessionId();
    StartProcessCommand startProcessCommand = new StartProcessCommand();
    startProcessCommand.setProcessId("org.drools.test.TestProcess");
    RuleFlowProcessInstance processInstance =
        (RuleFlowProcessInstance) service.execute(startProcessCommand);
    System.out.println("Started process instance " + processInstance.getId());
    long processInstanceId = processInstance.getId();

    TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, ruleBase, config, env);
    GetProcessInstanceCommand getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstanceId);
    processInstance = (RuleFlowProcessInstance) service.execute(getProcessInstanceCommand);
    assertNotNull(processInstance);

    Collection<NodeInstance> nodeInstances = processInstance.getNodeInstances();
    assertEquals(1, nodeInstances.size());
    SubProcessNodeInstance subProcessNodeInstance =
        (SubProcessNodeInstance) nodeInstances.iterator().next();
    long subProcessInstanceId = subProcessNodeInstance.getProcessInstanceId();
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(subProcessInstanceId);
    RuleFlowProcessInstance subProcessInstance =
        (RuleFlowProcessInstance) service.execute(getProcessInstanceCommand);
    assertNotNull(subProcessInstance);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, ruleBase, config, env);
    CompleteWorkItemCommand completeWorkItemCommand = new CompleteWorkItemCommand();
    completeWorkItemCommand.setWorkItemId(workItem.getId());
    service.execute(completeWorkItemCommand);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, ruleBase, config, env);
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(subProcessInstanceId);
    subProcessInstance = (RuleFlowProcessInstance) service.execute(getProcessInstanceCommand);
    assertNull(subProcessInstance);

    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstanceId);
    processInstance = (RuleFlowProcessInstance) service.execute(getProcessInstanceCommand);
    assertNull(processInstance);
    service.dispose();
  }
 @Override
 public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
   System.err.println("Email Task aborted: " + workItem);
   manager.abortWorkItem(workItem.getId());
 }
  public void testWorkItem() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    Reader source =
        new StringReader(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<process xmlns=\"http://drools.org/drools-4.0/process\"\n"
                + "         xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
                + "         xs:schemaLocation=\"http://drools.org/drools-4.0/process drools-processes-4.0.xsd\"\n"
                + "         type=\"RuleFlow\" name=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n"
                + "\n"
                + "  <header>\n"
                + "    <variables>\n"
                + "      <variable name=\"UserName\" >\n"
                + "        <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
                + "        <value>John Doe</value>\n"
                + "      </variable>\n"
                + "      <variable name=\"MyObject\" >\n"
                + "        <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"java.lang.Object\" />\n"
                + "      </variable>\n"
                + "    </variables>\n"
                + "  </header>\n"
                + "\n"
                + "  <nodes>\n"
                + "    <start id=\"1\" name=\"Start\" />\n"
                + "    <workItem id=\"2\" name=\"HumanTask\" >\n"
                + "      <work name=\"Human Task\" >\n"
                + "        <parameter name=\"ActorId\" >\n"
                + "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
                + "          <value>#{UserName}</value>\n"
                + "        </parameter>\n"
                + "        <parameter name=\"TaskName\" >\n"
                + "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
                + "          <value>Do something</value>\n"
                + "        </parameter>\n"
                + "        <parameter name=\"Priority\" >\n"
                + "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
                + "        </parameter>\n"
                + "        <parameter name=\"Comment\" >\n"
                + "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
                + "        </parameter>\n"
                + "        <parameter name=\"Attachment\" >\n"
                + "          <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"java.lang.Object\" />\n"
                + "        </parameter>\n"
                + "      </work>\n"
                + "      <mapping type=\"in\" from=\"MyObject\" to=\"Attachment\" />"
                + "      <mapping type=\"out\" from=\"Result\" to=\"MyObject\" />"
                + "    </workItem>\n"
                + "    <end id=\"3\" name=\"End\" />\n"
                + "  </nodes>\n"
                + "\n"
                + "  <connections>\n"
                + "    <connection from=\"1\" to=\"2\" />\n"
                + "    <connection from=\"2\" to=\"3\" />\n"
                + "  </connections>\n"
                + "\n"
                + "</process>");
    kbuilder.add(ResourceFactory.newReaderResource(source), KnowledgeType.DRF);

    Collection<KnowledgePackage> kpkgs = kbuilder.getKnowledgePackages();
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kpkgs);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    ProcessInstance processInstance = ksession.startProcess("org.drools.actions");
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("John Doe", workItem.getParameter("ActorId"));
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("UserName", "Jane Doe");
    parameters.put("MyObject", "SomeString");
    processInstance = ksession.startProcess("org.drools.actions", parameters);
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    workItem = handler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("Jane Doe", workItem.getParameter("ActorId"));
    assertEquals("SomeString", workItem.getParameter("Attachment"));
    Map<String, Object> results = new HashMap<String, Object>();
    results.put("Result", "SomeOtherString");
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), results);
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
    VariableScopeInstance variableScope =
        (VariableScopeInstance)
            ((org.drools.process.instance.ProcessInstance) processInstance)
                .getContextInstance(VariableScope.VARIABLE_SCOPE);
    assertEquals("SomeOtherString", variableScope.getVariable("MyObject"));
  }
 public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
   System.out.println("Executing workItem " + workItem.getParameter("TaskName"));
   workItems.add(workItem);
 }
  public void test4() throws Exception {
    String process =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n"
            + "  xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "  xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n"
            + "  type=\"RuleFlow\" name=\"ruleflow\" id=\"com.sample.ruleflow\" package-name=\"com.sample\" >\n"
            + "\n"
            + "    <header>\n"
            + "      <variables>\n"
            + "        <variable name=\"list\" >\n"
            + "          <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"java.util.List\" />\n"
            + "        </variable>\n"
            + "      </variables>\n"
            + "    </header>\n"
            + "\n"
            + "    <nodes>\n"
            + "      <forEach id=\"4\" name=\"ForEach\" variableName=\"item\" collectionExpression=\"list\" >\n"
            + "        <nodes>\n"
            + "          <humanTask id=\"1\" name=\"Human Task\" >\n"
            + "            <work name=\"Human Task\" >\n"
            + "              <parameter name=\"Comment\" >\n"
            + "                <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
            + "              </parameter>\n"
            + "              <parameter name=\"ActorId\" >\n"
            + "                <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
            + "              </parameter>\n"
            + "              <parameter name=\"Priority\" >\n"
            + "                <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
            + "              </parameter>\n"
            + "              <parameter name=\"TaskName\" >\n"
            + "                <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
            + "                <value>Do something: #{item}</value>\n"
            + "              </parameter>\n"
            + "            </work>\n"
            + "          </humanTask>\n"
            + "          <humanTask id=\"2\" name=\"Human Task Again\" >\n"
            + "            <work name=\"Human Task\" >\n"
            + "              <parameter name=\"Comment\" >\n"
            + "                <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
            + "              </parameter>\n"
            + "              <parameter name=\"ActorId\" >\n"
            + "                <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
            + "              </parameter>\n"
            + "              <parameter name=\"Priority\" >\n"
            + "                <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
            + "              </parameter>\n"
            + "              <parameter name=\"TaskName\" >\n"
            + "                <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n"
            + "                <value>Do something else: #{item}</value>\n"
            + "              </parameter>\n"
            + "            </work>\n"
            + "          </humanTask>\n"
            + "        </nodes>\n"
            + "        <connections>\n"
            + "          <connection from=\"1\" to=\"2\" />\n"
            + "        </connections>\n"
            + "        <in-ports>\n"
            + "          <in-port type=\"DROOLS_DEFAULT\" nodeId=\"1\" nodeInType=\"DROOLS_DEFAULT\" />\n"
            + "        </in-ports>\n"
            + "        <out-ports>\n"
            + "          <out-port type=\"DROOLS_DEFAULT\" nodeId=\"2\" nodeOutType=\"DROOLS_DEFAULT\" />\n"
            + "        </out-ports>\n"
            + "      </forEach>\n"
            + "      <start id=\"1\" name=\"Start\" />\n"
            + "      <end id=\"3\" name=\"End\" />\n"
            + "    </nodes>\n"
            + "\n"
            + "    <connections>\n"
            + "      <connection from=\"1\" to=\"4\" />\n"
            + "      <connection from=\"4\" to=\"3\" />\n"
            + "    </connections>\n"
            + "\n"
            + "</process>\n";
    final PackageBuilder builder = new PackageBuilder();
    builder.addProcessFromXml(new StringReader(process));
    final Package pkg = builder.getPackage();
    final RuleBase ruleBase = RuleBaseFactory.newRuleBase();
    ruleBase.addPackage(pkg);

    StatefulSession session = ruleBase.newStatefulSession();
    TestListWorkItemHandler handler = new TestListWorkItemHandler();
    session.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    List<String> list = new ArrayList<String>();
    list.add("one");
    list.add("two");
    list.add("three");
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("list", list);
    session.startProcess("com.sample.ruleflow", parameters);

    assertEquals(1, session.getProcessInstances().size());
    assertEquals(3, handler.getWorkItems().size());

    session = getSerialisedStatefulSession(session);
    session.getWorkItemManager().registerWorkItemHandler("Human Task", handler);

    List<WorkItem> workItems = new ArrayList<WorkItem>(handler.getWorkItems());
    handler.reset();
    for (WorkItem workItem : workItems) {
      session.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    }
    assertEquals(1, session.getProcessInstances().size());
    assertEquals(3, handler.getWorkItems().size());

    session = getSerialisedStatefulSession(session);

    for (WorkItem workItem : handler.getWorkItems()) {
      session.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    }

    assertEquals(0, session.getProcessInstances().size());
  }
  @Test
  public void testPersistenceWorkItemsUserTransaction() throws Exception {
    final Environment env = KnowledgeBaseFactory.newEnvironment();
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
    env.set(
        EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager());

    final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    final Collection<KnowledgePackage> kpkgs = getProcessWorkItems();
    kbase.addKnowledgePackages(kpkgs);

    final Properties properties = new Properties();
    properties.setProperty("drools.commandService", SingleSessionCommandService.class.getName());
    properties.setProperty(
        "drools.processInstanceManagerFactory", JPAProcessInstanceManagerFactory.class.getName());
    properties.setProperty(
        "drools.workItemManagerFactory", JPAWorkItemManagerFactory.class.getName());
    properties.setProperty(
        "drools.processSignalManagerFactory", JPASignalManagerFactory.class.getName());
    properties.setProperty("drools.timerService", JpaJDKTimerService.class.getName());
    final SessionConfiguration config = new SessionConfiguration(properties);

    SingleSessionCommandService service = new SingleSessionCommandService(kbase, config, env);
    final int sessionId = service.getSessionId();

    final UserTransaction ut =
        (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    final StartProcessCommand startProcessCommand = new StartProcessCommand();
    startProcessCommand.setProcessId("org.drools.test.TestProcess");
    ProcessInstance processInstance = service.execute(startProcessCommand);
    System.out.println("Started process instance " + processInstance.getId());
    ut.commit();

    final TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    ut.begin();
    GetProcessInstanceCommand getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    assertNotNull(processInstance);
    ut.commit();
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    ut.begin();
    CompleteWorkItemCommand completeWorkItemCommand = new CompleteWorkItemCommand();
    completeWorkItemCommand.setWorkItemId(workItem.getId());
    service.execute(completeWorkItemCommand);
    ut.commit();

    workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    ut.begin();
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    ut.commit();
    assertNotNull(processInstance);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    ut.begin();
    completeWorkItemCommand = new CompleteWorkItemCommand();
    completeWorkItemCommand.setWorkItemId(workItem.getId());
    service.execute(completeWorkItemCommand);
    ut.commit();

    workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    ut.begin();
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    ut.commit();
    assertNotNull(processInstance);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    ut.begin();
    completeWorkItemCommand = new CompleteWorkItemCommand();
    completeWorkItemCommand.setWorkItemId(workItem.getId());
    service.execute(completeWorkItemCommand);
    ut.commit();

    workItem = handler.getWorkItem();
    assertNull(workItem);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    ut.begin();
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    ut.commit();
    assertNull(processInstance);
    service.dispose();
  }