@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());
  }
  @POST
  @Path("/withvars/process/instance/{procInstId: [0-9]+}/signal")
  public Response withvars_process_instance_procInstid_signal(
      @PathParam("procInstId") Long procInstId) {
    String oper = getRelativePath(uriInfo);
    Map<String, List<String>> params = getRequestParams(uriInfo);
    String eventType = getStringParam("signal", true, params, oper);
    Object event = getObjectParam("event", false, params, oper);
    String errorMsg = "Unable to signal process instance " + procInstId;
    if (eventType == null) {
      errorMsg += " with empty signal";
    } else {
      errorMsg += " with signal type '" + eventType + "'";
    }
    if (event != null) {
      errorMsg += " and event '" + event + "'";
    }

    processRequestBean.doKieSessionOperation(
        new SignalEventCommand(procInstId, eventType, event), deploymentId, procInstId, errorMsg);

    ProcessInstance processInstance = getProcessInstance(procInstId);
    Map<String, String> vars = getVariables(processInstance.getId());

    return createCorrectVariant(
        new JaxbProcessInstanceWithVariablesResponse(processInstance, vars), headers);
  }
  @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);
  }
  @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 processInstanceWithVariablesTest() throws Exception {
    KieSession ksession = createKnowledgeSession("BPMN2-StringStructureRef.bpmn2");
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);

    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);
  }
  @Test
  public void testPersistenceRuleSet() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("RuleSetProcess.rf"), ResourceType.DRF);
    kbuilder.add(new ClassPathResource("RuleSetRules.drl"), ResourceType.DRL);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    long id = ksession.getIdentifier();

    ksession.insert(new ArrayList<Object>());

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ProcessInstance processInstance = ksession.startProcess("org.drools.test.TestProcess");

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ksession.fireAllRules();
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNull(processInstance);
  }
  @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);
  }
Esempio n. 8
0
  @Test(timeout = 30000)
  public void testAsyncWorkItem() throws Exception {

    ExecutorService executorService = ExecutorServiceFactory.newExecutorService();
    executorService.setThreadPoolSize(1);
    executorService.setInterval(1);
    executorService.setRetries(2);
    executorService.init();

    addWorkItemHandler("async", new AsyncWorkItemHandler(executorService));

    addWorkItemHandler("Milestone", new SystemOutWorkItemHandler());
    KieSession ksession = createKSession(TERMINATE_CASE);
    RuntimeEngine runtimeEngine = getRuntimeEngine();
    CaseMgmtService caseMgmtService = new CaseMgmtUtil(runtimeEngine);
    ProcessInstance pi = caseMgmtService.startNewCase("AsyncWorkItem");
    long pid = pi.getId();

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("CommandClass", CheckCallCommand.class.getCanonicalName());
    caseMgmtService.createDynamicWorkTask(pid, "async", params);

    // This will time out if the barrier waits for longer than 5 seconds.
    // The .await(..) call will only timeout (throw an exception) if the
    //   other party (that is calling .execute(CommandContext)) has *not* also
    //   called await (in CheckCallCommand.execute(CommandContext)
    // In this way, it's also a check to see if the command has executed
    CheckCallCommand.getBarrier().await(5, TimeUnit.SECONDS);

    caseMgmtService.triggerAdHocFragment(pid, "Terminate");
  }
