@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 =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    int id = ksession.getId();

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

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

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

    ksession = JPAKnowledgeService.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 =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    int origNumObjects = ksession.getObjects().size();
    int id = ksession.getId();

    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 = 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();
    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(origNumObjects + 1, ksession.getObjects().size());
    for (Object o : ksession.getObjects()) {
      logger.debug(o.toString());
    }
    assertNull(processInstance);
  }
  @Test
  public void testLocalTransactionPerStatement() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(ruleString.getBytes()), ResourceType.DRL);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    List<?> list = new ArrayList<Object>();

    ksession.setGlobal("list", list);

    ksession.insert(1);
    ksession.insert(2);
    ksession.insert(3);

    ksession.fireAllRules();

    assertEquals(3, list.size());
  }
  @Override
  protected StatefulKnowledgeSession createSession(KnowledgeBase kbase) {

    EnvironmentBuilder envBuilder = new KnowledgeSessionStorageEnvironmentBuilder(storage);
    Environment env = KieServices.Factory.get().newEnvironment();
    env.set(EnvironmentName.TRANSACTION_MANAGER, envBuilder.getTransactionManager());
    env.set(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, envBuilder.getPersistenceContextManager());

    return JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
  }
Пример #5
0
  @Before
  public void setUp() throws Exception {
    context = setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME);
    env = createEnvironment(context);

    kbase = createBase();
    StatefulKnowledgeSession ksession =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    sessionId = ksession.getIdentifier();
    ksession.dispose();
  }
 protected StatefulKnowledgeSession createKnowledgeSession(KnowledgeBase kbase) {
   if (context == null) {
     context = DroolsPersistenceUtil.setupWithPoolingDataSource(DROOLS_PERSISTENCE_UNIT_NAME);
   }
   KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
   Environment env = createEnvironment(context);
   if (this.locking) {
     env.set(EnvironmentName.USE_PESSIMISTIC_LOCKING, true);
   }
   return JPAKnowledgeService.newStatefulKnowledgeSession(kbase, ksconf, env);
 }
  @Override
  protected StatefulKnowledgeSession disposeAndReloadSession(
      StatefulKnowledgeSession ksession, KnowledgeBase kbase) {
    long sessionId = ksession.getIdentifier();
    ksession.dispose();
    EnvironmentBuilder envBuilder = new KnowledgeSessionStorageEnvironmentBuilder(storage);
    Environment env = KieServices.Factory.get().newEnvironment();
    env.set(EnvironmentName.TRANSACTION_MANAGER, envBuilder.getTransactionManager());
    env.set(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, envBuilder.getPersistenceContextManager());

    return JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId, kbase, null, env);
  }
  @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 =
        JPAKnowledgeService.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 =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    int id = ksession.getId();

    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 = 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);
    assertEquals("John Doe", workItem.getParameter("text"));

    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());
    assertNull(processInstance);
  }
  @Test
  public void testSetFocus() {
    String str = "";
    str += "package org.drools.test\n";
    str += "global java.util.List list\n";
    str += "rule rule1\n";
    str += "agenda-group \"badfocus\"";
    str += "when\n";
    str += "  Integer(intValue > 0)\n";
    str += "then\n";
    str += "  list.add( 1 );\n";
    str += "end\n";
    str += "\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    List<?> list = new ArrayList<Object>();

    ksession.setGlobal("list", list);

    ksession.insert(1);
    ksession.insert(2);
    ksession.insert(3);
    ksession.getAgenda().getAgendaGroup("badfocus").setFocus();

    ksession.fireAllRules();

    assertEquals(3, list.size());
  }
  @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 =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    int id = ksession.getId();

    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 = 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());
    assertNull("Process did not complete.", processInstance);
  }
Пример #12
0
 private StatefulKnowledgeSession reloadKnowledgeSession() {
   return JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId, kbase, null, env);
 }
