@Test
  public void testNullSafeNullComparisonReverse() {
    // DROOLS-82
    String str =
        "import org.drools.compiler.*;\n"
            + "rule R1 when\n"
            + "   Person( \"Main Street\".equalsIgnoreCase(address!.street) )\n"
            + "then\n"
            + "end";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    ksession.insert(new Person("Mario", 38));

    Person mark = new Person("Mark", 37);
    mark.setAddress(new Address("Main Street"));
    ksession.insert(mark);

    Person edson = new Person("Edson", 34);
    edson.setAddress(new Address(null));
    ksession.insert(edson);

    assertEquals(1, ksession.fireAllRules());
    ksession.dispose();
  }
Esempio n. 2
0
  @Test
  public void testFixedPattern() throws FileNotFoundException {

    DecisionTableConfiguration dtconf = KnowledgeBuilderFactory.newDecisionTableConfiguration();
    dtconf.setInputType(DecisionTableInputType.XLS);
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("fixedPattern.xls", getClass()),
        ResourceType.DTABLE,
        dtconf);
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    List<Long> list = new ArrayList<Long>();
    ksession.setGlobal("list", list);

    ksession.insert(1L);
    ksession.insert(2);
    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(1L, (long) list.get(0));

    ksession.dispose();
  }
  @Test
  public void testNullSafeMemberOf() {
    // DROOLS-50
    String str =
        "declare A\n"
            + "    list : java.util.List\n"
            + "end\n"
            + "\n"
            + "rule Init when\n"
            + "then\n"
            + "    insert( new A( java.util.Arrays.asList( \"test\" ) ) );"
            + "    insert( \"test\" );"
            + "end\n"
            + "rule R when\n"
            + "    $a : A()\n"
            + "    $s : String( this memberOf $a!.list )\n"
            + "then\n"
            + "end";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    assertEquals(2, ksession.fireAllRules());
    ksession.dispose();
  }
  @Test
  public void testDoubleNullSafe() {
    String str =
        "import org.drools.compiler.*;\n"
            + "rule R1 when\n"
            + "   Person( address!.street!.length > 15 ) \n"
            + "then\n"
            + "end";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.insert(new Person("Mario", 38));

    Person mark = new Person("Mark", 37);
    mark.setAddress(new Address("Main Street"));
    ksession.insert(mark);

    Person edson = new Person("Edson", 34);
    edson.setAddress(new Address(null));
    ksession.insert(edson);

    Person alex = new Person("Alex", 34);
    alex.setAddress(new Address("The Main Very Big Street"));
    ksession.insert(alex);

    assertEquals(1, ksession.fireAllRules());
    ksession.dispose();
  }
  @Test
  public void testNullSafeBinding() {
    String str =
        "import org.drools.compiler.*;\n"
            + "rule R1 when\n"
            + "   Person( $streetName : address!.street ) \n"
            + "then\n"
            + "end";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.insert(new Person("Mario", 38));

    Person mark = new Person("Mark", 37);
    mark.setAddress(new Address("Main Street"));
    ksession.insert(mark);

    Person edson = new Person("Edson", 34);
    edson.setAddress(new Address(null));
    ksession.insert(edson);

    assertEquals(2, ksession.fireAllRules());
    ksession.dispose();
  }
 @Override
 protected StatefulKnowledgeSession disposeAndReloadSession(
     StatefulKnowledgeSession ksession, KnowledgeBase kbase) {
   long ksessionId = ksession.getIdentifier();
   ksession.dispose();
   return InfinispanKnowledgeService.loadStatefulKnowledgeSession(
       ksessionId, kbase, null, createEnvironment(context));
 }
  @Test
  public void testOutOfMemory() throws Exception {
    KnowledgeBase kbase = loadKnowledgeBase("empty.drl");

    for (int i = 0; i < 10000; i++) {
      StatefulKnowledgeSession session = createKnowledgeSession(kbase);
      WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger(session);
      session.fireAllRules();
      session.dispose();
    }
  }
  @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();
  }
  @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 create2ProcessInstances() throws Exception {
    long[] processId = new long[2];

    StatefulKnowledgeSession ksession = reloadKnowledgeSession();
    processId[0] =
        ksession.createProcessInstance("org.jbpm.processinstance.helloworld", null).getId();
    processId[1] =
        ksession.createProcessInstance("org.jbpm.processinstance.helloworld", null).getId();
    ksession.dispose();

    assertProcessInstancesExist(processId);
  }
