Beispiel #1
0
  @Test
  public void testPopulatedSingleRuleNoSharing() throws Exception {
    KieBaseConfiguration kconf =
        (KieBaseConfiguration) KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(RuleEngineOption.PHREAK);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf);
    InternalWorkingMemory wm = ((InternalWorkingMemory) kbase.newStatefulKnowledgeSession());

    wm.insert(new A(1));
    wm.insert(new B(1));
    wm.insert(new C(1));
    wm.insert(new C(2));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.fireAllRules();

    kbase.addKnowledgePackages(buildKnowledgePackage("r1", "   A() B() C(object == 2) D() E()\n"));
    List list = new ArrayList();
    wm.setGlobal("list", list);

    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class);
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getSinkPropagator().getSinks()[0];

    LiaNodeMemory lm = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory sm = lm.getSegmentMemory();
    assertNotNull(sm.getStagedLeftTuples().getInsertFirst());

    wm.fireAllRules();
    assertNull(sm.getStagedLeftTuples().getInsertFirst());
    assertEquals(1, list.size());

    assertEquals("r1", ((Match) list.get(0)).getRule().getName());
  }
Beispiel #2
0
  private KnowledgeBase buildKnowledgeBase(String ruleName, String rule) {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n";
    str += "import " + B.class.getCanonicalName() + "\n";
    str += "import " + C.class.getCanonicalName() + "\n";
    str += "import " + D.class.getCanonicalName() + "\n";
    str += "import " + E.class.getCanonicalName() + "\n";
    str += "global java.util.List list \n";

    int i = 0;
    str += "rule " + ruleName + "  when \n";
    str += rule;
    str += "then \n";
    str += " list.add( kcontext.getMatch() );\n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

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

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(RuleEngineOption.PHREAK);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf);
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    return kbase;
  }
Beispiel #3
0
  public void init(boolean exitOnClose) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder
        .batch()
        .add(newClassPathResource("init.drl", getClass()), DRL)
        .add(newClassPathResource("game.drl", getClass()), DRL)
        .add(newClassPathResource("keys.drl", getClass()), DRL)
        .add(newClassPathResource("move.drl", getClass()), DRL)
        .add(newClassPathResource("collision.drl", getClass()), DRL)
        .add(newClassPathResource("ui.drl", getClass()), DRL)
        .build();
    if (kbuilder.hasErrors()) {
      throw new RuntimeException(kbuilder.getErrors().toString());
    }

    KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption(EventProcessingOption.STREAM);

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

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    // ksession.addEventListener( new DebugAgendaEventListener() );
    PongConfiguration pconf = new PongConfiguration();
    pconf.setExitOnClose(exitOnClose);
    ksession.setGlobal("pconf", pconf);

    //        ksession.addEventListener( new DefaultAgendaEventListener() {
    //            public void beforeMatchFired(BeforeActivationFiredEvent event)  {
    //                System.out.println( "b: " + event.getActivation().getRule().getName() + " : "
    // + event.getActivation().toFactHandles() );
    //            }
    //            public void afterMatchFired(AfterActivationFiredEvent event)  {
    //                System.out.println( "a: " + event.getActivation().getRule().getName() + " : "
    // + event.getActivation().toFactHandles() );
    //            }
    ////            public void matchCreated(ActivationCreatedEvent event)  {
    ////                System.out.println( "cr: " + event.getActivation().getRule().getName() + " :
    // " + event.getActivation().toFactHandles() );
    ////            }
    ////            public void matchCancelled(ActivationCancelledEvent event)  {
    ////                System.out.println( "cl: " + event.getActivation().getRule().getName() + " :
    // " + event.getActivation().toFactHandles() );
    ////            }
    //
    //        });

    runKSession(ksession);
  }
