@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());
  }
  @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);
  }
    public void run() {
      try {
        // wait for amount of time timer expires and plus 1s initially
        Thread.sleep(wait * 1000 + 1000);
        long processInstanceId = counter + 1;

        for (int y = 0; y < wait; y++) {
          RuntimeEngine runtime =
              manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
          try {
            testCompleteTaskByProcessInstance(manager, runtime, processInstanceId);
          } catch (Throwable e) {
            if (checkOptimiticLockException(e)) {
              logger.debug("{} retrying for process instance {}", counter, processInstanceId);
              manager.disposeRuntimeEngine(runtime);
              runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
              testRetryCompleteTaskByProcessInstance(manager, runtime, processInstanceId);
            } else {
              throw e;
            }
          }
          manager.disposeRuntimeEngine(runtime);
        }

        completedTask++;
      } catch (Throwable t) {
        t.printStackTrace();
      }
    }
  @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);
  }
Example #5
0
  @Deprecated
  public static StatefulKnowledgeSession loadStatefulKnowledgeSession(
      KnowledgeBase kbase, int sessionId) {
    Properties properties = getProperties();
    String persistenceEnabled = properties.getProperty("persistence.enabled", "false");
    RuntimeEnvironmentBuilder builder = null;
    if ("true".equals(persistenceEnabled)) {
      String dialect =
          properties.getProperty(
              "persistence.persistenceunit.dialect", "org.hibernate.dialect.H2Dialect");
      Map<String, String> map = new HashMap<String, String>();
      map.put("hibernate.dialect", dialect);
      EntityManagerFactory emf =
          Persistence.createEntityManagerFactory(
              properties.getProperty(
                  "persistence.persistenceunit.name", "org.jbpm.persistence.jpa"),
              map);

      builder =
          RuntimeEnvironmentBuilder.Factory.get()
              .newDefaultBuilder()
              .entityManagerFactory(emf)
              .addEnvironmentEntry(
                  EnvironmentName.TRANSACTION_MANAGER,
                  TransactionManagerServices.getTransactionManager());

    } else {
      builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder();
    }
    builder.knowledgeBase(kbase);
    RuntimeManager manager =
        RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(builder.get());
    return (StatefulKnowledgeSession) manager.getRuntimeEngine(EmptyContext.get()).getKieSession();
  }
  @Test
  public void testSinglePerRequestManager() {
    assertNotNull(perRequestManager);

    RuntimeEngine runtime = perRequestManager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(runtime);
    testProcessStartOnManager(runtime);
    perRequestManager.disposeRuntimeEngine(runtime);
  }
  @Test
  public void testSinglePerProcessInstanceManager() {
    assertNotNull(perProcessInstanceManager);

    RuntimeEngine runtime =
        perProcessInstanceManager.getRuntimeEngine(ProcessInstanceIdContext.get());
    assertNotNull(runtime);
    testProcessStartOnManager(runtime);
    perProcessInstanceManager.disposeRuntimeEngine(runtime);
  }
 public void run() {
   try {
     RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get());
     testStartProcess(runtime);
     manager.disposeRuntimeEngine(runtime);
     completedStart++;
   } catch (Throwable t) {
     t.printStackTrace();
   }
 }
  public void commonDeploy(
      DeploymentUnit unit,
      DeployedUnitImpl deployedUnit,
      RuntimeEnvironment environemnt,
      KieContainer kieContainer) {

    synchronized (this) {
      if (deploymentsMap.containsKey(unit.getIdentifier())) {
        DeployedUnit deployed = deploymentsMap.remove(unit.getIdentifier());
        RuntimeManager manager = deployed.getRuntimeManager();
        manager.close();
      }
      RuntimeManager manager = null;
      deploymentsMap.put(unit.getIdentifier(), deployedUnit);
      ((SimpleRuntimeEnvironment) environemnt)
          .addToEnvironment("IdentityProvider", identityProvider);
      try {
        switch (unit.getStrategy()) {
          case SINGLETON:
            manager = managerFactory.newSingletonRuntimeManager(environemnt, unit.getIdentifier());
            break;
          case PER_REQUEST:
            manager = managerFactory.newPerRequestRuntimeManager(environemnt, unit.getIdentifier());
            break;

          case PER_PROCESS_INSTANCE:
            manager =
                managerFactory.newPerProcessInstanceRuntimeManager(
                    environemnt, unit.getIdentifier());
            break;
          default:
            throw new IllegalArgumentException("Invalid strategy " + unit.getStrategy());
        }
        ((InternalRuntimeManager) manager).setKieContainer(kieContainer);
        deployedUnit.setRuntimeManager(manager);
        DeploymentDescriptor descriptor =
            ((InternalRuntimeManager) manager).getDeploymentDescriptor();
        List<String> requiredRoles = descriptor.getRequiredRoles(DeploymentDescriptor.TYPE_EXECUTE);
        if (requiredRoles != null && !requiredRoles.isEmpty()) {
          ((InternalRuntimeManager) manager)
              .setSecurityManager(
                  new IdentityRolesSecurityManager(identityProvider, requiredRoles));
        }
        notifyOnDeploy(unit, deployedUnit);

      } catch (Throwable e) {
        deploymentsMap.remove(unit.getIdentifier());
        if (manager != null) {
          manager.close();
        }
        notifyOnUnDeploy(unit, deployedUnit);
        throw new RuntimeException(e);
      }
    }
  }