Esempio n. 11
0
  @Test
  public void testForallSinglePattern2() throws Exception {
    final KnowledgeBase kbase = loadKnowledgeBase("test_ForallSinglePattern2.drl");
    final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    ksession.insert(new Triangle(3, 3, 3));
    ksession.insert(new Triangle(3, 3, 3));

    // no cheeses, so should fire
    int fired = ksession.fireAllRules();
    assertEquals(1, fired);

    ksession.dispose();
  }
  protected void dispose(StatefulKnowledgeSession ksession) {
    StatefulKnowledgeSessionImpl wm = ((StatefulKnowledgeSessionImpl) ksession);

    for (AgendaEventListener listener : wm.getAgendaEventSupport().getEventListeners()) {
      this.agendaEventSupport.removeEventListener(listener);
    }
    for (RuleRuntimeEventListener listener : wm.getRuleRuntimeEventSupport().getEventListeners()) {
      this.ruleRuntimeEventSupport.removeEventListener(listener);
    }
    InternalProcessRuntime processRuntime = wm.internalGetProcessRuntime();
    if (processRuntime != null) {
      for (ProcessEventListener listener : processRuntime.getProcessEventListeners()) {
        this.processEventSupport.removeEventListener(listener);
      }
    }
    ksession.dispose();
  }
Esempio n. 13
0
  @Test
  public void testExists3() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource(
            "test_Exists_JBRULES_2810.drl", FirstOrderLogicTest.class),
        ResourceType.DRL);

    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());

    final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    WorkingMemoryConsoleLogger logger = new WorkingMemoryConsoleLogger(ksession);
    ksession.fireAllRules();
    ksession.dispose();
  }
  @Test
  public void testNullSafeInnerConstraint() {
    String str =
        "declare Content\n"
            + " complexContent : Content\n"
            + " extension : Content\n"
            + "end\n"
            + "\n"
            + "declare Context\n"
            + " ctx : Content\n"
            + "end\n"
            + "\n"
            + "rule \"Complex Type Attribute\"\n"
            + "when\n"
            + " $con : Content()\n"
            + " Context( ctx == $con || == $con!.complexContent!.extension )\n"
            + "then\n"
            + " System.out.println( $con ); \n"
            + "end\n"
            + "\n"
            + "rule \"Init\"\n"
            + "when\n"
            + "then\n"
            + " Content ext = new Content();\n"
            + " Content complex = new Content( new Content( null, ext ), null );\n"
            + " Content complex2 = new Content( null, null );\n"
            + " Context ctx = new Context( ext );\n"
            + " Context ctx2 = new Context( complex2 );\n"
            + " insert( complex );\n"
            + " insert( complex2 );\n"
            + " insert( ctx );\n"
            + " insert( ctx2 );\n"
            + "end";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    assertEquals(3, ksession.fireAllRules());
    ksession.dispose();
  }