Beispiel #4
0
  @Test
  @Ignore("Added 30-APR-2011 -Rikkola-")
  public void testNestedEnumFromJar() {
    String str =
        ""
            + "package org.drools.compiler.test \n"
            + "import org.kie.examples.eventing.EventRequest \n"
            + "global java.util.List list \n"
            + "rule 'zaa'\n  "
            + "when \n  "
            + "request: EventRequest( status == EventRequest.Status.ACTIVE )\n   "
            + "then \n "
            + "request.setStatus(EventRequest.Status.ACTIVE); \n  "
            + "end";

    JarInputStream jis = null;
    try {
      jis = new JarInputStream(this.getClass().getResourceAsStream("/eventing-example.jar"));
    } catch (IOException e) {
      fail("Failed to load the jar");
    }
    MapBackedClassLoader loader = createClassLoader(jis);

    KnowledgeBuilderConfiguration knowledgeBuilderConfiguration =
        KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, loader);
    KnowledgeBuilder kbuilder =
        KnowledgeBuilderFactory.newKnowledgeBuilder(knowledgeBuilderConfiguration);
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

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

    KieBaseConfiguration knowledgeBaseConfiguration =
        KnowledgeBaseFactory.newKnowledgeBaseConfiguration(null, loader);

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

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal("list", list);
    Triangle t = new Triangle(Triangle.Type.ACUTE);
    ksession.insert(t);

    ksession.fireAllRules();

    assertEquals(Triangle.Type.ACUTE, list.get(0));
  }
Beispiel #5
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());
  }
Beispiel #6
0
  @Test
  public void testEqualsObject() {
    final LeftTupleSource ts = new MockTupleSource(1);
    final ObjectSource os = new MockObjectSource(2);

    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    BuildContext buildContext = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());

    final BetaNode j1 = new JoinNode(1, ts, os, EmptyBetaConstraints.getInstance(), buildContext);
    final BetaNode j2 = new JoinNode(2, ts, os, EmptyBetaConstraints.getInstance(), buildContext);
    final BetaNode n1 = new NotNode(3, ts, os, EmptyBetaConstraints.getInstance(), buildContext);
    final BetaNode n2 = new NotNode(4, ts, os, EmptyBetaConstraints.getInstance(), buildContext);

    assertEquals(j1, j1);
    assertEquals(j2, j2);
    assertEquals(j1, j2);
    assertEquals(n1, n1);
    assertEquals(n2, n2);
    assertEquals(n1, n2);

    assertFalse(j1.equals(n1));
    assertFalse(j1.equals(n2));
    assertFalse(n1.equals(j1));
    assertFalse(n1.equals(j2));
  }
