@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 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 testPersistenceWorkItems() {
    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);
    int origNumObjects = ksession.getObjects().size();
    long id = ksession.getIdentifier();

    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 = 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();
    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(origNumObjects + 1, ksession.getObjects().size());
    for (Object o : ksession.getObjects()) {
      logger.debug(o.toString());
    }
    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 =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    int id = ksession.getId();

    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 = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

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

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

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

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

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

    ksession = JPAKnowledgeService.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);
  }
Esempio n. 5
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 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 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);
  }
  @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);
  }
Esempio n. 9
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");
  }
  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
  @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);
  }
Esempio n. 12
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());
  }
  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);
  }
  /* The purpose of the shared entity manager is to allow the application domain
   * and JBPM domain to be persisted by a single entity manager and transaction.
   */
  @Test
  public void testSpringWithJTAAndSharedEMFAndUserManagedTx() throws Exception {

    UserTransaction ut =
        (UserTransaction)
            new InitialContext().lookup(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME);
    ut.begin();

    KieSession ksession = getKieSession();
    TaskService taskService = getTaskService();
    ProcessInstance processInstance = ksession.startProcess(SAMPLE_HELLO_PROCESS_ID);

    System.out.println("Process started");

    AuditLogService logService = getLogService();
    ProcessInstanceLog log = logService.findProcessInstance(processInstance.getId());
    assertNotNull(log);

    List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner(USER_JOHN, "en-UK");
    System.out.println("Found " + tasks.size() + " task(s) for user '" + USER_JOHN + "'");
    assertEquals(1, tasks.size());

    long taskId = tasks.get(0).getId();
    taskService.start(taskId, USER_JOHN);
    taskService.complete(taskId, USER_JOHN, null);

    tasks = taskService.getTasksAssignedAsPotentialOwner(USER_MARY, "en-UK");
    System.out.println("Found " + tasks.size() + " task(s) for user '" + USER_MARY + "'");
    assertEquals(1, tasks.size());

    taskId = tasks.get(0).getId();
    taskService.start(taskId, USER_MARY);
    taskService.complete(taskId, USER_MARY, null);

    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNull(processInstance);
    System.out.println("Process instance completed");

    ut.commit();
  }
  @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());
  }
Esempio n. 17
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. 18
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();
  }
  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;
  }
  @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);
  }
  @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 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);
  }
  @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;
  }
Esempio n. 25
0
  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 testPersistenceEvents() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("EventsProcess.rf"), ResourceType.DRF);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    int id = ksession.getId();

    ProcessInstance processInstance = ksession.startProcess("org.drools.test.TestProcess");
    logger.debug("Started process instance {}", processInstance.getId());

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

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

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

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

    ksession.signalEvent("MyEvent1", null, processInstance.getId());

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

    ksession.signalEvent("MyEvent2", null, processInstance.getId());

    ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNull(processInstance);
  }
  /** WithVars methods */
  @POST
  @Path("/withvars/process/{processDefId: [_a-zA-Z0-9-:\\.]+}/start")
  public Response withvars_process_processDefId_start(@PathParam("processDefId") String processId) {
    Map<String, List<String>> requestParams = getRequestParams(uriInfo);
    String oper = getRelativePath(uriInfo);
    Map<String, Object> params = extractMapFromParams(requestParams, oper);

    Object result =
        processRequestBean.doKieSessionOperation(
            new StartProcessCommand(processId, params),
            deploymentId,
            (Long) getNumberParam(PROC_INST_ID_PARAM_NAME, false, requestParams, oper, true),
            "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, uriInfo.getRequestUri().toString());

    return createCorrectVariant(resp, headers);
  }
  @Test
  public void testImplicit() {
    KieServices ks = KieServices.Factory.get();
    KieContainer kContainer = ks.getKieClasspathContainer();
    KieSession ksession = kContainer.newKieSession("ksession-samples");
    ProcessInstance processInstance = ksession.startProcess("approveorder");

    Purchase purchase = new Purchase();
    purchase.setCustomerName("sekhar");
    purchase.setPaymentMethod(PaymentMethod.DEBIT);
    purchase.setSubtotal(0);
    ksession.insert(purchase);
    int rulesFired = ksession.fireAllRules();
    System.out.println("facthandles count -->" + ksession.getFactHandles().size());
    // Check the count
    Assert.assertEquals(1, rulesFired);
    // Check the node exists
    // assertNodeExists(processInstance, "Discount","printout");
    // Check the node names
    // assertNodeTriggered(processInstance.getId(),"Discount","printout");
    // Assert completed
    assertProcessInstanceCompleted(processInstance.getId(), ksession);
  }
  @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());
  }