Esempio n. 15
0
  @Test
  public void testOrs() throws Exception {
    String str =
        "package org.drools.compiler.integrationtests\n"
            + "import "
            + Message.class.getName()
            + "\n"
            + "rule X\n"
            + "    when\n"
            + "        Message( message == 'test' )\n"
            + "        Message( !fired ) or eval( !false )\n"
            + "    then\n"
            + "end\n";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    ksession.insert(new Message("test"));
    int rules = ksession.fireAllRules();
    assertEquals(2, rules);
    ksession.dispose();
  }
  @Test
  public void testMixedNullSafes() {
    String str =
        "import org.drools.compiler.*;\n"
            + "rule R1 when\n"
            + " $p : Person( "
            + " address!.street!.length > 0 && ( address!.street!.length < 15 || > 20 && < 30 ) "
            + " && address!.zipCode!.length > 0 && address.zipCode == \"12345\" "
            + " ) \n"
            + "then\n"
            + " System.out.println( $p ); \n"
            + "end";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.insert(new Person("Mario", 38));

    Person mark = new Person("Mark", 37);
    mark.setAddress(new Address("Main Street", null, "12345"));
    ksession.insert(mark);

    Person edson = new Person("Edson", 34);
    edson.setAddress(new Address(null));
    ksession.insert(edson);

    Person alex = new Person("Alex", 34);
    alex.setAddress(new Address("The Main Verrry Long Street"));
    ksession.insert(alex);

    Person frank = new Person("Frank", 24);
    frank.setAddress(new Address("Long Street number 21", null, "12345"));
    ksession.insert(frank);

    assertEquals(2, ksession.fireAllRules());
    ksession.dispose();
  }
  @Test
  public void noProcessInstancesLeftWithPreTxKSessionAndRollback() throws Exception {
    long[] notProcess = new long[4];

    StatefulKnowledgeSession ksession = reloadKnowledgeSession();

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

    notProcess[0] =
        ksession.createProcessInstance("org.jbpm.processinstance.helloworld", null).getId();
    notProcess[1] =
        ksession.createProcessInstance("org.jbpm.processinstance.helloworld", null).getId();

    ut.rollback();
    // Validate that proc inst mgr cache is also flushed on rollback
    assertEquals(0, ksession.getProcessInstances().size());

    ksession = reloadKnowledgeSession(ksession);
    assertEquals(0, ksession.getProcessInstances().size());
    ksession.dispose();

    assertProcessInstancesNotExist(notProcess);
  }
  @Test
  public void create2ProcessInstancesInsideTransaction() throws Exception {
    long[] processId = new long[2];

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

    StatefulKnowledgeSession ksession = reloadKnowledgeSession();
    processId[0] =
        ksession.createProcessInstance("org.jbpm.processinstance.helloworld", null).getId();
    processId[1] =
        ksession.createProcessInstance("org.jbpm.processinstance.helloworld", null).getId();
    assertEquals(2, ksession.getProcessInstances().size());

    // process instance manager cache flushed on tx
    ut.commit();
    assertEquals(0, ksession.getProcessInstances().size());

    ksession = reloadKnowledgeSession(ksession);
    assertEquals(0, ksession.getProcessInstances().size());
    ksession.dispose();

    assertProcessInstancesExist(processId);
  }
 @Test
 public void getEmptyProcessInstances() throws Exception {
   StatefulKnowledgeSession ksession = reloadKnowledgeSession();
   assertEquals(0, ksession.getProcessInstances().size());
   ksession.dispose();
 }
 private StatefulKnowledgeSession reloadKnowledgeSession(StatefulKnowledgeSession ksession) {
   ksession.dispose();
   return reloadKnowledgeSession();
 }
Esempio n. 21
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();
    }
  }