Beispiel #7
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(timeout = 10000)
  public void testCalendarsWithIntervalsAndStartAndLimit() throws Exception {
    String str = "";
    str += "package org.simple \n";
    str += "global java.util.List list \n";
    str += "rule xxx \n";
    str += "  calendars \"cal1\"\n";
    str += "  timer (0d 1d start=3-JAN-2010 repeat-limit=4) "; // int: protocol is assumed
    str += "when \n";
    str += "then \n";
    str += "  list.add(\"fired\"); \n";
    str += "end  \n";

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ClockTypeOption.get("pseudo"));

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = createKnowledgeSession(kbase, conf);

    List list = new ArrayList();
    PseudoClockScheduler timeService =
        (PseudoClockScheduler) ksession.<SessionClock>getSessionClock();
    DateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.UK);
    Date date = df.parse("1-JAN-2010");

    Calendar cal1 =
        new Calendar() {
          public boolean isTimeIncluded(long timestamp) {
            return true;
          }
        };

    long oneDay = 60 * 60 * 24;
    ksession.getCalendars().set("cal1", cal1);
    ksession.setGlobal("list", list);

    timeService.advanceTime(date.getTime(), TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    assertEquals(0, list.size());

    timeService.advanceTime(oneDay, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(0, list.size());

    timeService.advanceTime(oneDay, TimeUnit.SECONDS); // day 3
    ksession.fireAllRules();
    assertEquals(1, list.size());

    timeService.advanceTime(oneDay, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(2, list.size());

    timeService.advanceTime(oneDay, TimeUnit.SECONDS); // day 5
    ksession.fireAllRules();
    assertEquals(3, list.size());

    timeService.advanceTime(oneDay, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(3, list.size());
  }
 private KieSessionConfiguration getKnowledgeSessionConfiguration(
     KieSessionModelImpl kSessionModel) {
   KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
   ksConf.setOption(kSessionModel.getClockType());
   ksConf.setOption(kSessionModel.getBeliefSystem());
   return ksConf;
 }
  @Test
  public void testAllLinkedInWithNotNodesOnly() {
    setUp(NOT_NODE);

    assertEquals(NotNode.class, n3.getClass()); // make sure it created NotNodes

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(RuleEngineOption.PHREAK);
    AbstractWorkingMemory wm =
        new AbstractWorkingMemory(
            1, (ReteooRuleBase) RuleBaseFactory.newRuleBase((RuleBaseConfiguration) kconf));

    BetaMemory bm = (BetaMemory) wm.getNodeMemory(n3);
    createSegmentMemory(n3, wm);
    assertTrue(bm.getSegmentMemory().isSegmentLinked()); // not nodes start off linked

    DefaultFactHandle f1 = (DefaultFactHandle) wm.insert("test1"); // unlinked after first assertion
    n3.assertObject(f1, context, wm);

    // this doesn't unlink on the assertObject, as the node's memory must be processed. So use the
    // helper method the main network evaluator uses.
    PhreakNotNode.unlinkNotNodeOnRightInsert((NotNode) n3, bm, wm);
    assertFalse(bm.getSegmentMemory().isSegmentLinked());

    n3.retractRightTuple(f1.getFirstRightTuple(), context, wm);
    assertTrue(bm.getSegmentMemory().isSegmentLinked());
    // assertFalse( bm.getSegmentMemory().isSigmentLinked() ); // check retraction unlinks again
  }
Beispiel #11
0
  // JBRULES-2526
  @Test
  public void testOrWithVariableResolution2() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource(
            "test_OrCEFollowedByMultipleEval2.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);

    final AgendaEventListener al = mock(AgendaEventListener.class);
    ksession.addEventListener(al);

    ksession.insert(new FactA("a"));
    ksession.insert(new FactB("b"));
    ksession.insert(new FactC("c"));

    ksession.fireAllRules();
    verify(al, times(8)).afterMatchFired(any(AfterMatchFiredEvent.class));
  }
  @Test
  public void testLiaNodeInitialisation() {
    setUp(JOIN_NODE);
    // Initialise from lian
    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(RuleEngineOption.PHREAK);
    AbstractWorkingMemory wm =
        new AbstractWorkingMemory(
            1, (ReteooRuleBase) RuleBaseFactory.newRuleBase((RuleBaseConfiguration) kconf));
    SegmentUtilities.createSegmentMemory(liaNode, wm);
    liaNode.assertObject((InternalFactHandle) wm.insert("str"), context, wm);

    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    assertEquals(1, liaMem.getNodePosMaskBit());
    assertEquals(3, liaMem.getSegmentMemory().getAllLinkedMaskTest());

    BetaMemory bm1 = (BetaMemory) wm.getNodeMemory(n1);
    assertEquals(2, bm1.getNodePosMaskBit());
    assertEquals(3, bm1.getSegmentMemory().getAllLinkedMaskTest());

    // Initialise from n1
    wm =
        new AbstractWorkingMemory(
            1, (ReteooRuleBase) RuleBaseFactory.newRuleBase((RuleBaseConfiguration) kconf));
    n1.assertObject((InternalFactHandle) wm.insert("str"), context, wm);

    liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    assertEquals(1, liaMem.getNodePosMaskBit());
    assertEquals(3, liaMem.getSegmentMemory().getAllLinkedMaskTest());

    bm1 = (BetaMemory) wm.getNodeMemory(n1);
    assertEquals(2, bm1.getNodePosMaskBit());
    assertEquals(3, bm1.getSegmentMemory().getAllLinkedMaskTest());
  }
Beispiel #13
0
  @Test
  @SuppressWarnings("unchecked")
  public void test1() throws Exception {
    String rule = "package org.test;\n";
    rule += "import org.jbpm.integrationtests.test.Person\n";
    rule += "global java.util.List list\n";
    rule += "rule \"Rule 1\"\n";
    rule += "  ruleflow-group \"hello\"\n";
    rule += "when\n";
    rule += "    $p : Person( ) \n";
    rule += "then\n";
    rule += "    list.add( $p );\n";
    rule += "end";

    String process =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n"
            + "    xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "    xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n"
            + "    type=\"RuleFlow\" name=\"ruleflow\" id=\"org.test.ruleflow\" package-name=\"org.test\" >\n"
            + "  <header>\n"
            + "  </header>\n"
            + "  <nodes>\n"
            + "    <start id=\"1\" name=\"Start\" />\n"
            + "    <ruleSet id=\"2\" name=\"Hello\" ruleFlowGroup=\"hello\" />\n"
            + "    <end id=\"3\" name=\"End\" />\n"
            + "  </nodes>\n"
            + "  <connections>\n"
            + "    <connection from=\"1\" to=\"2\"/>\n"
            + "    <connection from=\"2\" to=\"3\"/>\n"
            + "  </connections>\n"
            + "</process>";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newReaderResource(new StringReader(rule)), ResourceType.DRL);
    kbuilder.add(ResourceFactory.newReaderResource(new StringReader(process)), ResourceType.DRF);

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

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

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

    Person p = new Person("bobba fet", 32);
    ksession.insert(p);
    ksession.startProcess("org.test.ruleflow");

    assertEquals(1, ksession.getProcessInstances().size());

    ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
    assertEquals(1, ksession.getProcessInstances().size());

    ksession.fireAllRules();

    assertEquals(1, ((List<Object>) ksession.getGlobal("list")).size());
    assertEquals(p, ((List<Object>) ksession.getGlobal("list")).get(0));
    assertEquals(0, ksession.getProcessInstances().size());
  }
Beispiel #14
0
  private KieBase createKnowledgeBase() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource(
            "memory/BPMN2-RuleTaskWithInsertProcessInstance.bpmn2"),
        ResourceType.BPMN2);
    kbuilder.add(
        ResourceFactory.newClassPathResource("memory/ProcessInstanceRule.drl"), ResourceType.DRL);

    if (!kbuilder.getErrors().isEmpty()) {
      Iterator<KnowledgeBuilderError> errIter = kbuilder.getErrors().iterator();
      while (errIter.hasNext()) {
        KnowledgeBuilderError err = errIter.next();
        StringBuilder lines = new StringBuilder("");
        if (err.getLines().length > 0) {
          lines.append(err.getLines()[0]);
          for (int i = 1; i < err.getLines().length; ++i) {
            lines.append(", " + err.getLines()[i]);
          }
        }
        logger.warn(err.getMessage() + " (" + lines.toString() + ")");
      }
      throw new IllegalArgumentException("Errors while parsing knowledge base");
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    return kbase;
  }
Beispiel #15
0
  @Test
  public void testPackageImports() throws Exception {
    String str = "";
    str += "package org.kie \n";
    str += "dialect \"mvel\"\n";
    str += "import org.acme.healthcare.* \n";
    str += "import org.acme.insurance.* \n";
    str += "import org.acme.sensors.SensorReading \n";
    str += "rule rule1 \n";
    str += "  when \n";
    str += "    eval(true)\n";
    str += "  then \n";
    str += "    insert(new Claim());         // from org.acme.healthcare.* \n";
    str += "    insert(new Policy());        // from org.acme.insurance.* \n";
    str += "    insert(new SensorReading()); // from org.acme.sensor.SensorReading \n";
    str += "end\n";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
      throw new RuntimeException(kbuilder.getErrors().toString());
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    int result = ksession.fireAllRules();

    assertEquals(1, result);
    Collection<? extends Object> insertedObjects = ksession.getObjects();
    assertEquals(3, insertedObjects.size());
  }
Beispiel #16
0
  @Test
  public void testNestedEnum() {
    String str =
        ""
            + "package org.drools.compiler.test \n"
            + "import "
            + Triangle.class.getCanonicalName()
            + "\n"
            + "global java.util.List list \n"
            + "rule \"show\" \n"
            + "when  \n"
            + "    $t: Triangle(t == Triangle.Type.ACUTE) \n"
            + "then \n"
            + "    list.add($t.getT()); \n"
            + "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

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

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

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal("list", list);
    Triangle t = new Triangle(Triangle.Type.ACUTE);
    ksession.insert(t);

    ksession.fireAllRules();

    assertEquals(Triangle.Type.ACUTE, list.get(0));
  }
  @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 =
        InfinispanKnowledgeService.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());
  }
  @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 testAllLinkedInWithExistsNodesOnly() {
    setUp(EXISTS_NODE);

    assertEquals(ExistsNode.class, n3.getClass()); // make sure it created ExistsNodes

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(RuleEngineOption.PHREAK);
    AbstractWorkingMemory wm =
        new AbstractWorkingMemory(
            1, (ReteooRuleBase) RuleBaseFactory.newRuleBase((RuleBaseConfiguration) kconf));
    DefaultFactHandle f1 = (DefaultFactHandle) wm.insert("test1");
    n3.assertObject(f1, context, wm);

    BetaMemory bm = (BetaMemory) wm.getNodeMemory(n3);
    assertFalse(bm.getSegmentMemory().isSegmentLinked());

    n4.assertObject(f1, context, wm);
    assertFalse(bm.getSegmentMemory().isSegmentLinked());

    n5.assertObject(f1, context, wm);
    assertFalse(bm.getSegmentMemory().isSegmentLinked());

    n6.assertObject(f1, context, wm);
    assertTrue(
        bm.getSegmentMemory()
            .isSegmentLinked()); // only after all 4 nodes are populated, is the segment linked in

    n6.retractRightTuple(f1.getLastRightTuple(), context, wm);
    assertFalse(bm.getSegmentMemory().isSegmentLinked()); // check retraction unlinks again
  }