Esempio n. 9
0
  @Test
  public void testCancelNonRegisteredWorkItemHandler() {
    String processId = "org.drools.actions";
    String workName = "Unnexistent Task";
    RuleFlowProcess process = getWorkItemProcess(processId, workName);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    ((AbstractRuleBase) ((InternalKnowledgeBase) kbase).getRuleBase()).addProcess(process);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.getWorkItemManager().registerWorkItemHandler(workName, new DoNothingWorkItemHandler());

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("UserName", "John Doe");
    parameters.put("Person", new Person("John Doe"));

    ProcessInstance processInstance = ksession.startProcess("org.drools.actions", parameters);
    long processInstanceId = processInstance.getId();
    Assert.assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    ksession.getWorkItemManager().registerWorkItemHandler(workName, null);

    try {
      ksession.abortProcessInstance(processInstanceId);
      Assert.fail("should fail if WorkItemHandler for" + workName + "is not registered");
    } catch (WorkItemHandlerNotFoundException wihnfe) {

    }

    Assert.assertEquals(ProcessInstance.STATE_ABORTED, processInstance.getState());
  }
  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;
      }
    }
  }
  @POST
  @Produces(MediaType.APPLICATION_XML)
  @Path("/withvars/process/instance/{procInstId: [0-9]+}/signal")
  public JaxbProcessInstanceWithVariablesResponse signalProcessInstanceWithVars(
      @PathParam("procInstId") Long procInstId) {
    Map<String, List<String>> params = getRequestParams(request);
    String eventType = getStringParam("eventType", true, params, "signal");
    Object event = getObjectParam("event", false, params, "signal");
    Command<?> cmd = new SignalEventCommand(procInstId, eventType, event);
    String errorMsg = "Unable to signal process instance " + procInstId;
    if (eventType == null) {
      errorMsg += " with empty signal";
    } else {
      errorMsg += " with signal type '" + eventType + "'";
    }
    if (event != null) {
      errorMsg += " and event '" + event + "'";
    }
    internalDoKieSessionOperation(cmd, errorMsg);

    cmd = new GetProcessInstanceCommand(procInstId);
    ((GetProcessInstanceCommand) cmd).setReadOnly(true);
    Object result =
        internalDoKieSessionOperation(cmd, "Unable to get process instance " + procInstId);
    ProcessInstance processInstance = (ProcessInstance) result;

    Map<String, String> vars = getVariables(processInstance.getId());

    return new JaxbProcessInstanceWithVariablesResponse(processInstance, vars);
  }
  @Test
  public void testPersistenceTimer2() throws Exception {
    KieSession service = (KieSession) ctx.getBean("jpaSingleSessionCommandService2");

    int sessionId = service.getId();

    ProcessInstance processInstance = service.startProcess("org.drools.test.ProcessTimer2");
    log.info("Started process instance {}", processInstance.getId());

    Thread.sleep(2000);

    final Environment env = (Environment) ctx.getBean("env");
    /*
    Environment env = KnowledgeBaseFactory.newEnvironment();
    env.set( EnvironmentName.ENTITY_MANAGER_FACTORY,
             ctx.getBean( "myEmf" ) );
    env.set( EnvironmentName.TRANSACTION_MANAGER,
             ctx.getBean( "txManager" ) );
    */
    KieStoreServices kstore = (KieStoreServices) ctx.getBean("kstore1");
    KieBase kbase1 = (KieBase) ctx.getBean("kb_persistence");
    service = kstore.loadKieSession(sessionId, kbase1, null, env);

    processInstance = service.getProcessInstance(processInstance.getId());
    assertNull(processInstance);
  }
  @Test
  public void testPersistenceWorkItems2() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("WorkItemsProcess.rf"), ResourceType.DRF);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    long id = ksession.getIdentifier();

    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();

    ProcessInstance processInstance = ksession.startProcess("org.drools.test.TestProcess");
    ksession.insert("TestString");
    logger.debug("Started process instance " + processInstance.getId());

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

    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);

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

    ut.commit();

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);

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

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);

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

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertEquals(1, ksession.getObjects().size());
    for (Object o : ksession.getObjects()) {
      logger.debug(o.toString());
    }
    assertNull(processInstance);
  }
  @Test
  public void startProcessTest() {
    StatefulKnowledgeSession ksession = createProcessSession();

    ProcessInstance processInstance = ksession.startProcess("Minimal");

    Assert.assertNotNull(processInstance);

    Assert.assertEquals("Minimal", processInstance.getProcessId());
  }
  @Test
  public void startProcessWithParametersTest() {
    StatefulKnowledgeSession ksession = createProcessSession();
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("long", 1L);
    ProcessInstance processInstance = ksession.startProcess("Minimal", parameters);

    Assert.assertNotNull(processInstance);

    Assert.assertEquals("Minimal", processInstance.getProcessId());
  }
Esempio n. 16
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();
 }
  @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());
  }
Esempio n. 18
0
  @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()));
  }
