Ejemplo n.º 1
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();
  }
Ejemplo n.º 2
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));
  }
Ejemplo n.º 3
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;
  }
Ejemplo n.º 4
0
  private Collection<KnowledgePackage> buildKnowledgePackage(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());

    return kbuilder.getKnowledgePackages();
  }
  @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());
  }
Ejemplo n.º 6
0
  @Test
  public void testTokensInString() {
    // should query antldr DFA63 class but don't know how
    String[] operators = {",", "=", "|=", "*"};
    // test various in consequence
    String strBegin =
        ""
            + "package org.kie \n"
            + "import org.drools.compiler.Cheese \n"
            + "dialect \"mvel\"\n"
            + "rule rule1 \n"
            + "when \n"
            + "$c:Cheese(type==\"swiss\") \n"
            + "then \n"
            + "modify($c){ type = \"swiss";

    String strEnd = "good\"};\n" + "end\n";
    StringBuffer failures = new StringBuffer();
    for (String oper : operators) {
      KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
      String rule = strBegin + oper + strEnd;
      System.out.print(rule);
      kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL);
      if (kbuilder.hasErrors()) {
        failures.append(kbuilder.getErrors().toString());
      }
    }
    String failStr = failures.toString();
    if (failStr.length() > 0) {
      fail(failStr);
    }
  }
Ejemplo n.º 7
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());
  }
  public WorkingMemorySimulationRepository(boolean fireRulesOnStore, Resource... rules) {
    this.fireRulesOnStore = fireRulesOnStore;
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    for (Resource path : rules) {

      kbuilder.add(path, ResourceType.DRL);
    }
    if (kbuilder.hasErrors()) {
      throw new RuntimeException("Error while building knowledge base: " + kbuilder.getErrors());
    }

    this.ksession = kbuilder.newKnowledgeBase().newKieSession();
    try {
      // register global for aggregated events
      ksession.setGlobal("logger", new SystemOutLogger());
      ksession.setGlobal("simulation", new ArrayList<AggregatedActivitySimulationEvent>());
      ksession.setGlobal("summary", new ArrayList<AggregatedActivitySimulationEvent>());
      AggregatedProcessSimulationEvent init = new AggregatedProcessSimulationEvent("", 0, 0, 0);
      List processOnlyList = new ArrayList<AggregatedSimulationEvent>();
      processOnlyList.add(init);
      ksession.setGlobal("processEventsOnly", processOnlyList);
    } catch (Exception e) {
      // catch it as there could be no simulation global declared
    }
  }
Ejemplo n.º 9
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));
  }
Ejemplo n.º 10
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));
  }
Ejemplo n.º 11
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());
    }
  }
Ejemplo n.º 12
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));
  }
Ejemplo n.º 13
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;
  }
Ejemplo n.º 14
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());
  }
Ejemplo n.º 15
0
  @Test
  public void testSizeCheckInObject() {
    String str =
        ""
            + "package org.drools.compiler.test \n"
            + "import "
            + Triangle.class.getCanonicalName()
            + "\n"
            +
            // "import " + Address.class.getCanonicalName() + "\n" +
            "global java.util.List list \n"
            + "rule \"show\" \n"
            + "when  \n"
            + "    $m : Triangle( deliveries.size == 0) \n"
            + "then \n"
            + "    list.add('r1'); \n"
            + "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      System.out.println(kbuilder.getErrors().toString());
      fail(kbuilder.getErrors().toString());
    }
  }
  @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);
  }
Ejemplo n.º 17
0
 private KnowledgeBase readKnowledgeBase(String resource) throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   DecisionTableConfiguration config = KnowledgeBuilderFactory.newDecisionTableConfiguration();
   config.setInputType(DecisionTableInputType.XLS);
   kbuilder.add(
       ResourceFactory.newClassPathResource(resource, getClass()), ResourceType.DTABLE, config);
   KnowledgeBuilderErrors errors = kbuilder.getErrors();
   if (errors.size() > 0) {
     for (KnowledgeBuilderError error : errors) {
       System.err.println(error);
     }
     throw new IllegalArgumentException("Could not parse knowledge.");
   }
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
   return kbase;
 }
Ejemplo n.º 18
0
  private KnowledgeBase createBase() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("processinstance/HelloWorld.rf"), ResourceType.DRF);
    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());

    return kbuilder.newKnowledgeBase();
  }
 private static KieSession createKieSession() {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(
       ResourceFactory.newClassPathResource("exceptions/ExceptionHandlingWithSignal.bpmn2"),
       ResourceType.BPMN2);
   KieBase kbase = kbuilder.newKnowledgeBase();
   return kbase.newKieSession();
 }
Ejemplo n.º 20
0
  KieBase loadDecisionTableDirect(String decisionTableResourceName) {
    logDecisionTableAsDrools(decisionTableResourceName);
    KnowledgeBase kieBase = KnowledgeBaseFactory.newKnowledgeBase();

    DecisionTableConfiguration dtconf = KnowledgeBuilderFactory.newDecisionTableConfiguration();
    dtconf.setInputType(DecisionTableInputType.XLS);

    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add(
        ResourceFactory.newClassPathResource("rules/" + decisionTableResourceName),
        ResourceType.DTABLE,
        dtconf);
    validate(kBuilder);

    kieBase.addKnowledgePackages(kBuilder.getKnowledgePackages());
    return kieBase;
  }
  @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);
  }
Ejemplo n.º 22
0
  @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);
  }
Ejemplo n.º 23
0
  @Test
  public void testDuplicateLocalVariableMVELConsequence() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newInputStreamResource(
            getClass().getResourceAsStream("test_DuplicateLocalVariableMVELConsequence.drl")),
        ResourceType.DRL);

    assertTrue(kbuilder.hasErrors());
  }
Ejemplo n.º 24
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();
  }
Ejemplo n.º 25
0
  KieBase loadRules(String drools) {
    KnowledgeBase kieBase = KnowledgeBaseFactory.newKnowledgeBase();

    Resource droolsResource = ResourceFactory.newByteArrayResource(drools.getBytes());

    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add(droolsResource, org.kie.api.io.ResourceType.DRL);
    validate(kBuilder);

    kieBase.addKnowledgePackages(kBuilder.getKnowledgePackages());
    return kieBase;
  }
Ejemplo n.º 26
0
  private KnowledgeBase loadKnowledgeBaseFromString(String drl) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);

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

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    return kbase;
  }
Ejemplo n.º 27
0
  private void wrongTimerExpression(String timer) {
    String str = "";
    str += "package org.simple \n";
    str += "rule xxx \n";
    str += "  timer (" + timer + ") ";
    str += "when \n";
    str += "then \n";
    str += "end  \n";

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

    assertTrue(kbuilder.hasErrors());
  }
Ejemplo n.º 28
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);
  }
  @Test
  public void testPersistenceWorkItems3() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("WorkItemsProcess.rf"), ResourceType.DRF);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

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

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

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

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

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

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

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

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

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

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

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