Beispiel #20
0
  @Test
  public void testIncrementOperator() throws Exception {
    String str = "";
    str += "package org.kie \n";
    str += "global java.util.List list \n";
    str += "rule rule1 \n";
    str += "    dialect \"mvel\" \n";
    str += "when \n";
    str += "    $I : Integer() \n";
    str += "then \n";
    str += "    i = $I.intValue(); \n";
    str += "    i += 5; \n";
    str += "    list.add( i ); \n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

    assertFalse(kbuilder.hasErrors());

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

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.insert(5);

    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(10, list.get(0));
  }
Beispiel #21
0
  @Test
  public void testNewConstructor() {
    String str =
        ""
            + "package org.drools.compiler.test \n"
            + "import "
            + Person.class.getCanonicalName()
            + "\n"
            + "import "
            + Address.class.getCanonicalName()
            + "\n"
            + "global java.util.List list \n"
            + "rule \"show\" \n"
            + "when  \n"
            + "    $m : Person( address == new Address('s1')) \n"
            + "then \n"
            + "    list.add('r1'); \n"
            + "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

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

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

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal("list", list);

    Person p = new Person("yoda");
    p.setAddress(new Address("s1"));

    ksession.insert(p);

    ksession.fireAllRules();

    assertEquals("r1", list.get(0));

    // Check it was built with MVELReturnValueExpression constraint
    List<ObjectTypeNode> nodes = ((InternalKnowledgeBase) kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
      if (((ClassObjectType) n.getObjectType()).getClassType() == Person.class) {
        node = n;
        break;
      }
    }

    AlphaNode alphanode = (AlphaNode) node.getSinkPropagator().getSinks()[0];
    AlphaNodeFieldConstraint constraint = alphanode.getConstraint();

    if (constraint instanceof MvelConstraint) {
      assertTrue(((MvelConstraint) constraint).getFieldExtractor() instanceof ClassFieldReader);
      FieldValue r = ((MvelConstraint) constraint).getField();
      assertEquals(p.getAddress(), r.getValue());
    }
  }
 private KieBaseConfiguration getKnowledgeBaseConfiguration(
     KieBaseModelImpl kBaseModel, ClassLoader cl) {
   KieBaseConfiguration kbConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(null, cl);
   kbConf.setOption(kBaseModel.getEqualsBehavior());
   kbConf.setOption(kBaseModel.getEventProcessingMode());
   kbConf.setOption(kBaseModel.getDeclarativeAgenda());
   return kbConf;
 }
  @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);
  }
  @Before
  public void setUp() throws Exception {
    store.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);
    this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();

    this.buildContext = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());
  }