Example #10
0
 @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();
 }
Example #11
0
 /**
  * Disposes currently active (in scope of a test) <code>RuntimeManager</code> together with all
  * active <code>RuntimeEngine</code>'s that were created (in scope of a test). Usual use case is
  * to simulate system shutdown.
  */
 protected void disposeRuntimeManager() {
   if (!activeEngines.isEmpty()) {
     for (RuntimeEngine engine : activeEngines) {
       manager.disposeRuntimeEngine(engine);
     }
     activeEngines.clear();
   }
   if (manager != null) {
     manager.close();
     manager = null;
   }
 }
  @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());
  }
Example #13
0
  public void signalEvent(String type, Object event) {
    String actualSignalType = type.replaceFirst(ASYNC_SIGNAL_PREFIX, "");

    ProcessPersistenceContextManager contextManager =
        (ProcessPersistenceContextManager)
            getKnowledgeRuntime().getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
    ProcessPersistenceContext context = contextManager.getProcessPersistenceContext();
    List<Long> processInstancesToSignalList =
        context.getProcessInstancesWaitingForEvent(actualSignalType);
    // handle signal asynchronously
    if (type.startsWith(ASYNC_SIGNAL_PREFIX)) {
      RuntimeManager runtimeManager =
          ((RuntimeManager) getKnowledgeRuntime().getEnvironment().get("RuntimeManager"));
      ExecutorService executorService =
          (ExecutorService) getKnowledgeRuntime().getEnvironment().get("ExecutorService");
      if (runtimeManager != null && executorService != null) {

        for (Long processInstanceId : processInstancesToSignalList) {
          CommandContext ctx = new CommandContext();
          ctx.setData("DeploymentId", runtimeManager.getIdentifier());
          ctx.setData("ProcessInstanceId", processInstanceId);
          ctx.setData("Signal", actualSignalType);
          ctx.setData("Event", event);

          executorService.scheduleRequest(AsyncSignalEventCommand.class.getName(), ctx);
        }

        return;
      } else {
        logger.warn(
            "Signal should be sent asynchronously but there is no executor service available, continuing sync...");
      }
    }

    for (long id : processInstancesToSignalList) {
      try {
        getKnowledgeRuntime().getProcessInstance(id);
      } catch (IllegalStateException e) {
        // IllegalStateException can be thrown when using RuntimeManager
        // and invalid ksession was used for given context
      } catch (RuntimeException e) {
        logger.warn(
            "Exception when loading process instance for signal '{}', instance with id {} will not be signaled",
            e.getMessage(),
            id);
      }
    }
    super.signalEvent(actualSignalType, event);
  }
 public void afterCompletion(int status) {
   try {
     manager.disposeRuntimeEngine(runtime);
   } catch (Throwable e) {
     // catch exception as it's only clean up and should not affect runtime
   }
 }
 @After
 public void teardown() {
   if (manager != null) {
     manager.close();
   }
   pds.close();
 }
  @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());
  }
 @After
 public void teardown() {
   globalScheduler.shutdown();
   if (manager != null) {
     manager.close();
   }
   emf.close();
 }
 /**
  * Disposes currently active (in scope of a test) <code>RuntimeManager</code> together with all
  * active <code>RuntimeEngine</code>'s that were created (in scope of a test). Usual use case is
  * to simulate system shutdown.
  */
 protected void disposeRuntimeManager() {
   if (!activeEngines.isEmpty()) {
     for (RuntimeEngine engine : activeEngines) {
       try {
         manager.disposeRuntimeEngine(engine);
       } catch (Exception e) {
         logger.debug(
             "Exception during dipose of runtime engine, might be already disposed - {}",
             e.getMessage());
       }
     }
     activeEngines.clear();
   }
   if (manager != null) {
     manager.close();
     manager = null;
   }
 }
  /**
   * 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;
  }
Example #20
0
 @After
 public void tearDown() throws Exception {
   clearHistory();
   if (setupDataSource) {
     if (emf != null) {
       emf.close();
       emf = null;
     }
     if (ds != null) {
       ds.close();
       ds = null;
     }
   }
   if (!activeEngines.isEmpty()) {
     for (RuntimeEngine engine : activeEngines) {
       manager.disposeRuntimeEngine(engine);
     }
   }
   if (manager != null) {
     manager.close();
     manager = null;
   }
 }
  @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());
  }
Example #22
0
  /**
   * 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;
  }
  @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());
  }
Example #24
0
  @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");
  }