Пример #13
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();
    }
  }
  @Test
  public void testProcessListener() {
    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);
    final List<ProcessEvent> events = new ArrayList<ProcessEvent>();
    ProcessEventListener listener =
        new ProcessEventListener() {
          public void afterNodeLeft(ProcessNodeLeftEvent event) {
            logger.debug("After node left: {}", event.getNodeInstance().getNodeName());
            events.add(event);
          }

          public void afterNodeTriggered(ProcessNodeTriggeredEvent event) {
            logger.debug("After node triggered: {}", event.getNodeInstance().getNodeName());
            events.add(event);
          }

          public void afterProcessCompleted(ProcessCompletedEvent event) {
            logger.debug("After process completed");
            events.add(event);
          }

          public void afterProcessStarted(ProcessStartedEvent event) {
            logger.debug("After process started");
            events.add(event);
          }

          public void beforeNodeLeft(ProcessNodeLeftEvent event) {
            logger.debug("Before node left: {}", event.getNodeInstance().getNodeName());
            events.add(event);
          }

          public void beforeNodeTriggered(ProcessNodeTriggeredEvent event) {
            logger.debug("Before node triggered: {}", event.getNodeInstance().getNodeName());
            events.add(event);
          }

          public void beforeProcessCompleted(ProcessCompletedEvent event) {
            logger.debug("Before process completed");
            events.add(event);
          }

          public void beforeProcessStarted(ProcessStartedEvent event) {
            logger.debug("Before process started");
            events.add(event);
          }

          public void afterVariableChanged(ProcessVariableChangedEvent event) {
            logger.debug("After Variable Changed");
            events.add(event);
          }

          public void beforeVariableChanged(ProcessVariableChangedEvent event) {
            logger.debug("Before Variable Changed");
            events.add(event);
          }
        };
    ksession.addEventListener(listener);

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

    assertEquals(12, events.size());
    assertTrue(events.get(0) instanceof ProcessStartedEvent);
    assertTrue(events.get(1) instanceof ProcessNodeTriggeredEvent);
    assertTrue(events.get(2) instanceof ProcessNodeLeftEvent);
    assertTrue(events.get(3) instanceof ProcessNodeTriggeredEvent);
    assertTrue(events.get(4) instanceof ProcessNodeLeftEvent);
    assertTrue(events.get(5) instanceof ProcessNodeTriggeredEvent);
    assertTrue(events.get(6) instanceof ProcessNodeTriggeredEvent);
    assertTrue(events.get(7) instanceof ProcessNodeLeftEvent);
    assertTrue(events.get(8) instanceof ProcessNodeTriggeredEvent);
    assertTrue(events.get(9) instanceof ProcessNodeLeftEvent);
    assertTrue(events.get(10) instanceof ProcessNodeTriggeredEvent);
    assertTrue(events.get(11) instanceof ProcessStartedEvent);

    ksession.removeEventListener(listener);
    events.clear();

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

    assertTrue(events.isEmpty());
  }
  @Test
  public void testUserTransactions() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(ruleString.getBytes()), ResourceType.DRL);

    KieBaseConfiguration kBaseConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    //        ((RuleBaseConfiguration)kBaseConf).setPhreakEnabled(false);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kBaseConf);

    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    StatefulKnowledgeSession ksession =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    ut.commit();

    List<?> list = new ArrayList<Object>();

    // insert and commit
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.setGlobal("list", list);
    ksession.insert(1);
    ksession.insert(2);
    ut.commit();

    // insert and rollback
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.insert(3);
    ut.rollback();

    // check we rolled back the state changes from the 3rd insert
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.fireAllRules();
    ut.commit();
    assertEquals(2, list.size());

    // insert and commit
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.insert(3);
    ksession.insert(4);
    ut.commit();

    // rollback again, this is testing that we can do consecutive rollbacks and commits without
    // issue
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.insert(5);
    ksession.insert(6);
    ut.rollback();

    ksession.fireAllRules();

    assertEquals(4, list.size());

    // now load the ksession
    ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(ksession.getId(), kbase, null, env);

    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.insert(7);
    ksession.insert(8);
    ut.commit();

    ksession.fireAllRules();

    assertEquals(6, list.size());
  }