Java Code Examples for org.kie.internal.builder.KnowledgeBuilder#hasErrors()

The following examples show how to use org.kie.internal.builder.KnowledgeBuilder#hasErrors() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FireUntilHaltAccumulateTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
        System.err.println(kbuilder.getErrors().toString());
    }
    final KieBaseConfiguration config =
            KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption( EventProcessingOption.STREAM);

    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(config);
    kbase.addPackages(kbuilder.getKnowledgePackages());

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

    this.statefulSession = kbase.newKieSession(sessionConfig, null);
    this.stockFactory = new StockFactory(kbase);
}
 
Example 2
Source File: KieService.java    From Liudao with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 单一规则上线
 *
 * @param packageName
 * @param ruleName
 */
public void addRule(String packageName, String ruleName) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource(packageName + "/" + ruleName + ".drl"), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        logger.error("Unable to compile drl. " + packageName + ruleName + ".drl");
        return;
    } else {
        if (kbase.getRule(packageName, ruleName) != null) {
            logger.info("update rule: " + packageName + "." + ruleName);
        } else {
            logger.info("add rule: " + packageName + "." + ruleName);
        }
    }

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    kieSession = kbase.newStatelessKieSession();
    setGlobal();
    printRules();
}
 
Example 3
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypeReDeclarationPojoMoreFields() {
    String str1 = "" +
                  "package org.drools \n" +
                  "import " + TypeDeclarationTest.class.getName() + ".ClassC; \n" +
                  "" +
                  "declare " + TypeDeclarationTest.class.getName() + ".ClassC \n" +
                  "    name : String \n" +
                  "    age : Integer \n" +
                  "    address : Objet \n" +
                  "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

    if ( ! kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
}
 
Example 4
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypeReDeclarationPojoLessFields() {
    String str1 = "" +
                  "package org.drools \n" +
                  "import " + TypeDeclarationTest.class.getName() + ".ClassC; \n" +
                  "" +
                  "declare " + TypeDeclarationTest.class.getName() + ".ClassC \n" +
                  "    name : String \n" +
                  "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

    if ( ! kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
}
 
Example 5
Source File: Query2Test.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvalRewrite() throws Exception {
    String str = "" +
    "package org.drools.compiler;\n" +
    "global java.util.List results;\n" +
    "rule \"eval rewrite\"\n" +
    "    when\n" +
    "        $o1 : OrderItem( order.number == 11, $seq : seq == 1 )\n" +
    //"        $o2 : OrderItem( order.number == $o1.order.number, seq != $seq )\n" +
    "        $o2 : Order( items[(Integer) 1] == $o1 ) \n" +
    "    then\n" +
    "        System.out.println( $o1 + \":\" + $o2 );\n" +
    "end        \n";
    
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL );
    
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    
    final Order order1 = new Order( 11,
                                    "Bob" );
    final OrderItem item11 = new OrderItem( order1,
                                            1 );
    final OrderItem item12 = new OrderItem( order1,
                                            2 );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);
    ksession.insert( order1 );
    ksession.insert( item11 );
    ksession.insert( item12 );
    
    ksession.fireAllRules();
    

}
 
Example 6
Source File: LegacyTraitTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieSession getSessionFromString(String drl) {
    KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    knowledgeBuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()),
                         ResourceType.DRL);
    if (knowledgeBuilder.hasErrors()) {
        throw new RuntimeException(knowledgeBuilder.getErrors().toString());
    }

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(knowledgeBuilder.getKnowledgePackages());

    KieSession session = kbase.newKieSession();
    return session;
}
 
Example 7
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * 2 resources (containing different declarations of the same type ) are added
 * to the kbuilder.
 * The expectation here is that the compilation fails because we are
 * trying to add an incompatible re-definition of the declared type:
 * it introduces a new field 'lastName'
 */
@Test
public void testTypeReDeclarationWithExtraField2() {
    //same package, different resources
    String str1 = "";
    str1 += "package org.drools.compiler \n" +
    		"declare org.drools.ClassA \n" +
    		"    name : String \n" +
    		"    age : Integer \n" +
    		"end \n";

    String str2 = "";
    str2 += "package org.drools.compiler \n" +
    		"declare org.drools.ClassA \n" +
    		"    name : String \n" +
    		"    lastName : String \n" +
    		"end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

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

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

}
 