Esempio n. 19
0
  @Test
  public void testEvaluationProcess() {
    KieSession ksession = createKnowledgeSession("Step1.bpmn");
    KieRuntimeLogger log =
        KieServices.Factory.get().getLoggers().newThreadedFileLogger(ksession, "test", 1000);
    TaskService taskService = getTaskService();

    // start a new process instance
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("employee", "krisv");
    params.put("reason", "Yearly performance evaluation");
    ProcessInstance processInstance = ksession.startProcess("com.sample.evaluation", params);
    System.out.println("Process started ...");

    // complete Self Evaluation
    List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("krisv", "en-UK");
    assertEquals(1, tasks.size());
    TaskSummary task = tasks.get(0);
    System.out.println("'krisv' completing task " + task.getName() + ": " + task.getDescription());
    taskService.start(task.getId(), "krisv");
    Map<String, Object> results = new HashMap<String, Object>();
    results.put("performance", "exceeding");
    taskService.complete(task.getId(), "krisv", results);

    // john from HR
    tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(1, tasks.size());
    task = tasks.get(0);
    System.out.println("'john' completing task " + task.getName() + ": " + task.getDescription());
    taskService.claim(task.getId(), "john");
    taskService.start(task.getId(), "john");
    results = new HashMap<String, Object>();
    results.put("performance", "acceptable");
    taskService.complete(task.getId(), "john", results);

    // mary from PM
    tasks = taskService.getTasksAssignedAsPotentialOwner("mary", "en-UK");
    assertEquals(1, tasks.size());
    task = tasks.get(0);
    System.out.println("'mary' completing task " + task.getName() + ": " + task.getDescription());
    taskService.claim(task.getId(), "mary");
    taskService.start(task.getId(), "mary");
    results = new HashMap<String, Object>();
    results.put("performance", "outstanding");
    taskService.complete(task.getId(), "mary", results);

    assertProcessInstanceCompleted(processInstance.getId(), ksession);
    System.out.println("Process instance completed");
    log.close();
  }
  @Test
  public void testPersistenceWorkItems3() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("WorkItemsProcess.rf"), ResourceType.DRF);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    ksession.getWorkItemManager().registerWorkItemHandler("MyWork", new SystemOutWorkItemHandler());
    ProcessInstance processInstance = ksession.startProcess("org.drools.test.TestProcess");
    ksession.insert("TestString");
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
  }
  @Test
  public void testPersistenceVariables() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("VariablesProcess.rf"), ResourceType.DRF);
    for (KnowledgeBuilderError error : kbuilder.getErrors()) {
      logger.debug(error.toString());
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    long id = ksession.getIdentifier();

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("name", "John Doe");
    ProcessInstance processInstance =
        ksession.startProcess("org.drools.test.TestProcess", parameters);

    TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("John Doe", workItem.getParameter("name"));

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);

    workItem = handler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("John Doe", workItem.getParameter("text"));

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);

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

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNull(processInstance);
  }
  @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);
  }
  @Test
  public void testPersistenceTimer() throws Exception {
    System.out.println("TMPDIR == " + TMPDIR);
    log.info("---> get bean jpaSingleSessionCommandService2");
    KieSession service = (KieSession) ctx.getBean("jpaSingleSessionCommandService2");

    int sessionId = service.getId();
    log.info("---> created SingleSessionCommandService id: " + sessionId);

    ProcessInstance processInstance = service.startProcess("org.drools.test.ProcessTimer");
    long procId = processInstance.getId();
    log.info("---> Started ProcessTimer id: {}", procId);

    service.dispose();
    log.info("---> session disposed");

    final Environment env = (Environment) ctx.getBean("env");
    /*
    Environment env = KnowledgeBaseFactory.newEnvironment();
    env.set( EnvironmentName.ENTITY_MANAGER_FACTORY,
             ctx.getBean( "myEmf" ) );
    env.set( EnvironmentName.TRANSACTION_MANAGER,
             ctx.getBean( "txManager" ) );
    */
    KieStoreServices kstore = (KieStoreServices) ctx.getBean("kstore1");
    KieBase kbase1 = (KieBase) ctx.getBean("kb_persistence");
    service = kstore.loadKieSession(sessionId, kbase1, null, env);

    log.info("---> load session: " + sessionId);
    processInstance = service.getProcessInstance(procId);
    log.info("---> GetProcessInstanceCommand id: " + procId);
    assertNotNull(processInstance);

    Thread.sleep(1000);
    log.info("---> session disposed");
    service.dispose();

    service = kstore.loadKieSession(sessionId, kbase1, null, env);
    log.info("---> load session: " + sessionId);
    Thread.sleep(3000);

    log.info("---> GetProcessInstanceCommand id: " + procId);
    processInstance = service.getProcessInstance(procId);
    log.info("---> session disposed");
    assertNull(processInstance);
  }
  public ProcessInstance execute(Context context) {
    KieSession ksession = ((KnowledgeCommandContext) context).getKieSession();

    if (data != null) {
      for (Object o : data) {
        ksession.insert(o);
      }
    }
    ProcessInstance processInstance =
        (ProcessInstance) ksession.createProcessInstance(processId, parameters);
    if (this.outIdentifier != null) {
      ((ExecutionResultImpl) ((KnowledgeCommandContext) context).getExecutionResults())
          .getResults()
          .put(this.outIdentifier, processInstance.getId());
    }
    return processInstance;
  }
  protected long[] runObjectVarProcess(KieSession ksession) {
    long[] pids = new long[3];

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("myobject", "Hello World!");

    ProcessInstance pi = ksession.startProcess(OBJECT_VARIABLE_PROCESS_ID, params); // completed
    pids[0] = pi.getId();
    params.put("myobject", "Hello Ivo!");
    pi = ksession.startProcess(OBJECT_VARIABLE_PROCESS_ID, params); // completed
    pids[1] = pi.getId();
    params.put("myobject", "Bye Ivo!");
    pi = ksession.startProcess(OBJECT_VARIABLE_PROCESS_ID, params); // completed
    pids[2] = pi.getId();

    return pids;
  }
  @Test
  public void testPersistenceSubProcess() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("SuperProcess.rf"), ResourceType.DRF);
    kbuilder.add(new ClassPathResource("SubProcess.rf"), ResourceType.DRF);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    long id = ksession.getIdentifier();

    ProcessInstance processInstance = ksession.startProcess("com.sample.SuperProcess");
    logger.debug("Started process instance " + processInstance.getId());

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

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);

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

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);

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

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNull("Process did not complete.", processInstance);
  }
  @Test
  public void testSubjectProperty() {
    ProcessInstance processInstance = kieSession.startProcess(HUMAN_TASK2_ID);

    List<TaskSummary> list = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
    TaskSummary task = list.get(0);

    Task t = taskService.getTaskById(task.getId());

    Assertions.assertThat(task.getDescription()).isEqualTo(EXPECTED_SUBJECT);
    Assertions.assertThat(task.getSubject()).isNullOrEmpty();
    Assertions.assertThat(t.getSubject()).isEqualTo(EXPECTED_SUBJECT);

    taskService.start(task.getId(), "john");
    taskService.complete(task.getId(), "john", null);

    ProcessInstanceLog plog = getLogService().findProcessInstance(processInstance.getId());

    Assertions.assertThat(plog.getStatus()).isEqualTo(ProcessInstance.STATE_COMPLETED);
  }
