@Before
 public void init() throws Exception {
   createRuntimeManager(HUMAN_TASK, HUMAN_TASK2);
   RuntimeEngine runtimeEngine = getRuntimeEngine();
   kieSession = runtimeEngine.getKieSession();
   taskService = (SynchronizedTaskService) runtimeEngine.getTaskService();
 }
  @Test
  public void testUserTaskFromKjar() {
    KieServices ks = KieServices.Factory.get();

    RuntimeEnvironment environment =
        RuntimeEnvironmentBuilder.Factory.get()
            .newDefaultBuilder(ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION))
            .userGroupCallback(userGroupCallback)
            .get();

    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();

    ProcessInstance processInstance = engine.getKieSession().startProcess("UserTask", params);

    List<TaskSummary> tasks =
        engine.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertNotNull(tasks);
    assertEquals(1, tasks.size());

    long taskId = tasks.get(0).getId();

    engine.getTaskService().start(taskId, "john");
    engine.getTaskService().complete(taskId, "john", null);

    processInstance = engine.getKieSession().getProcessInstance(processInstance.getId());
    assertNull(processInstance);

    manager.disposeRuntimeEngine(engine);
  }
  private boolean testRetryCompleteTaskByProcessInstance(
      RuntimeManager manager, RuntimeEngine runtime, long piId)
      throws InterruptedException, Exception {
    boolean result = false;
    List<Status> statusses = new ArrayList<Status>();
    statusses.add(Status.InProgress);

    List<TaskSummary> tasks = null;
    tasks = runtime.getTaskService().getTasksByStatusByProcessInstanceId(piId, statusses, "en-UK");
    if (tasks.isEmpty()) {
      logger.debug("Retry : Task thread found no tasks for piId {}", piId);
      Thread.sleep(1000);
    } else {
      long taskId = tasks.get(0).getId();
      logger.debug("Retry : Completing task {} piId {}", taskId, piId);
      try {

        runtime.getTaskService().complete(taskId, "john", null);
        logger.debug("Retry : Completed task {} piId {}", taskId, piId);
        result = true;

      } catch (PermissionDeniedException e) {
        // TODO can we avoid these by doing it all in one transaction?
        logger.debug("Task thread was too late for starting task {} piId {}", taskId, piId);
      } catch (Exception e) {
        throw e;
      }
    }

    return result;
  }
  @Test
  public void testDeploymentAndExecutionOfProcessWithImports() {

    assertNotNull(deploymentService);

    DeploymentUnit deploymentUnit = new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION);
    deploymentService.deploy(deploymentUnit);
    units.add(deploymentUnit);
    DeployedUnit deployedGeneral =
        deploymentService.getDeployedUnit(deploymentUnit.getIdentifier());
    assertNotNull(deployedGeneral);
    assertNotNull(deployedGeneral.getDeploymentUnit());
    assertNotNull(deployedGeneral.getRuntimeManager());

    RuntimeManager manager = deploymentService.getRuntimeManager(deploymentUnit.getIdentifier());
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();

    ProcessInstance processInstance = engine.getKieSession().startProcess("Import", params);

    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
  }
  @Override
  public RuntimeEngine getRuntimeEngine(Context<?> context) {
    if (isClosed()) {
      throw new IllegalStateException("Runtime manager " + identifier + " is already closed");
    }
    checkPermission();
    RuntimeEngine runtime = null;
    if (local.get() != null) {
      return local.get();
    }
    if (engineInitEager) {
      InternalTaskService internalTaskService =
          (InternalTaskService) taskServiceFactory.newTaskService();
      runtime = new RuntimeEngineImpl(factory.newKieSession(), internalTaskService);
      ((RuntimeEngineImpl) runtime).setManager(this);

      configureRuntimeOnTaskService(internalTaskService, runtime);
      registerDisposeCallback(runtime, new DisposeSessionTransactionSynchronization(this, runtime));
      registerDisposeCallback(
          runtime, new DestroySessionTransactionSynchronization(runtime.getKieSession()));
      registerItems(runtime);
      attachManager(runtime);
    } else {
      runtime = new RuntimeEngineImpl(context, new PerRequestInitializer());
      ((RuntimeEngineImpl) runtime).setManager(this);
    }
    local.set(runtime);
    return runtime;
  }
  @Test
  public void testScriptTaskFromKjarUsingNamedKbaseKsession() {
    KieServices ks = KieServices.Factory.get();

    RuntimeEnvironment environment =
        RuntimeEnvironmentBuilder.Factory.get()
            .newDefaultBuilder(
                ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION),
                "defaultKieBase",
                "defaultKieSession")
            .userGroupCallback(userGroupCallback)
            .get();

    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();

    ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
  }
  @Test
  public void testDeploymentOfProcessesKieConteinerInjection() {

    assertNotNull(deploymentService);

    KModuleDeploymentUnit deploymentUnit =
        new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION, "KBase-test", "ksession-test-2");

    deploymentService.deploy(deploymentUnit);
    units.add(deploymentUnit);

    assertNotNull(deploymentUnit.getDeploymentDescriptor());

    DeployedUnit deployed = deploymentService.getDeployedUnit(deploymentUnit.getIdentifier());
    assertNotNull(deployed);
    assertNotNull(deployed.getDeploymentUnit());
    assertNotNull(deployed.getRuntimeManager());
    assertNull(deployed.getDeployedAssetLocation("customtask"));
    assertEquals(
        GROUP_ID + ":" + ARTIFACT_ID + ":" + VERSION + ":" + "KBase-test" + ":" + "ksession-test-2",
        deployed.getDeploymentUnit().getIdentifier());

    RuntimeManager manager = deploymentService.getRuntimeManager(deploymentUnit.getIdentifier());
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("id", "test");
    ProcessInstance processInstance = engine.getKieSession().startProcess("customtask", params);

    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
    manager.disposeRuntimeEngine(engine);
  }
  private void testStartProcess(RuntimeEngine runtime) throws Exception {

    synchronized (
        (SingleSessionCommandService)
            ((CommandBasedStatefulKnowledgeSession) runtime.getKieSession()).getRunner()) {
      UserTransaction ut =
          (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
      try {
        ut.begin();
        logger.debug("Starting process on ksession {}", runtime.getKieSession().getIdentifier());
        Map<String, Object> params = new HashMap<String, Object>();
        DateTime now = new DateTime();
        now.plus(1000);

        params.put("x", "R2/" + wait + "/PT1S");
        ProcessInstance processInstance =
            runtime.getKieSession().startProcess("IntermediateCatchEvent", params);
        logger.debug(
            "Started process instance {} on ksession {}",
            processInstance.getId(),
            runtime.getKieSession().getIdentifier());
        ut.commit();
      } catch (Exception ex) {
        ut.rollback();
        throw ex;
      }
    }
  }
 @Override
 public void validate(KieSession ksession, Context<?> context) throws IllegalStateException {
   if (isClosed()) {
     throw new IllegalStateException("Runtime manager " + identifier + " is already closed");
   }
   RuntimeEngine runtimeInUse = local.get();
   if (runtimeInUse == null
       || runtimeInUse.getKieSession().getIdentifier() != ksession.getIdentifier()) {
     throw new IllegalStateException("Invalid session was used for this context " + context);
   }
 }
  /**
   * Returns new <code>RuntimeEngine</code> built from the manager of this test case. Common use
   * case is to maintain same session for process instance and thus <code>ProcessInstanceIdContext
   * </code> shall be used.
   *
   * @param context - instance of the context that shall be used to create <code>RuntimeManager
   *     </code>
   * @return new RuntimeEngine instance
   */
  protected RuntimeEngine getRuntimeEngine(Context<?> context) {
    if (manager == null) {
      throw new IllegalStateException(
          "RuntimeManager is not initialized, did you forgot to create it?");
    }

    RuntimeEngine runtimeEngine = manager.getRuntimeEngine(context);
    activeEngines.add(runtimeEngine);
    logService = new JPAAuditLogService(runtimeEngine.getKieSession().getEnvironment());

    return runtimeEngine;
  }
 @Test
 public void testProcess() {
   RuntimeManager manager = createRuntimeManager("hello.bpmn");
   RuntimeEngine runtimeEngine = getRuntimeEngine();
   KieSession ksession = runtimeEngine.getKieSession();
   ProcessInstance processInstance = ksession.startProcess("com.sample.bpmn.hello");
   // check whether the process instance has completed successfully
   assertProcessInstanceCompleted(processInstance.getId(), ksession);
   assertNodeTriggered(processInstance.getId(), "StartProcess", "Hello", "EndProcess");
   manager.disposeRuntimeEngine(runtimeEngine);
   manager.close();
 }
  @Test
  public void testDeploymentOfProcesses() {

    assertNotNull(deploymentService);

    KModuleDeploymentUnit deploymentUnit =
        new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION, "KBase-test", "ksession-test");

    deploymentService.deploy(deploymentUnit);
    units.add(deploymentUnit);

    assertNotNull(deploymentUnit.getDeploymentDescriptor());

    DeployedUnit deployed = deploymentService.getDeployedUnit(deploymentUnit.getIdentifier());
    assertNotNull(deployed);
    assertNotNull(deployed.getDeploymentUnit());
    assertNotNull(deployed.getRuntimeManager());
    assertNull(deployed.getDeployedAssetLocation("customtask"));
    assertEquals(
        GROUP_ID + ":" + ARTIFACT_ID + ":" + VERSION + ":" + "KBase-test" + ":" + "ksession-test",
        deployed.getDeploymentUnit().getIdentifier());

    assertNotNull(runtimeDataService);
    Collection<ProcessDefinition> processes = runtimeDataService.getProcesses(new QueryContext());
    assertNotNull(processes);
    assertEquals(3, processes.size());

    processes = runtimeDataService.getProcessesByFilter("custom", new QueryContext());
    assertNotNull(processes);
    assertEquals(1, processes.size());

    processes =
        runtimeDataService.getProcessesByDeploymentId(
            deploymentUnit.getIdentifier(), new QueryContext());
    assertNotNull(processes);
    assertEquals(3, processes.size());

    ProcessDefinition process = runtimeDataService.getProcessById("customtask");
    assertNotNull(process);

    RuntimeManager manager = deploymentService.getRuntimeManager(deploymentUnit.getIdentifier());
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("id", "test");
    ProcessInstance processInstance = engine.getKieSession().startProcess("customtask", params);

    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
  }
  @Test
  public void testTransactions() throws Exception {
    createRuntimeManager("humantask.bpmn");
    RuntimeEngine runtimeEngine = getRuntimeEngine();
    KieSession ksession = runtimeEngine.getKieSession();

    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ProcessInstance processInstance = ksession.startProcess("com.sample.bpmn.hello");
    ut.rollback();

    assertNull(ksession.getProcessInstance(processInstance.getId()));
  }
 @Override
 public KieSession initKieSession(
     Context<?> context, InternalRuntimeManager manager, RuntimeEngine engine) {
   RuntimeEngine inUse = local.get();
   if (inUse != null && ((RuntimeEngineImpl) inUse).internalGetKieSession() != null) {
     return inUse.getKieSession();
   }
   KieSession ksession = factory.newKieSession();
   ((RuntimeEngineImpl) engine).internalSetKieSession(ksession);
   registerDisposeCallback(
       engine, new DisposeSessionTransactionSynchronization(manager, engine));
   registerDisposeCallback(engine, new DestroySessionTransactionSynchronization(ksession));
   registerItems(engine);
   attachManager(engine);
   return ksession;
 }
  @Test
  public void testRestExecuteTaskCommands() throws Exception {
    RuntimeEngine engine =
        new RemoteRestSessionFactory(DEPLOYMENT_ID, deploymentUrl.toExternalForm())
            .newRuntimeEngine();
    KieSession ksession = engine.getKieSession();
    ProcessInstance processInstance = ksession.startProcess("org.jbpm.humantask");

    long processInstanceId = processInstance.getId();
    JaxbCommandResponse<?> response =
        executeTaskCommand(
            DEPLOYMENT_ID, new GetTasksByProcessInstanceIdCommand(processInstanceId));

    long taskId = ((JaxbLongListResponse) response).getResult().get(0);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("userId", USER_ID);
  }
  /**
   * Returns new <code>RuntimeEngine</code> built from the manager of this test case. Common use
   * case is to maintain same session for process instance and thus <code>ProcessInstanceIdContext
   * </code> shall be used.
   *
   * @param context - instance of the context that shall be used to create <code>RuntimeManager
   *     </code>
   * @return new RuntimeEngine instance
   */
  protected RuntimeEngine getRuntimeEngine(Context<?> context) {
    if (manager == null) {
      throw new IllegalStateException(
          "RuntimeManager is not initialized, did you forgot to create it?");
    }

    RuntimeEngine runtimeEngine = manager.getRuntimeEngine(context);
    activeEngines.add(runtimeEngine);
    if (sessionPersistence) {
      logService = new JPAAuditLogService(runtimeEngine.getKieSession().getEnvironment());

    } else {
      inMemoryLogger =
          new WorkingMemoryInMemoryLogger((StatefulKnowledgeSession) runtimeEngine.getKieSession());
    }

    return runtimeEngine;
  }
  public static void main(String[] args) {
    if (args.length == 1 && ("-h".equals(args[0]) || "--help".equals(args[0]))) {
      System.out.println("In order to invoke this class, you should:");
      System.out.println(
          " - Install the kie-wb-edition WAR file inside a JBoss7 (at standalone/deployments/kie-wb.war)");
      System.out.println(
          " - Start the JBoss7 server with bin/standalone.sh --server-config=standalone-full.xml");
      System.out.println(" - Deploy the HR project in the jbpm-playground default repository");
      System.out.println(
          " - Make sure you have a user called mariano, with password mypass, and roles admin and guest");
      System.out.println(" - Then run this test");
      System.exit(-1);
    }
    try {
      System.out.println("Creating JMS context ...");
      InitialContext ctx = new InitialContext();
      QueueConnectionFactory connFactory =
          (QueueConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory");
      Connection conn = connFactory.createConnection("mariano", "mypass");
      Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
      Queue ksessionQueue = (Queue) ctx.lookup("jms/queue/KIE.SESSION");
      Queue taskQueue = (Queue) ctx.lookup("jms/queue/KIE.TASK");
      Queue responseQueue = (Queue) ctx.lookup("jms/queue/KIE.RESPONSE");
      System.out.println("Creating JMS Runtime Factory...");

      RuntimeEngine engine =
          RemoteJmsRuntimeEngineFactoryBuilderImpl.newBuilder()
              .addDeploymentId("org.jbpm:HR:1.0")
              .addConnectionFactory(connFactory)
              .addKieSessionQueue(ksessionQueue)
              .addTaskServiceQueue(taskQueue)
              .addResponseQueue(responseQueue)
              .addUserName("mariano")
              .addPassword("mypass")
              .build()
              .newRuntimeEngine();

      engine.getKieSession().signalEvent("my-signal", "");
    } catch (Exception e) {
      System.out.println("An error has occurred: " + e.getMessage());
      e.printStackTrace(System.out);
    }
  }
  @Test
  public void testScriptTaskFromClasspathContainerNamedKbaseKsession() {

    RuntimeEnvironment environment =
        RuntimeEnvironmentBuilder.Factory.get()
            .newClasspathKmoduleDefaultBuilder("defaultKieBase", "defaultKieSession")
            .userGroupCallback(userGroupCallback)
            .get();

    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();

    ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
  }
  @Test
  @Ignore("JMS isn't working.. :/")
  public void testJmsRemoteApiHumanTaskProcess() throws Exception {
    // create JMS request
    RuntimeEngine engine =
        new RemoteJmsRuntimeEngineFactory(DEPLOYMENT_ID, getRemoteInitialContext())
            .newRuntimeEngine();
    KieSession ksession = engine.getKieSession();
    ProcessInstance processInstance = ksession.startProcess("org.jbpm.humantask");

    logger.debug(
        "Started process instance: "
            + processInstance
            + " "
            + (processInstance == null ? "" : processInstance.getId()));

    TaskService taskService = engine.getTaskService();
    List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner(USER_ID, "en-UK");
    long taskId = findTaskId(processInstance.getId(), tasks);

    logger.debug("Found task " + taskId);
    Task task = taskService.getTaskById(taskId);
    logger.debug("Got task " + taskId + ": " + task);
    taskService.start(taskId, USER_ID);
    taskService.complete(taskId, USER_ID, null);

    logger.debug("Now expecting failure");
    try {
      taskService.complete(taskId, USER_ID, null);
      fail("Should not have been able to complete task " + taskId + " a second time.");
    } catch (Throwable t) {
      // do nothing
    }

    List<Status> statuses = new ArrayList<Status>();
    statuses.add(Status.Reserved);
    List<TaskSummary> taskIds =
        taskService.getTasksByStatusByProcessInstanceId(processInstance.getId(), statuses, "en-UK");
    assertEquals("Expected 2 tasks.", 2, taskIds.size());
  }
  private void testProcessStartOnManager(RuntimeEngine runtime) {

    KieSession ksession = runtime.getKieSession();
    assertNotNull(ksession);

    ProcessInstance processInstance = ksession.startProcess("UserTask");
    assertNotNull(processInstance);

    List<Status> statuses = new ArrayList<Status>();
    statuses.add(Status.Reserved);
    List<TaskSummary> tasks =
        runtime.getTaskService().getTasksOwnedByStatus("john", statuses, "en-UK");
    assertNotNull(tasks);
    assertEquals(1, tasks.size());

    runtime.getTaskService().start(tasks.get(0).getId(), "john");

    runtime.getTaskService().complete(tasks.get(0).getId(), "john", null);

    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNull(processInstance);
  }
  @Test
  public void processInstanceWithVariablesTest() throws Exception {

    this.setupDataSource = true;
    this.sessionPersistence = true;
    super.setUp();

    RuntimeEngine runtimeEngine =
        createRuntimeManager("BPMN2-StringStructureRef.bpmn2").getRuntimeEngine(null);
    KieSession ksession = runtimeEngine.getKieSession();

    Map<String, Object> params = new HashMap<String, Object>();
    String val = "initial-val";
    params.put("test", val);
    ProcessInstance processInstance = ksession.startProcess("StructureRef");
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    Map<String, Object> res = new HashMap<String, Object>();
    res.put("testHT", "test value");
    // ksession.getWorkItemManager().completeWorkItem(workItemHandler.getWorkItem().getId(),
    // res);

    Map<String, String> map = new HashMap<String, String>();
    map.put("test", "initial-val");

    JaxbProcessInstanceWithVariablesResponse jpiwvr =
        new JaxbProcessInstanceWithVariablesResponse(processInstance, map);
    testRoundTrip(jpiwvr);

    JaxbProcessInstanceListResponse jpilp = new JaxbProcessInstanceListResponse();
    List<ProcessInstance> procInstList = new ArrayList<ProcessInstance>();
    procInstList.add(new JaxbProcessInstanceResponse(processInstance));
    jpilp.setResult(procInstList);
    testRoundTrip(jpilp);

    super.tearDown();
    this.setupDataSource = false;
    this.sessionPersistence = false;
  }
  @Test
  public void testUnDeploymentWithActiveProcesses() {

    assertNotNull(deploymentService);

    DeploymentUnit deploymentUnit = new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION);
    deploymentService.deploy(deploymentUnit);
    units.add(deploymentUnit);
    DeployedUnit deployedGeneral =
        deploymentService.getDeployedUnit(deploymentUnit.getIdentifier());
    assertNotNull(deployedGeneral);
    assertNotNull(deployedGeneral.getDeploymentUnit());
    assertNotNull(deployedGeneral.getRuntimeManager());

    RuntimeManager manager = deploymentService.getRuntimeManager(deploymentUnit.getIdentifier());
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();

    ProcessInstance processInstance =
        engine.getKieSession().startProcess("org.jbpm.writedocument", params);

    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    try {
      // undeploy should fail due to active process instances
      deploymentService.undeploy(deploymentUnit);
      fail("Should fail due to active process instance");
    } catch (IllegalStateException e) {

    }

    engine.getKieSession().abortProcessInstance(processInstance.getId());
  }
 @Override
 public void disposeRuntimeEngine(RuntimeEngine runtime) {
   if (isClosed()) {
     throw new IllegalStateException("Runtime manager " + identifier + " is already closed");
   }
   local.set(null);
   try {
     if (canDestroy(runtime)) {
       runtime.getKieSession().destroy();
     } else {
       if (runtime instanceof Disposable) {
         ((Disposable) runtime).dispose();
       }
     }
   } catch (Exception e) {
     // do nothing
     if (runtime instanceof Disposable) {
       ((Disposable) runtime).dispose();
     }
   }
 }
  @Test
  public void testSupportProcess() {
    DeploymentUnit deploymentUnitSupport =
        new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION);
    deploymentService.deploy(deploymentUnitSupport);
    units.add(deploymentUnitSupport);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("customer", "polymita");

    RuntimeManager managerSupport =
        deploymentService.getRuntimeManager(deploymentUnitSupport.getIdentifier());
    assertNotNull(managerSupport);

    RuntimeEngine engine = managerSupport.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);
    ProcessInstance pI = engine.getKieSession().startProcess("support.process", params);
    assertNotNull(pI);
    TaskService taskService = engine.getTaskService();

    // Configure Release
    List<TaskSummary> tasksAssignedToSalaboy =
        taskService.getTasksAssignedAsPotentialOwner("salaboy", "en-UK");

    assertEquals(1, tasksAssignedToSalaboy.size());
    assertEquals("Create Support", tasksAssignedToSalaboy.get(0).getName());

    TaskSummary createSupportTask = tasksAssignedToSalaboy.get(0);

    taskService.start(createSupportTask.getId(), "salaboy");

    Map<String, Object> taskContent =
        ((InternalTaskService) taskService).getTaskContent(createSupportTask.getId());

    assertEquals("polymita", taskContent.get("input_customer"));

    Map<String, String> taskOutputMappings =
        bpmn2Service.getTaskOutputMappings(
            deploymentUnitSupport.getIdentifier(), "support.process", createSupportTask.getName());

    assertEquals(1, taskOutputMappings.size());
    assertEquals("output_customer", taskOutputMappings.values().iterator().next());

    Map<String, Object> output = new HashMap<String, Object>();

    output.put("output_customer", "polymita/redhat");
    taskService.complete(createSupportTask.getId(), "salaboy", output);

    tasksAssignedToSalaboy = taskService.getTasksAssignedAsPotentialOwner("salaboy", "en-UK");
    assertEquals(1, tasksAssignedToSalaboy.size());

    assertEquals("Resolve Support", tasksAssignedToSalaboy.get(0).getName());

    TaskSummary resolveSupportTask = tasksAssignedToSalaboy.get(0);

    taskService.start(resolveSupportTask.getId(), "salaboy");

    taskService.complete(resolveSupportTask.getId(), "salaboy", null);

    tasksAssignedToSalaboy = taskService.getTasksAssignedAsPotentialOwner("salaboy", "en-UK");
    assertEquals(1, tasksAssignedToSalaboy.size());

    assertEquals("Notify Customer", tasksAssignedToSalaboy.get(0).getName());

    TaskSummary notifySupportTask = tasksAssignedToSalaboy.get(0);

    taskService.start(notifySupportTask.getId(), "salaboy");
    output = new HashMap<String, Object>();
    output.put("output_solution", "solved today");
    taskService.complete(notifySupportTask.getId(), "salaboy", output);
  }
  @Test
  public void testDeploymentOfProcessWithDescriptorKieConteinerInjection() {

    assertNotNull(deploymentService);

    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId(GROUP_ID, "kjar-with-dd", VERSION);
    List<String> processes = new ArrayList<String>();
    processes.add("repo/processes/general/customtask.bpmn");
    processes.add("repo/processes/general/humanTask.bpmn");
    processes.add("repo/processes/general/import.bpmn");

    DeploymentDescriptor customDescriptor = new DeploymentDescriptorImpl("org.jbpm.domain");
    customDescriptor
        .getBuilder()
        .runtimeStrategy(RuntimeStrategy.PER_REQUEST)
        .addWorkItemHandler(
            new NamedObjectModel(
                "mvel",
                "Log",
                "new org.jbpm.kie.services.test.objects.KieConteinerSystemOutWorkItemHandler(kieContainer)"));

    Map<String, String> resources = new HashMap<String, String>();
    resources.put(
        "src/main/resources/" + DeploymentDescriptor.META_INF_LOCATION, customDescriptor.toXml());

    InternalKieModule kJar1 = createKieJar(ks, releaseId, processes, resources);
    File pom = new File("target/kmodule", "pom.xml");
    pom.getParentFile().mkdir();
    try {
      FileOutputStream fs = new FileOutputStream(pom);
      fs.write(getPom(releaseId).getBytes());
      fs.close();
    } catch (Exception e) {

    }
    MavenRepository repository = getMavenRepository();
    repository.deployArtifact(releaseId, kJar1, pom);

    DeploymentUnit deploymentUnit =
        new KModuleDeploymentUnit(
            GROUP_ID, "kjar-with-dd", VERSION, "KBase-test", "ksession-test2");
    deploymentService.deploy(deploymentUnit);
    units.add(deploymentUnit);
    DeployedUnit deployedGeneral =
        deploymentService.getDeployedUnit(deploymentUnit.getIdentifier());
    assertNotNull(deployedGeneral);
    assertNotNull(deployedGeneral.getDeploymentUnit());
    assertNotNull(deployedGeneral.getRuntimeManager());

    DeploymentDescriptor descriptor =
        ((InternalRuntimeManager) deployedGeneral.getRuntimeManager()).getDeploymentDescriptor();
    assertNotNull(descriptor);
    assertEquals("org.jbpm.domain", descriptor.getPersistenceUnit());
    assertEquals("org.jbpm.domain", descriptor.getAuditPersistenceUnit());
    assertEquals(AuditMode.JPA, descriptor.getAuditMode());
    assertEquals(PersistenceMode.JPA, descriptor.getPersistenceMode());
    assertEquals(RuntimeStrategy.PER_REQUEST, descriptor.getRuntimeStrategy());
    assertEquals(0, descriptor.getMarshallingStrategies().size());
    assertEquals(0, descriptor.getConfiguration().size());
    assertEquals(0, descriptor.getEnvironmentEntries().size());
    assertEquals(0, descriptor.getEventListeners().size());
    assertEquals(0, descriptor.getGlobals().size());
    assertEquals(0, descriptor.getTaskEventListeners().size());
    assertEquals(1, descriptor.getWorkItemHandlers().size());
    assertEquals(0, descriptor.getRequiredRoles().size());

    RuntimeManager manager = deploymentService.getRuntimeManager(deploymentUnit.getIdentifier());
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();

    ProcessInstance processInstance = engine.getKieSession().startProcess("customtask", params);

    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
    manager.disposeRuntimeEngine(engine);
  }
  @Test
  public void testSessionPerProcessInstance() throws Exception {
    RuntimeEnvironment environment =
        RuntimeEnvironmentBuilder.Factory.get()
            .newDefaultBuilder()
            .entityManagerFactory(emf)
            .userGroupCallback(userGroupCallback)
            .addAsset(
                ResourceFactory.newClassPathResource(
                    "org/jbpm/test/functional/timer/IntermediateCatchEventTimerCycleWithHT.bpmn2"),
                ResourceType.BPMN2)
            .schedulerService(globalScheduler)
            .get();

    long startTimeStamp = System.currentTimeMillis();
    long maxEndTime = startTimeStamp + maxWaitTime;

    manager = RuntimeManagerFactory.Factory.get().newPerProcessInstanceRuntimeManager(environment);
    // prepare task service with users and groups
    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    TaskService taskService = engine.getTaskService();

    Group grouphr = TaskModelProvider.getFactory().newGroup();
    ((InternalOrganizationalEntity) grouphr).setId("HR");

    User mary = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) mary).setId("mary");
    User john = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) john).setId("john");

    ((InternalTaskService) taskService).addGroup(grouphr);
    ((InternalTaskService) taskService).addUser(mary);
    ((InternalTaskService) taskService).addUser(john);

    manager.disposeRuntimeEngine(engine);

    completedStart = 0;
    for (int i = 0; i < nbThreadsProcess; i++) {
      new StartProcessPerProcessInstanceRunnable(manager, i).run();
    }
    completedTask = 0;
    for (int i = 0; i < nbThreadsTask; i++) {
      new Thread(new CompleteTaskPerProcessInstanceRunnable(manager, i)).start();
    }
    while (completedStart < nbThreadsProcess || completedTask < nbThreadsTask) {
      Thread.sleep(100);
      if (System.currentTimeMillis() > maxEndTime) {
        fail("Failure, did not finish in time most likely hanging");
      }
    }
    // make sure all process instance were completed
    engine = manager.getRuntimeEngine(EmptyContext.get());
    AuditService logService = engine.getAuditService();
    // active
    List<? extends ProcessInstanceLog> logs =
        logService.findActiveProcessInstances("IntermediateCatchEvent");
    assertNotNull(logs);
    for (ProcessInstanceLog log : logs) {
      logger.debug("Left over {}", log.getProcessInstanceId());
    }
    assertEquals(0, logs.size());

    // completed
    logs = logService.findProcessInstances("IntermediateCatchEvent");
    assertNotNull(logs);
    assertEquals(nbThreadsProcess, logs.size());
    manager.disposeRuntimeEngine(engine);

    logger.debug("Done");
  }