Example 8
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleTypeReDeclaration() {
    //same package, different resources
    String str1 = "";
    str1 += "package org.drools \n" +
            "declare org.drools.ClassC \n" +
            "    name : String \n" +
            "    age : Integer \n" +
            "end \n";

    String str2 = "";
    str2 += "package org.drools \n" +
            "declare org.drools.ClassC \n" +
            "    name : String \n" +
            "    age : Integer \n" +
            "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

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

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


}
 
Example 9
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testTokensInString(){
    //should query antldr DFA63 class but don't know how
    final String [] operators = {"," ,"=" , "|=", "*"};
    //test various in consequence
    final 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";

    final String strEnd = "good\"};\n" + "end\n";
    final StringBuilder failures = new StringBuilder();
    for (final String oper : operators) {
        final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        final 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());
        }
    }
    final String failStr = failures.toString();
    if (failStr.length() > 0) {
        fail(failStr);
    }
}
 
Example 10
Source File: LogicalTraitTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@ParameterizedLogicalTraitTest
public void testShadowAlias(VirtualPropertyMode mode) {

    KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilderImpl.add(
            ResourceFactory.newClassPathResource("org/drools/compiler/factmodel/traits/testTraitedAliasing.drl"),
            ResourceType.DRL);
    if (kbuilderImpl.hasErrors()) {
        fail(kbuilderImpl.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilderImpl.getKnowledgePackages());

    TraitFactory.setMode(mode, kbase);

    KieSession ks = kbase.newKieSession();

    ArrayList list = new ArrayList();
    ks.setGlobal("list", list);

    ks.fireAllRules();

    for (Object o : ks.getObjects()) {
        System.out.println(o);
    }

    try {
        ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    System.out.println(list);
    assertFalse(list.contains(false));
    assertEquals(8, list.size());
}
 
Example 11
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected void testInvalidDrl(final String drl) {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
        logger.warn(kbuilder.getErrors().toString());
    }
    assertTrue(kbuilder.hasErrors());
}
 
Example 12
Source File: DslTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDSLWithSingleDot() {
    // DROOLS-768
    String dsl = "[when][]if there is a simple event\n" +
                 "{evtName}={evtName}" +
                 ": SimpleEvent()\n" +
                 "[when][]and a simple event 2\n" +
                 "{evtName2} with the same {attribute} as {evtName}={evtName2} " +
                 ": SimpleEvent2(" +
                 "{attribute}=={evtName}.{attribute}" +
                 ")\n" +
                 "[then][]ok=System.out.println(\"that works\");\n" +
                 "\n";

    String drl = "declare SimpleEvent\n" +
                 "  code: String\n" +
                 "end\n" +
                 "\n" +
                 "declare SimpleEvent2\n" +
                 "  code: String\n" +
                 "end\n" +
                 "rule \"RG_CORR_RECOK_OK\"\n" +
                 "when\n" +
                 "if there is a simple event $evt\n" +
                 "and a simple event 2 $evt2 with the same code as $evt\n" +
                 "then\n" +
                 "ok\n" +
                 "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(dsl.getBytes()), ResourceType.DSL );
    kbuilder.add( ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DSLR);

    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
}
 
Example 13
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclareExtendsJavaParentOuterPackaga() {
    String drl = "package org.drools.test; \n" +
                 "import org.drools.compiler.integrationtests.ExtendsTest.X; \n" +
                 "declare Student extends X end \n" +
                 "";
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(  );
    kBuilder.add( new ByteArrayResource( drl.getBytes() ), ResourceType.DRL );
    if ( kBuilder.hasErrors() ) {
        System.err.println( kBuilder.getErrors() );
    }
    assertFalse( kBuilder.hasErrors() );
}
 
Example 14
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNestedEnumWithMap() {
    final String str = ""+
       "package org.drools.compiler.test \n" +
       "import " + DMap.class.getCanonicalName() + " \n" +
       "import " + Triangle.class.getCanonicalName() + "\n" +
       "global java.util.List list \n" +
       "rule \"show\" \n" + 
       "when  \n" + 
       "    $m : DMap( this[Triangle.Type.ACUTE] == 'xxx') \n" + 
       "then \n" + 
       "    list.add('r1'); \n" + 
       "end \n";

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

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

    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());

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

    final DMap m = new DMap();
    m.put(Triangle.Type.ACUTE, "xxx");

    ksession.insert(m);
    ksession.fireAllRules();
    assertEquals("r1", list.get(0));
}
 