Esempio n. 30
0
  private void createKnowledgeSessionStartProcessEtc(KieBase kbase) {
    logger.info("session count=" + kbase.getKieSessions().size());

    StatefulKnowledgeSession ksession =
        JPAKnowledgeService.newStatefulKnowledgeSession(
            kbase, getKnowledgeSessionConfiguration(), env);
    addEventListenersToSession(ksession);

    /**
     * The following log line caused the memory leak. The specific (reverse-ordered) stack trace is
     * the following:
     *
     * <p>MemoryLeakTest.createKnowledgeSessionStartProcessEtc(KnowledgeBase) calls
     * kbase.getKieSessions() .. KnowledgeBaseImpl.getStatefulKnowledgeSessions() line: 186
     * StatefulKnowledgeSessionImpl.<init>(ReteooWorkingMemory, KnowledgeBase) line: 121
     * ReteooStatefulSession(AbstractWorkingMemory).setKnowledgeRuntime(InternalKnowledgeRuntime)
     * line: 1268 ReteooStatefulSession(AbstractWorkingMemory).createProcessRuntime() line: 342
     * ProcessRuntimeFactory.newProcessRuntime(AbstractWorkingMemory) line: 12
     * ProcessRuntimeFactoryServiceImpl.newProcessRuntime(AbstractWorkingMemory) line: 1
     * ProcessRuntimeFactoryServiceImpl.newProcessRuntime(AbstractWorkingMemory) line: 10
     * ProcessRuntimeImpl.<init>(AbstractWorkingMemory) line: 84
     * ProcessRuntimeImpl.initProcessEventListeners() line: 215
     *
     * <p>And ProcessRuntimeImpl.initProcessEventListeners() is what adds a new listener to
     * AbstractRuleBase.eventSupport.listeners via this line (235):
     * kruntime.getKnowledgeBase().addEventListener(knowledgeBaseListener);
     *
     * <p>The StatefulKnowledgeSessionImpl instance created in this .getStatefulKnowledgeSessions()
     * method is obviously never disposed, which means that the listener is never removed. The
     * listener then contains a link to a field (signalManager) of the ProcessRuntimeImpl, which
     * contains a link to the StatefulKnowledgeSessionImpl instance created here. etc..
     */
    logger.info("session count=" + kbase.getKieSessions().size());

    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);

    try {
      // create process instance, insert into session and start process
      Map<String, Object> processParams = new HashMap<String, Object>();
      String[] fireballVarHolder = new String[1];
      processParams.put("fireball", fireballVarHolder);
      ProcessInstance processInstance = ksession.createProcessInstance(PROCESS_NAME, processParams);
      ksession.insert(processInstance);
      ksession.startProcessInstance(processInstance.getId());

      // after the log line has been added, the DefaultProcessEventListener registered
      //  in the addEventListenersToSession() method no longer works?!?
      ksession.fireAllRules();

      // test process variables
      String[] procVar =
          (String[]) ((WorkflowProcessInstance) processInstance).getVariable("fireball");
      assertEquals("Rule task did NOT fire or complete.", "boom!", procVar[0]);

      // complete task and process
      Map<String, Object> results = new HashMap<String, Object>();
      results.put("chaerg", new SerializableResult("zhrini", 302l, "F", "A", "T"));
      ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), results);

      assertNull(ksession.getProcessInstance(processInstance.getId()));
    } finally {
      // This should clean up all listeners, but doesn't -> see docs above
      ksession.dispose();
    }
  }