private void doControlTask() throws IOException, ClassNotFoundException {
    BlockingTaskSummaryResponseHandler handler = new BlockingTaskSummaryResponseHandler();
    client.getTasksAssignedAsPotentialOwner("control", "en-UK", handler);
    List<TaskSummary> sums = handler.getResults();
    assertNotNull(sums);
    assertEquals(1, sums.size());

    BlockingTaskOperationResponseHandler startTaskOperationHandler =
        new BlockingTaskOperationResponseHandler();
    client.start(sums.get(0).getId(), "control", startTaskOperationHandler);

    BlockingGetTaskResponseHandler getTaskHandler = new BlockingGetTaskResponseHandler();
    client.getTask(sums.get(0).getId(), getTaskHandler);
    Task controlTask = getTaskHandler.getTask();

    BlockingGetContentResponseHandler getContentHandler = new BlockingGetContentResponseHandler();
    client.getContent(controlTask.getTaskData().getDocumentContentId(), getContentHandler);
    Content content = getContentHandler.getContent();

    assertNotNull(content);

    ByteArrayInputStream bais = new ByteArrayInputStream(content.getContent());
    ObjectInputStream ois = new ObjectInputStream(bais);
    Map<String, Object> deserializedContent = (Map<String, Object>) ois.readObject();
    Emergency retrivedEmergency = (Emergency) deserializedContent.get("emergency");
    assertNotNull(retrivedEmergency);
    ActivePatients retrivedActivePatients =
        (ActivePatients) deserializedContent.get("activePatients");
    assertNotNull(retrivedActivePatients);
    assertEquals(1, retrivedActivePatients.size());
    SuggestedProcedures retrivedSuggestedProcedures =
        (SuggestedProcedures) deserializedContent.get("suggestedProcedures");
    assertNotNull(retrivedSuggestedProcedures);
    assertEquals(
        "[DefaultHeartAttackProcedure: ]",
        retrivedSuggestedProcedures.getSuggestedProceduresString());

    Map<String, Object> info = new HashMap<String, Object>();
    SelectedProcedures selectedProcedures = new SelectedProcedures(retrivedEmergency.getId());

    selectedProcedures.addSelectedProcedureName("DefaultHeartAttackProcedure");
    info.put("selectedProcedures", selectedProcedures);

    ContentData result = new ContentData();
    result.setAccessType(AccessType.Inline);
    result.setType("java.util.Map");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(info);
    out.close();
    result.setContent(bos.toByteArray());

    BlockingTaskOperationResponseHandler completeTaskOperationHandler =
        new BlockingTaskOperationResponseHandler();
    client.complete(sums.get(0).getId(), "control", result, completeTaskOperationHandler);
  }
  private void doOperatorTask() throws ClassNotFoundException, IOException {
    BlockingTaskSummaryResponseHandler handler = new BlockingTaskSummaryResponseHandler();
    client.getTasksAssignedAsPotentialOwner("operator", "en-UK", handler);
    List<TaskSummary> sums = handler.getResults();
    assertNotNull(sums);
    assertEquals(1, sums.size());

    BlockingTaskOperationResponseHandler startTaskOperationHandler =
        new BlockingTaskOperationResponseHandler();
    client.start(sums.get(0).getId(), "operator", startTaskOperationHandler);

    BlockingGetTaskResponseHandler getTaskHandler = new BlockingGetTaskResponseHandler();
    client.getTask(sums.get(0).getId(), getTaskHandler);
    Task operatorTask = getTaskHandler.getTask();

    BlockingGetContentResponseHandler getContentHandler = new BlockingGetContentResponseHandler();
    client.getContent(operatorTask.getTaskData().getDocumentContentId(), getContentHandler);
    Content content = getContentHandler.getContent();

    assertNotNull(content);

    ByteArrayInputStream bais = new ByteArrayInputStream(content.getContent());
    ObjectInputStream ois = new ObjectInputStream(bais);
    Map<String, Object> deserializedContent = (Map<String, Object>) ois.readObject();
    Call restoredCall = (Call) deserializedContent.get("call");
    persistenceService.storeCall(restoredCall);

    Emergency emergency = new Emergency();

    emergency.setCall(restoredCall);

    emergency.setLocation(new Location(1, 2));
    emergency.setType(Emergency.EmergencyType.HEART_ATTACK);
    emergency.setNroOfPeople(1);
    persistenceService.storeEmergency(emergency);

    trackingService.attachEmergency(restoredCall.getId(), emergency.getId());

    Map<String, Object> info = new HashMap<String, Object>();
    info.put("emergency", emergency);

    ContentData result = new ContentData();
    result.setAccessType(AccessType.Inline);
    result.setType("java.util.Map");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(info);
    out.close();
    result.setContent(bos.toByteArray());

    BlockingTaskOperationResponseHandler completeTaskOperationHandler =
        new BlockingTaskOperationResponseHandler();
    client.complete(sums.get(0).getId(), "operator", result, completeTaskOperationHandler);
  }
  public static ContentData marshal(Object o, Environment env) {
    MarshallerWriteContext context = null;
    ContentData content = null;
    try {
      MarshallingConfigurationImpl marshallingConfigurationImpl = null;
      if (env != null) {
        marshallingConfigurationImpl =
            new MarshallingConfigurationImpl(
                (ObjectMarshallingStrategy[])
                    env.get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES),
                false,
                false);
      } else {
        marshallingConfigurationImpl =
            new MarshallingConfigurationImpl(
                new ObjectMarshallingStrategy[] {
                  new SerializablePlaceholderResolverStrategy(
                      ClassObjectMarshallingStrategyAcceptor.DEFAULT)
                },
                false,
                false);
      }
      ObjectMarshallingStrategyStore objectMarshallingStrategyStore =
          marshallingConfigurationImpl.getObjectMarshallingStrategyStore();
      ByteArrayOutputStream stream = new ByteArrayOutputStream();

      context =
          new MarshallerWriteContext(stream, null, null, null, objectMarshallingStrategyStore, env);
      Variable marshallVariable = null;
      if (o instanceof Map) {
        marshallVariable =
            ProtobufProcessMarshaller.marshallVariablesMap(context, (Map<String, Object>) o);
      } else {
        marshallVariable = ProtobufProcessMarshaller.marshallVariable(context, "results", o);
      }
      PersisterHelper.writeToStreamWithHeader(context, marshallVariable);

      context.close();

      byte[] toByteArray = stream.toByteArray();

      content = new ContentData();
      content.setContent(toByteArray);
      content.setType(o.getClass().getCanonicalName());
      content.setAccessType(AccessType.Inline);

    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return content;
  }
  public static final void main(String[] args) {
    try {
      setupTaskServer();
      // load up the knowledge base
      KnowledgeBase kbase = readKnowledgeBase();
      StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
      KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession);
      ksession
          .getWorkItemManager()
          .registerWorkItemHandler("Human Task", new CommandBasedWSHumanTaskHandler(ksession));
      // start a new process instance
      Map<String, Object> params = new HashMap<String, Object>();
      params.put("userId", "krisv");
      params.put("s", "Need a new laptop computer");
      ksession.startProcess("UserTask", params);

      SystemEventListenerFactory.setSystemEventListener(new SystemEventListener());
      TaskClient taskClient =
          new TaskClient(
              new MinaTaskClientConnector(
                  "MinaConnector",
                  new MinaTaskClientHandler(SystemEventListenerFactory.getSystemEventListener())));
      taskClient.connect("127.0.0.1", 9123);
      Thread.sleep(1000);

      // sleep to allow notification to be sent for deadline start
      Thread.sleep(6000);
      //            Assert.assertEquals(4, wiser.getMessages().size());
      //            Assert.assertEquals("*****@*****.**",
      // wiser.getMessages().get(0).getEnvelopeReceiver());
      //            Assert.assertEquals("*****@*****.**",
      // wiser.getMessages().get(1).getEnvelopeReceiver());
      //            Assert.assertEquals("Task is ready for mike",
      // wiser.getMessages().get(0).getMimeMessage().getSubject());

      // wait another few seconds to trigger complete deadline
      Thread.sleep(4000);
      //            Assert.assertEquals(6, wiser.getMessages().size());
      //            Assert.assertEquals("*****@*****.**",
      // wiser.getMessages().get(2).getEnvelopeReceiver());
      //            Assert.assertEquals("*****@*****.**",
      // wiser.getMessages().get(3).getEnvelopeReceiver());
      //            Assert.assertEquals("Not completedTask is ready for mike",
      // wiser.getMessages().get(4).getMimeMessage().getSubject());

      BlockingTaskSummaryResponseHandler taskSummaryHandler =
          new BlockingTaskSummaryResponseHandler();
      taskClient.getTasksAssignedAsPotentialOwner("mike", "en-UK", taskSummaryHandler);
      TaskSummary task1 = taskSummaryHandler.getResults().get(0);

      BlockingTaskOperationResponseHandler taskOperationHandler =
          new BlockingTaskOperationResponseHandler();
      taskClient.start(task1.getId(), "mike", taskOperationHandler);
      taskOperationHandler.waitTillDone(1000);
      taskOperationHandler = new BlockingTaskOperationResponseHandler();
      Map<String, Object> results = new HashMap<String, Object>();
      results.put("comment", "Agreed, existing laptop needs replacing");
      results.put("outcome", "Accept");
      ContentData contentData = new ContentData();
      contentData.setAccessType(AccessType.Inline);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream out;
      try {
        out = new ObjectOutputStream(bos);
        out.writeObject(results);
        out.close();
        contentData = new ContentData();
        contentData.setContent(bos.toByteArray());
        contentData.setAccessType(AccessType.Inline);
      } catch (IOException e) {
        e.printStackTrace();
      }
      taskClient.complete(task1.getId(), "mike", contentData, taskOperationHandler);
      taskOperationHandler.waitTillDone(1000);
      Thread.sleep(1000);

      logger.close();
    } catch (Throwable t) {
      t.printStackTrace();
    }
    wiser.stop();
    System.exit(0);
  }
Beispiel #5
0
 /**
  * Sets the content data for this task data. It will set the <field>outputContentId</field> from
  * the specified outputContentId, <field>outputAccessType</field>, <field>outputType</field> from
  * the specified outputContentData.
  *
  * @param outputContentId id of output content
  * @param outputContentData contentData
  */
 public void setOutput(long outputContentId, ContentData outputContentData) {
   setOutputContentId(outputContentId);
   setOutputAccessType(outputContentData.getAccessType());
   setOutputType(outputContentData.getType());
 }
Beispiel #6
0
 /**
  * Sets the document content data for this task data. It will set the
  * <field>documentContentId</field> from the specified documentID,
  * <field>documentAccessType</field>, <field>documentType</field> from the specified
  * documentConentData.
  *
  * @param documentID id of document content
  * @param documentConentData ContentData
  */
 public void setDocument(long documentID, ContentData documentConentData) {
   setDocumentContentId(documentID);
   setDocumentAccessType(documentConentData.getAccessType());
   setDocumentType(documentConentData.getType());
 }
  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);
  }