Example 15
Source File: ProcessActionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testActionContextMVEL() {
	KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
       Reader source = new StringReader(
           "<?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=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n" +
           "\n" +
           "  <header>\n" +
		"    <imports>\n" +
		"      <import name=\"org.jbpm.integrationtests.test.Message\" />\n" +
		"    </imports>\n" +
		"    <globals>\n" +
		"      <global identifier=\"list\" type=\"java.util.List\" />\n" +
		"    </globals>\n" +
   		"    <variables>\n" +
   		"      <variable name=\"variable\" >\n" +
   		"        <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
   		"        <value>SomeText</value>\n" +
   		"      </variable>\n" +
   		"    </variables>\n" +
           "  </header>\n" +
           "\n" +
           "  <nodes>\n" +
           "    <start id=\"1\" name=\"Start\" />\n" +
		"    <actionNode id=\"2\" name=\"MyActionNode\" >\n" +
		"      <action type=\"expression\" dialect=\"mvel\" >System.out.println(\"Triggered\");\n" +
		"System.out.println(kcontext.getKnowledgeRuntime());\n" +
		"String myVariable = (String) kcontext.getVariable(\"variable\");\n" +
		"list.add(myVariable);\n" +
		"String nodeName = kcontext.getNodeInstance().getNodeName();\n" +
		"list.add(nodeName);\n" +
		"insert( new Message() );\n" +
		"</action>\n" +
		"    </actionNode>\n" + 
           "    <end id=\"3\" name=\"End\" />\n" +
           "  </nodes>\n" +
           "\n" +
           "  <connections>\n" +
           "    <connection from=\"1\" to=\"2\" />\n" +
           "    <connection from=\"2\" to=\"3\" />\n" +
           "  </connections>\n" +
           "\n" +
           "</process>");
       kbuilder.add(new ReaderResource(source), ResourceType.DRF);
       if ( kbuilder.hasErrors() ) {
           fail( kbuilder.getErrors().toString() );
       }
       KieBase kbase = kbuilder.newKieBase();
       KieSession ksession = kbase.newKieSession();
       List<String> list = new ArrayList<String>();
       ksession.setGlobal("list", list);
       ProcessInstance processInstance =
           ksession.startProcess("org.drools.actions");
       assertEquals(2, list.size());
       assertEquals("SomeText", list.get(0));
       assertEquals("MyActionNode", list.get(1));
       Collection<FactHandle> factHandles = ksession.getFactHandles(new ObjectFilter() {
		public boolean accept(Object object) {
			return object instanceof Message;
		}
       });
       assertFalse(factHandles.isEmpty());
       assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
   }
 
Example 16
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeclaresInForeignPackages() {
    String str1 = "" +
                  "package org.drools \n" +

                  "declare foreign.ClassC fld : foreign.ClassD end " +

                  "declare foreign.ClassD end " +

                  "";


    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

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

}
 
Example 17
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testArrayAccessorWithGenerics() {
    final 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( addresses[0] == new Address('s1'), addresses[0].street == new Address('s1').street ) \n" + 
       "then \n" + 
       "    list.add('r1'); \n" + 
       "end \n";

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

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

    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());

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

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

    ksession.insert(p);
    ksession.fireAllRules();
    assertEquals("r1", list.get(0));

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

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

    if (constraint instanceof MvelConstraint) {
        assertTrue(((MvelConstraint) constraint).getFieldExtractor() instanceof MVELObjectClassFieldReader);
        assertEquals(new Address("s1"), ((MvelConstraint) constraint).getField().getValue());
    }

    alphanode = (AlphaNode) alphanode.getObjectSinkPropagator().getSinks()[0];
    constraint = alphanode.getConstraint();

    if (constraint instanceof MvelConstraint) {
        assertTrue(((MvelConstraint) constraint).getFieldExtractor() instanceof MVELObjectClassFieldReader);
        assertEquals(new Address("s1").getStreet(), ((MvelConstraint) constraint).getField().getValue());
    }
}
 