Esempio n. 28
0
  @Test
  @Transactional(value = TransactionMode.DEFAULT)
  public void testSimpleProcess() throws Exception {
    final String processString = "testProj.testProcess";
    final String variableKey = "processString";

    Map<String, Object> processVariables = new HashMap<String, Object>();
    processVariables.put(variableKey, "Initial");

    StartProcessCommand startProcess = new StartProcessCommand(processString, processVariables);
    String correlationId = cmdExecutor.execute(kri, startProcess);
    ProcessInstance processInstance = null;
    int count = 0;
    while (processInstance == null && count < 1) {
      processInstance = (ProcessInstance) cmdExecutor.pollResponse(correlationId);
      count += 1;
    }

    assertEquals(1, processInstance.getState());
  }
  @Test
  public void commandsResponseTest() throws Exception {
    KieSession ksession = createKnowledgeSession("BPMN2-StringStructureRef.bpmn2");
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);

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

    JaxbCommandsResponse resp = new JaxbCommandsResponse();
    resp.setDeploymentId("deploy");
    resp.setProcessInstanceId(processInstance.getId());
    resp.addResult(processInstance, 0, cmd);

    testRoundtrip(resp);
  }
  /** WithVars methods */
  @POST
  @Produces(MediaType.APPLICATION_XML)
  @Path("/withvars/process/{processDefId: [_a-zA-Z0-9-:\\.]+}/start")
  public JaxbProcessInstanceWithVariablesResponse startNewProcessWithVars(
      @PathParam("processDefId") String processId) {
    Map<String, List<String>> formParams = getRequestParams(request);
    Map<String, Object> params =
        extractMapFromParams(formParams, "process/" + processId + "/start");
    Command<?> cmd = new StartProcessCommand(processId, params);

    Object result =
        internalDoKieSessionOperation(
            cmd, "Unable to get process instance logs for process '" + processId + "'");
    ProcessInstance procInst = (ProcessInstance) result;

    Map<String, String> vars = getVariables(procInst.getId());
    JaxbProcessInstanceWithVariablesResponse resp =
        new JaxbProcessInstanceWithVariablesResponse(procInst, vars, request);

    return resp;
  }