Beispiel #26
0
  @Test
  public void testCollectAfterOrCE() throws Exception {
    // Set up facts
    final Cheesery bonFromage = new Cheesery();
    bonFromage.addCheese(new Cheese("cheddar"));
    bonFromage.addCheese(new Cheese("cheddar"));

    // Test in memory compile of DRL
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("test_OrCEFollowedByCollect.drl", getClass()),
        ResourceType.DRL);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (errors.size() > 0) {
      for (KnowledgeBuilderError error : errors) {
        logger.warn(error.toString());
      }
      throw new IllegalArgumentException("Could not parse knowledge.");
    }
    assertFalse(kbuilder.hasErrors());

    Collection<KnowledgePackage> knowledgePackages = kbuilder.getKnowledgePackages();

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(knowledgePackages);

    StatefulKnowledgeSession session = createKnowledgeSession(kbase);
    session.insert(bonFromage);

    int rules = session.fireAllRules();
    assertEquals(2, rules);

    // Serialize and test again
    knowledgePackages = SerializationHelper.serializeObject(knowledgePackages);
    kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(knowledgePackages);

    session = createKnowledgeSession(kbase);
    session.insert(bonFromage);

    rules = session.fireAllRules();
    assertEquals(2, rules);
  }
Beispiel #27
0
  @Before
  public void setUp() throws Exception {
    store.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);

    this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    buildContext = new BuildContext(kBase, new ReteooBuilder.IdGenerator());
    pctxFactory = kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
  }
  @Test
  public void testSimpleReturnValueConstraintEvaluator() throws Exception {
    final InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");

    ProcessDescr processDescr = new ProcessDescr();
    processDescr.setClassName("Process1");
    processDescr.setName("Process1");

    WorkflowProcessImpl process = new WorkflowProcessImpl();
    process.setName("Process1");
    process.setPackageName("pkg1");

    ReturnValueDescr descr = new ReturnValueDescr();
    descr.setText("return value;");

    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
    DialectCompiletimeRegistry dialectRegistry =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    JavaDialect javaDialect = (JavaDialect) dialectRegistry.getDialect("java");

    ProcessBuildContext context =
        new ProcessBuildContext(
            pkgBuilder, pkg, process, processDescr, dialectRegistry, javaDialect);

    pkgBuilder.addPackageFromDrl(new StringReader("package pkg1;\nglobal Boolean value;"));

    ReturnValueConstraintEvaluator node = new ReturnValueConstraintEvaluator();

    final JavaReturnValueEvaluatorBuilder builder = new JavaReturnValueEvaluatorBuilder();
    builder.build(context, node, descr, null);

    ProcessDialectRegistry.getDialect(JavaDialect.ID).addProcess(context);
    javaDialect.compileAll();
    assertEquals(0, javaDialect.getResults().size());

    final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    List<KnowledgePackage> packages = new ArrayList<KnowledgePackage>();
    packages.add(pkgBuilder.getPackage());
    kbase.addKnowledgePackages(packages);
    final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.setGlobal("value", true);

    RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();
    processInstance.setKnowledgeRuntime((InternalKnowledgeRuntime) ksession);

    SplitInstance splitInstance = new SplitInstance();
    splitInstance.setProcessInstance(processInstance);

    assertTrue(node.evaluate(splitInstance, null, null));

    ksession.setGlobal("value", false);

    assertFalse(node.evaluate(splitInstance, null, null));
  }
Beispiel #29
0
  public static void setup() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newInputStreamResource(
            ExampleScenario.class.getResourceAsStream(FILE_NAME_RULES)),
        ResourceType.DRL);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    wm = kbase.newStatefulKnowledgeSession();
  }
  private StatefulKnowledgeSessionImpl createWorkingMemory(InternalKnowledgeBase kBase) {
    // WorkingMemoryEntryPoint
    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption(ClockTypeOption.get("pseudo"));
    SessionConfiguration sessionConf = ((SessionConfiguration) ksconf);
    StatefulKnowledgeSessionImpl wm =
        new StatefulKnowledgeSessionImpl(
            1L, kBase, true, sessionConf, EnvironmentFactory.newEnvironment());

    return wm;
  }