@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()); }
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 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); } }
@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()); } }
@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)); }
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; }
@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 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 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 invokePmmlWithTrait() { String extraDrl = "package org.drools.pmml.pmml_4_2.test;" + "" + "import org.drools.core.factmodel.traits.Entity;" + "" + "rule \"Init\" " + "when " + " $s : String( this == \"trigger\" ) " + "then " + " System.out.println( \"Trig\" ); " + " Entity o = new Entity(); " + " insert( o ); \n" + "" + // don an object with the default input trait ( modelName + "Input" ) // both soft and hard fields will be used to feed data into the model "" + " MockColdTrait input = don( o, MockColdTrait.class ); " + " modify( input ) { " + " setTemp( 22.0 );" + " } " + "end " + "" + "" + "rule Log when $x : MockColdTrait() then System.out.println( \"IN \" + $x ); end " + "rule Log2 when $x : Cold() then System.out.println( \"OUT \" + $x ); end "; KieServices ks = KieServices.Factory.get(); KieFileSystem kfs = ks.newKieFileSystem(); kfs.write(ResourceFactory.newClassPathResource(pmmlSource).setResourceType(ResourceType.PMML)); kfs.write( ResourceFactory.newByteArrayResource(extraDrl.getBytes()) .setSourcePath("rules.drl") .setResourceType(ResourceType.DRL)); Results res = ks.newKieBuilder(kfs).buildAll().getResults(); if (res.hasMessages(Message.Level.ERROR)) { System.out.println(res.getMessages(Message.Level.ERROR)); } assertEquals(0, res.getMessages(Message.Level.ERROR).size()); KieSession kSession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession(); kSession.insert("trigger"); kSession.fireAllRules(); System.out.println(reportWMObjects(kSession)); QueryResults qrs = kSession.getQueryResults("Cold", "MockCold", Variable.v); assertTrue(qrs.iterator().hasNext()); Object val = qrs.iterator().next().get("$result"); Assert.assertEquals(0.56, val); }
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; }
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; }
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()); }
@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)); }
@Test public void testSetFocus() { String str = ""; str += "package org.drools.test\n"; str += "global java.util.List list\n"; str += "rule rule1\n"; str += "agenda-group \"badfocus\""; str += "when\n"; str += " Integer(intValue > 0)\n"; str += "then\n"; str += " list.add( 1 );\n"; str += "end\n"; str += "\n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); if (kbuilder.hasErrors()) { fail(kbuilder.getErrors().toString()); } kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); StatefulKnowledgeSession ksession = InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env); List<?> list = new ArrayList<Object>(); ksession.setGlobal("list", list); ksession.insert(1); ksession.insert(2); ksession.insert(3); ksession.getAgenda().getAgendaGroup("badfocus").setFocus(); ksession.fireAllRules(); assertEquals(3, list.size()); }
@Test public void testEvalWithBigDecimal() throws Exception { String str = ""; str += "package org.kie \n"; str += "import java.math.BigDecimal; \n"; str += "global java.util.List list \n"; str += "rule rule1 \n"; str += " dialect \"mvel\" \n"; str += "when \n"; str += " $bd : BigDecimal() \n"; str += " eval( $bd.compareTo( BigDecimal.ZERO ) > 0 ) \n"; str += "then \n"; str += " list.add( $bd ); \n"; str += "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { System.err.println(kbuilder.getErrors()); } 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(new BigDecimal(1.5)); ksession.fireAllRules(); assertEquals(1, list.size()); assertEquals(new BigDecimal(1.5), list.get(0)); }
@Test public void testArrayAccessorWithoutGenerics() { 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( addressesNoGenerics[0].street == new Address('s1').street) \n" + "then \n" + " list.add('r1'); \n" + "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); // This should fail as there are no generics for the List assertTrue(kbuilder.hasErrors()); }
@Test public void testUserTransactions() throws Exception { 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()); UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); StatefulKnowledgeSession ksession = InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env); ut.commit(); List<?> list = new ArrayList<Object>(); // insert and commit ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); ksession.setGlobal("list", list); ksession.insert(1); ksession.insert(2); ksession.fireAllRules(); ut.commit(); // insert and rollback ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); ksession.insert(3); ut.rollback(); // check we rolled back the state changes from the 3rd insert ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); ksession.fireAllRules(); ut.commit(); assertEquals(2, list.size()); // insert and commit ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); ksession.insert(3); ksession.insert(4); ut.commit(); ksession.fireAllRules(); assertEquals(4, list.size()); // rollback again, this is testing that we can do consecutive rollbacks and commits without // issue ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); ksession.insert(5); ksession.insert(6); ut.rollback(); ksession.fireAllRules(); assertEquals(4, list.size()); // now load the ksession ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession( ksession.getIdentifier(), kbase, null, env); ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); ksession.insert(7); ksession.insert(8); ut.commit(); ksession.fireAllRules(); assertEquals(6, list.size()); }
@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(); }