Esempio n. 22
0
  @Test
  public void testLotsOfOrs() throws Exception {
    // Decomposed this test down to just two rules, while still exhibiting the problem
    // Uncomment rest of rule as those are fixed, to complicate it again.
    String str =
        "package org.drools.compiler.test\n"
            + "\n"
            + "import "
            + FirstOrderLogicTest.class.getCanonicalName()
            + ".Field;\n"
            + " \n"
            + "rule \"test\"\n"
            + "    when\n"
            + "        (\n"
            + "            ( \n"
            + "                a : Field( name == \"a\") and\n"
            + "                eval( !a.getValue().equals(\"a\") ) and\n"
            + "                b : Field( name == \"b\" ) and\n"
            + "                eval( b.intValue()>10 )\n"
            + "           )\n"
            + "           or\n"
            + "           (\n"
            + "                b2 : Field( name == \"b\" ) and\n"
            + "                eval( b2.intValue()<10 )\n"
            + "           )\n"
            + "        )\n"
            + "        and \n"
            + "        (\n"
            + "            t : Field( name == \"t\" ) and\n"
            + "            eval( t.getValue().equals(\"Y\") )\n"
            + "        )\n"
            + "        and (\n"
            + "           (\n"
            + "                c : Field( name == \"c\" ) and\n"
            + "                eval( c.getValue().equals(\"c\") ) and\n"
            + "                d : Field( name == \"d\" ) and\n"
            + "                eval( d.intValue()<5 )\n"
            + "           ) \n"
            + "           or \n"
            + "           (\n"
            + "                c : Field( name == \"c\" ) and\n"
            + "                eval( c.getValue().equals(\"c\") ) and\n"
            + "                d : Field( name == \"d\" ) and\n"
            + "                eval( d.intValue()<20 )\n"
            + "           ) \n"
            + "           or \n"
            + "           ( \n"
            + "                c : Field( name == \"c\") and\n"
            + "                eval( c.getValue().equals(\"d\") ) and\n"
            + "                d : Field( name == \"d\" ) and\n"
            + "                eval( d.intValue()<20 )\n"
            + "           )\n"
            + "        )\n"
            + "    then\n"
            + "        System.out.println( \"Worked!\" ); \n"
            + "end";

    logger.info(str);

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    ksession.insert(new Field("t", "Y"));
    ksession.insert(new Field("a", "b"));
    ksession.insert(new Field("b", "15"));
    ksession.insert(new Field("c", "d"));
    ksession.insert(new Field("d", "15"));
    ksession.fireAllRules();
    ksession.dispose();
  }
Esempio n. 23
0
  @Test
  public void testEventTimestamp() {
    // DROOLS-268
    String drl =
        "\n"
            + "import org.drools.reteoo.integrationtests.CepEspTest.Event; \n"
            + "global java.util.List list; \n"
            + "global org.drools.core.time.SessionPseudoClock clock; \n"
            + ""
            + "declare Event \n"
            + " @role( event )\n"
            + " @timestamp( time ) \n"
            + " @expires( 10000000 ) \n"
            + "end \n"
            + ""
            + ""
            + "rule \"inform about E1\"\n"
            + "when\n"
            + " $event1 : Event( type == 1 )\n"
            + " //there is an event (T2) with value 0 between 0,2m after doorClosed\n"
            + " $event2: Event( type == 2, value == 1, this after [0, 1200ms] $event1, $timestamp : time )\n"
            + " //there is no newer event (T2) within the timeframe\n"
            + " not Event( type == 2, this after [0, 1200ms] $event1, time > $timestamp ) \n"
            + "then\n"
            + " list.add( clock.getCurrentTime() ); \n "
            + "end\n"
            + "\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }
    KieBaseConfiguration baseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    baseConfig.setOption(EventProcessingOption.STREAM);
    baseConfig.setOption(RuleEngineOption.RETEOO);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(baseConfig);
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));

    // init stateful knowledge session
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(sessionConfig, null);
    ArrayList list = new ArrayList();
    ksession.setGlobal("list", list);

    SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock();
    ksession.setGlobal("clock", clock);

    ksession.insert(new Event(1, -1, clock.getCurrentTime())); // 0
    clock.advanceTime(600, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 600
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 700
    clock.advanceTime(300, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 1000
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 1, clock.getCurrentTime())); // 1100
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 1300

    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();

    assertFalse(list.isEmpty());
    assertEquals(1, list.size());
    Long time = (Long) list.get(0);

    assertTrue(time > 1000 && time < 1500);

    ksession.dispose();
  }
 @Override
 public void terminate() {
   ksession.dispose(); // Stateful rule session must always be disposed when finished
 }