Example 18
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipleInheritanceWithPosition6() throws Exception {
    // DROOLS-249
    String drl =
            "package org.drools.test\n" +
            "declare trait PosTrait\n" +
            "@propertyReactive\n" +
            " field0 : int = 100 //@position(0)\n" +
            " field1 : int = 101 //@position(1)\n" +
            " field2 : int = 102 //@position(0)\n" +
            "end\n" +
            "\n" +
            "declare trait SecPosTrait\n" +
            "@propertyReactive\n" +
            " field3 : int = 100 //@position(0)\n" +
            " field1 : int = 101 //@position(1)\n" +
            "end\n" +
            "\n" +
            "declare trait MultiInhPosTrait extends PosTrait, SecPosTrait\n" +
            "@propertyReactive\n" +
            " mfield0 : int = 200 //@position(0)\n" +
            " mfield1 : int = 201 //@position(2)\n" +
            "end";
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( );
    kBuilder.add( new ByteArrayResource( drl.getBytes() ), ResourceType.DRL );
    if ( kBuilder.hasErrors() ) {
        System.err.println( kBuilder.getErrors() );
    }
    assertFalse( kBuilder.hasErrors() );

    InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
    knowledgeBase.addPackages( kBuilder.getKnowledgePackages() );

    FactType sw = knowledgeBase.getFactType( "org.drools.test", "MultiInhPosTrait" );
    assertEquals( 6, sw.getFields().size() );
    assertEquals( "field0", sw.getFields().get(0).getName() );
    assertEquals( "field1", sw.getFields().get(1).getName() );
    assertEquals( "field2", sw.getFields().get(2).getName() );
    assertEquals( "field3", sw.getFields().get(3).getName() );
    assertEquals( "mfield0", sw.getFields().get(4).getName() );
    assertEquals( "mfield1", sw.getFields().get(5).getName() );
}
 
Example 19
Source File: TerminalNodeIteratorTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testTerminalNodeListener() {
    String str = "package org.kie.test \n" +
                 "\n" +
                 "rule rule1 when\n" +
                 "then\n" +
                 "end\n" +
                 "rule rule2 when\n" +
                 "then\n" +
                 "end\n" +
                 "rule rule3 when\n" +
                 "    Object()" +
                 "then\n" +
                 "end\n" +
                 "rule rule4 when\n" +
                 "    Object()" +
                 "then\n" +
                 "end\n" +
                 "rule rule5 when\n" + // this will result in two terminal nodes
                 "    Object() or\n" +
                 "    Object()\n" +
                 "then\n" +
                 "end\n";

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

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

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );

    List<String> nodes = new ArrayList<String>();
    Iterator it = TerminalNodeIterator.iterator(kbase);
    for ( TerminalNode node = (TerminalNode) it.next(); node != null; node = (TerminalNode) it.next() ) {
        nodes.add( ((RuleTerminalNode) node).getRule().getName() );
    }

    assertEquals( 6,
                  nodes.size() );
    assertTrue( nodes.contains( "rule1" ) );
    assertTrue( nodes.contains( "rule2" ) );
    assertTrue( nodes.contains( "rule3" ) );
    assertTrue( nodes.contains( "rule4" ) );
    assertTrue( nodes.contains( "rule5" ) );

    int first = nodes.indexOf( "rule5" );
    int second = nodes.lastIndexOf( "rule5" );
    assertTrue( first != second );
}
 
Example 20
Source File: DslTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
    public void testDSLWithIndividualConstraintMappings() throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( ResourceFactory.newClassPathResource( "test_dslWithIndividualConstraints.dsl", getClass() ),
                              ResourceType.DSL );
        kbuilder.add( ResourceFactory.newClassPathResource( "test_dslWithIndividualConstraints.dslr", getClass() ) ,
                              ResourceType.DSLR );

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

        // Check errors
        final String err = kbuilder.getErrors().toString();
        assertEquals( "",
                      err );
        assertEquals(0,
                     kbuilder.getErrors().size());

        // the compiled package
        final Collection<KiePackage> pkgs = kbuilder.getKnowledgePackages();
        assertEquals(1, pkgs.size());

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages(pkgs);
        kbase    = SerializationHelper.serializeObject(kbase);

        KieSession session = createKnowledgeSession(kbase);
        List results = new ArrayList();
        session.setGlobal("results",
                          results);
        Cheese cheese = new Cheese( "stilton",
                                    42 );
        session.insert(cheese);

//        wm  = SerializationHelper.serializeObject(wm);
        session.fireAllRules();

        // should have fired
        assertEquals( 1,
                      results.size() );
        assertEquals(cheese,
                     results.get(0));

    }