Java Code Examples for org.kie.internal.builder.KnowledgeBuilderFactory#newKnowledgeBuilder()

The following examples show how to use org.kie.internal.builder.KnowledgeBuilderFactory#newKnowledgeBuilder() . 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: MoreBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 7 votes vote down vote up
@Test
public void testQuery() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("org/drools/compiler/integrationtests/simple_query_test.drl"), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    ksession = createKnowledgeSession(kbase);
    
    ksession.insert( new Cheese( "stinky", 5 ) );
    ksession.insert( new Cheese( "smelly", 7 ) );
    
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newQuery("numStinkyCheeses", "simple query"));
    Command<?> cmds = CommandFactory.newBatchExecution(commands);
    ExecutionResults result = (ExecutionResults) ksession.execute(cmds);
    assertNotNull(result, "Batch execution result is null!");

    Object queryResultsObject = result.getValue("numStinkyCheeses");
    assertTrue(queryResultsObject != null && queryResultsObject instanceof QueryResults, "Retrieved object is null or incorrect!");
    
    assertEquals( 1, ((QueryResults) queryResultsObject).size() );
}
 
Example 2
Source File: PropertyReactivityTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPRBindingOnNonexistingWatchedAttribute(){
    final String str =
            "package org.drools.test;\n" +
            "\n" +
            "import org.drools.compiler.integrationtests.PropertyReactivityTest.Klass4;\n" +
            "\n" +
            "global java.util.List list;\n" +
            "\n" +

            "rule \"Get Person name\"\n" +
            "salience 1\n" +
            "when\n" +
            "  $x : Klass4( ) @watch( nmae )\n" +
            "then\n" +
            "end\n";

    final KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    knowledgeBuilder.add( new ByteArrayResource( str.getBytes() ), ResourceType.DRL );

    System.out.println( knowledgeBuilder.getErrors() );
    assertTrue( knowledgeBuilder.hasErrors() );
}
 
Example 3
Source File: ChangeSetTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testIntegregation() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource("changeset1Test.xml",
            getClass()),
                  ResourceType.CHANGE_SET );
    assertFalse( kbuilder.hasErrors() );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );
    ksession.fireAllRules();
    ksession.dispose();

    assertEquals( 2,
                  list.size() );
    assertTrue( list.containsAll( Arrays.asList( new String[]{"rule1", "rule2"} ) ) );
}
 
Example 4
Source File: NamedConsequencesTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutOfScopeNamedConsequences() {
    String str = "import org.drools.compiler.Cheese;\n " +
            "global java.util.List results;\n" +
            "\n" +
            "rule R1 when\n" +
            "    $a: Cheese ( type == \"stilton\" )\n" +
            "    do[t1]\n" +
            "    $b: Cheese ( type == \"cheddar\" )\n" +
            "then\n" +
            "    results.add( $b.getType() );\n" +
            "then[t1]\n" +
            "    results.add( $b.getType() );\n" +
            "end\n";

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

    assertTrue(kbuilder.hasErrors());
}
 
Example 5
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtendCircular() throws Exception {
    String s1 = "package org.drools;\n" +
                "global java.util.List list;\n" +
                "\n" +
                "declare Bean1 extends Bean2 \n" +
                " foo : int @key\n" +
                "end\n" +
                "" +
                "declare Bean2 extends Bean3 \n" +
                " foo : int @key\n" +
                "end\n" +
                "" +
                "declare Bean3 extends Bean1 \n" +
                " foo : int @key\n" +
                "end\n";

    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( );
    kBuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL );
    assertTrue( kBuilder.hasErrors() );

    System.out.println( kBuilder.getErrors() );
    assertTrue( kBuilder.getErrors().toString().contains( "circular" ) );
}
 
Example 6
Source File: RuleExtensionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRuleExtendsMissingOnIncrementalKB() {
    // DROOLS-100
    String str =
            "package org.drools.test;\n" +
                    "\n" +
                    "global java.util.List list;\n" +
                    "\n" +
                    "rule \"Base\"\n" +
                    "when\n" +
                    "  String( this == \"go\" )\n" +
                    "then\n" +
                    "end\n" +
                    "";

    String str2 =
            "package org.drools.test;\n" +
                    "global java.util.List list;\n" +
                    "\n" +
                    "rule \"ExtYes\" extends \"Bse\"\n" +
                    "when\n" +
                    "then\n" +
                    "  list.add( 1 );\n" +
                    "end\n";

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

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

    KnowledgeBuilder kbuilder2 = KnowledgeBuilderFactory.newKnowledgeBuilder( kb );
    kbuilder2.add( ResourceFactory.newByteArrayResource( str2.getBytes() ), ResourceType.DRL );
    assertTrue(kbuilder2.hasErrors());
}
 
Example 7
Source File: AsmGeneratorTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatterDeclarations() {
    String s = 
        "package org.kie.test\n" +
        "global java.util.List list\n" +        
        "rule r1 when\n" +
        "    s1 : String( this == 's1' )\n" +
        "    s2 : String( this == 's2' )\n" +
        "    s3 : String( this == 's3' )\n" +
        "    s4 : String( this == 's4' )\n" +
        "    s5 : String( this == 's5' )\n" +
        "then\n" +
        "    // s5 is missed out on purpose to make sure we only resolved required declarations\n" +
        "   list.add( s1 + s2 + s3 + s5 ); \n" +
        "end\n";
    
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(s.getBytes()), ResourceType.DRL );
    
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list", list );        
    
    ksession.insert( "s1" );
    ksession.insert( "s2" );
    ksession.insert( "s3" );
    ksession.insert( "s4" );
    ksession.insert( "s5" );
    
    ksession.fireAllRules();     
    assertEquals( 1, list.size() );
    assertEquals( "s1s2s3s5", list.get( 0 ));        
}
 
Example 8
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
    public void readDrlInEncodingLatin1() throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( ResourceFactory.newClassPathResource( "test_I18nPerson_latin1.drl.latin1", "ISO-8859-1", getClass() ),
                      ResourceType.DRL );
        if ( kbuilder.hasErrors() ) {
            fail( kbuilder.getErrors().toString() );
        }

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

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

        I18nPerson i18nPerson = new I18nPerson();
        i18nPerson.setGarçon("Value 1");
//        i18nPerson.setÉlève("Value 2");
        ksession.insert(i18nPerson);
        ksession.fireAllRules();

        assertTrue(list.contains("garçon"));
//        assertTrue(list.contains("élève"));
        ksession.dispose();
    }
 
Example 9
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
 * adding a new field to the declared Type
 */
@Test
public void testTypeReDeclarationWithExtraField() {
    //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 10
Source File: LargeRuleBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private static void bigBlobCompile() throws DroolsParserException,
        IOException, Exception {
    StringBuilder buf = new StringBuilder();
    buf.append(getHeader());

    for (int i = 0; i < 1; i++) {
        String name = "x" + i;
        int status = i;

        String r = getTemplate1(name, status);
        buf.append(r);
    }

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

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

    File f = new File("foo.rulebase");
    if (f.exists())
        f.delete();

    ObjectOutput out = new DroolsObjectOutputStream(new FileOutputStream(f));
    out.writeObject(kbase);
    out.flush();
    out.close();
    ObjectInputStream in = new DroolsObjectInputStream(new FileInputStream(f));
    KieBase rb_ = (KieBase) in.readObject();
}
 
Example 11
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private InternalKnowledgeBase 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.hasErrors(), kbuilder.getErrors().toString());

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    return kbase;
}
 
Example 12
Source File: ActionNodeTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleActionNode() throws Exception {                
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( new ClassPathResource( "ActionNodeTest.xml", ActionNodeTest.class ), ResourceType.DRF );
    KieBase kbase = kbuilder.newKieBase();
    
    KieSession ksession = kbase.newKieSession();
    List<String> list = new ArrayList<String>();
    ksession.setGlobal( "list", list );
    
    ksession.startProcess( "process name" );
    
    assertEquals( 1, list.size() );
    assertEquals( "action node was here", list.get(0) );        
}
 
Example 13
Source File: ParserTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testErrorLineNumbers() throws Exception {
    // this test aims to test semantic errors
    // parser errors are another test case
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("errors_in_rule.drl", getClass()), ResourceType.DRL);

    final KnowledgeBuilderError[] errors = kbuilder.getErrors().toArray(new KnowledgeBuilderError[0]);
    assertEquals(3, errors.length);

    final DescrBuildError stiltonError = (DescrBuildError) errors[0];
    assertTrue(stiltonError.getMessage().contains("Stilton"));
    assertNotNull(stiltonError.getDescr());
    assertTrue(stiltonError.getLine() != -1);

    // check that its getting it from the ruleDescr
    assertEquals(stiltonError.getLine(), stiltonError.getDescr().getLine());
    // check the absolute error line number (there are more).
    assertEquals(26, stiltonError.getLine());

    final DescrBuildError poisonError = (DescrBuildError) errors[1];
    assertTrue(poisonError.getMessage().contains("Poison"));
    assertEquals(28, poisonError.getLine());

    final KnowledgeBuilderConfigurationImpl cfg = new KnowledgeBuilderConfigurationImpl();
    final JavaDialectConfiguration javaConf = (JavaDialectConfiguration) cfg.getDialectConfiguration("java");
    switch (javaConf.getCompiler()) {
        case NATIVE:
            assertTrue(errors[2].getMessage().contains("illegal"));
            break;
        case ECLIPSE:
            assertTrue(errors[2].getMessage().contains("add"));
            break;
        default:
            fail("Unknown compiler used");
    }

    // now check the RHS, not being too specific yet, as long as it has the
    // rules line number, not zero
    final DescrBuildError rhsError = (DescrBuildError) errors[2];
    assertTrue(rhsError.getLine() >= 23 && rhsError.getLine() <= 32);
}
 
Example 14
Source File: AgendaFilterTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testAgendaFilter() {
    // JBRULES-3374
    String drl = "package org.drools\n" +
            " \n" +
            "import org.jbpm.integrationtests.AgendaFilterTest.Message\n" +
            " \n" +
            "rule \"R1\"\n" +
            "ruleflow-group \"node1\"\n" +
            "no-loop \n" +
            "salience 3\n" +
            "    when\n" +
            "        Message( status == Message.GOODBYE, myMessage : message )\n" +
            "    then\n" +
            "       System.out.println( \"R1\"  );\n" +
            "end\n" +
            "\n" +
            "rule \"R2\"\n" +
            "ruleflow-group \"node1\"\n" +
            "no-loop \n" +
            "salience 2\n" +
            "    when\n" +
            "        m : Message( status == Message.HELLO, myMessage : message )\n" +
            "    then\n" +
            "        System.out.println( \"R2\"  );\n" +
            "        m.setMessage( \"Goodbye cruel world\" );\n" +
            "        m.setStatus( Message.GOODBYE );\n" +
            "        update( m );\n" +
            "end\n" +
            "\n" +
            "rule \"R3\"\n" +
            "ruleflow-group \"node2\"\n" +
            "no-loop \n" +
            "    when\n" +
            "        m: Message( status == Message.GOODBYE, myMessage : message )\n" +
            "    then\n" +
            "        System.out.println( \"R3\"  );\n" +
            "        m.setStatus(5);\n" +
            "        update (m);\n" +
            "        \n" +
            "end";

    String rf = "<?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=\"process-test\" package-name=\"com.sample\" >\n" +
            "\n" +
            "  <header>\n" +
            "  </header>\n" +
            "\n" +
            "  <nodes>\n" +
            "    <start id=\"1\" name=\"Start\" x=\"122\" y=\"96\" width=\"48\" height=\"48\" />\n" +
            "    <ruleSet id=\"2\" name=\"Node1\" x=\"277\" y=\"96\" width=\"80\" height=\"48\" ruleFlowGroup=\"node1\" />\n" +
            "    <ruleSet id=\"3\" name=\"Node2\" x=\"433\" y=\"98\" width=\"80\" height=\"48\" ruleFlowGroup=\"node2\" />\n" +
            "    <end id=\"4\" name=\"End\" x=\"645\" y=\"96\" width=\"48\" height=\"48\" />\n" +
            "  </nodes>\n" +
            "\n" +
            "  <connections>\n" +
            "    <connection from=\"1\" to=\"2\" />\n" +
            "    <connection from=\"2\" to=\"3\" />\n" +
            "    <connection from=\"3\" to=\"4\" />\n" +
            "  </connections>\n" +
            "\n" +
            "</process>";

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

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

    KieSession ksession = createKieSession(kbuilder.getKnowledgePackages().toArray(new KiePackage[0]));

    // go !
    Message message = new Message();
    message.setMessage("Hello World");
    message.setStatus(Message.HELLO);
    ksession.insert(message);
    ksession.startProcess("process-test");
    
    assertEquals("Goodbye cruel world", message.getMessage());
}
 
Example 15
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 16
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testKnowledgeProviderWithRules() {
    KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    String str = "";
    str += "package org.drools.compiler.test1\n";
    str += "rule rule1\n";
    str += "when\n";
    str += "then\n";
    str += "end\n\n";
    str += "rule rule2\n";
    str += "when\n";
    str += "then\n";
    str += "end\n";
    builder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), ResourceType.DRL );

    str = "package org.drools.compiler.test2\n";
    str += "rule rule3\n";
    str += "when\n";
    str += "then\n";
    str += "end\n\n";
    str += "rule rule4\n";
    str += "when\n";
    str += "then\n";
    str += "end\n";
    builder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), ResourceType.DRL );

    Collection<KiePackage> pkgs = builder.getKnowledgePackages();
    assertNotNull( pkgs );
    assertEquals( 2, pkgs.size() );

    KiePackage test1 = getKnowledgePackage(pkgs, "org.drools.compiler.test1" );
    Collection<Rule> rules = test1.getRules();
    assertEquals( 2, rules.size() );
    Rule rule = getRule( rules, "rule1" );
    assertEquals("rule1", rule.getName() );
    rule = getRule( rules, "rule2" );
    assertEquals( "rule2", rule.getName() );

    KiePackage test2 = getKnowledgePackage(pkgs, "org.drools.compiler.test2" );
    rules = test2.getRules();
    assertEquals( 2, rules.size() );
    rule = getRule( rules, "rule3" );
    assertEquals("rule3", rule.getName() );
    rule = getRule( rules, "rule4" );
    assertEquals( "rule4", rule.getName() );
}
 
Example 17
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testTMSwithQueries() {
    String str =""+
            "package org.drools.compiler.test;\n" +
            "\n" +
            "global java.util.List list; \n" +
            "\n" +
            "declare Bean\n" +
            "    str : String\n" +
            "end\n" +
            "\n" +
            "query bean ( String $s )\n" +
            "    Bean(  $s ; )\n" +
            "end\n" +
            "\n" +
            "\n" +
            "rule \"init\"\n" +
            "when\n" +
            "then\n" +
            "    insert( new Bean(\"AAA\") );\n" +
            "    insert( \"x\" );\n" +
            "end\n" +
            "\n" +
            "rule \"LogicIn\"\n" +
            "when\n" +
            "    String( this == \"x\" )\n" +
            "    ?bean(  \"AAA\" ; )\n" +
            "then\n" +
            "    insertLogical(\"y\");\n" +
            "    retract(\"x\");\n" +
            "end " +
            "\n" +
            "rule \"Never\"\n" +
            "salience -999\n" +
            "when\n" +
            "    $s : String( this == \"y\" )\n" +
            "then\n" +
            "    list.add($s);\n" +
            "end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()),
            ResourceType.DRL );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession kSession = createKnowledgeSession(kbase);
    try {
        List list = new ArrayList();
        kSession.setGlobal("list",list);


        kSession.fireAllRules();
        assertEquals(0, list.size());
    } finally {
        kSession.dispose();
    }
}
 
Example 18
Source File: PhreakLiaNodeTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
    public void test2() {
        String str = "package org.drools.compiler.test\n" +
                "\n" +
                "import " + A.class.getCanonicalName() + "\n" +
                "import " + B.class.getCanonicalName() + "\n" +
                "\n" +
                "rule r1 \n" +
                "    when \n" +
                "        $a : A( object == 1 )\n" +
                "    then \n" +
                "        System.out.println( $a ); \n" +
                "end \n" +
                "rule r2 \n" +
                "    when \n" +
                "        $a : A( object == 2 )\n" +
                "    then \n" +
                "        System.out.println( $a ); \n" +
                "end \n " +
                "rule r3 \n" +
                "    when \n" +
                "        $a : A( object == 2 )\n" +
                "        $b : B( )\n" +
                "    then \n" +
                "        System.out.println( $a + \" : \" + $b  );"
                + "      modify($a) { setObject(3) };  \n" +
                "end \n " +                
                "rule r4 \n" +
                "    when \n" +
                "        $a : A( object == 3 )\n" +
                "    then \n" +
                "        System.out.println( $a ); \n" +
                "end \n";
                
        KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

        if ( builder.hasErrors() ) {
            throw new RuntimeException(builder.getErrors().toString());
        }
        
        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(builder.getKnowledgePackages());

        KieSession ksession = knowledgeBase.newKieSession();

        InternalFactHandle fhB = ( InternalFactHandle ) ksession.insert( B.b(1) );
        
        InternalFactHandle fhA = ( InternalFactHandle ) ksession.insert( A.a(1) );
        ksession.fireAllRules();        
        System.out.println( "---1---" );
        
//        ksession.update( fhA, a(1) );
//        ksession.fireAllRules();
//        System.out.println( "---2---" );
//
        
        InternalFactHandle fhB2 = ( InternalFactHandle ) ksession.insert( B.b(2) );
        InternalFactHandle fhB3 = ( InternalFactHandle ) ksession.insert( B.b(3) );
        
        ksession.update( fhA, A.a(2) );
        ksession.fireAllRules(); 
        System.out.println( "---3---" );

//        ksession.update( fhA, a(2) );
//        ksession.fireAllRules();
//        System.out.println( "---4---" );
//        
//        ksession.update( fhA, a(3) );
//        ksession.fireAllRules(); 
//        System.out.println( "---5---" );
//        
//        ksession.update( fhB, b(1) );
//
//        ksession.update( fhA, a(3) );
//        ksession.fireAllRules();  
        
//        ksession.update( fhA, a(1) );
//        ksession.fireAllRules();        
//
//        ksession.update( fhA, a(1) );
//        ksession.fireAllRules();          
        
        ksession.dispose();        
    }
 
Example 19
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testIdeographicSpaceInDSL() throws Exception {
    // JBRULES-3723
    String dsl =
            "// Testing 'IDEOGRAPHIC SPACE' (U+3000)\n" +
            "[when]名前が {firstName}=Person(name==\"山本 {firstName}\")\n" +
            "[then]メッセージ {message}=messages.add(\"メッセージ \" + {message});";

    String dslr =
            "package test\n" +
            "\n" +
            "import org.drools.compiler.Person\n" +
            "\n" +
            "expander test_I18n.dsl\n" +
            "\n" +
            "global java.util.List messages;\n" +
            "\n" +
            "rule \"IDEOGRAPHIC SPACE test\"\n" +
            "    when\n" +
            "        // Person(name==\"山本 太郎\")\n" +
            "        名前が 太郎\n" +
            "    then\n" +
            "        // messages.add(\"メッセージ ルールにヒットしました\");\n" +
            "         メッセージ \"ルールにヒットしました\"\n" +
            "end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    // Here I should explicitly set "UTF-8" because String.getBytes() depends on platform encoding and is not dealt by Drools side.
    kbuilder.add( ResourceFactory.newByteArrayResource(dsl.getBytes("UTF-8")), ResourceType.DSL );
    kbuilder.add( ResourceFactory.newByteArrayResource( dslr.getBytes("UTF-8") ), ResourceType.DSLR );
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }

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

    List messages = new ArrayList();
    ksession.setGlobal( "messages", messages );

    Person person = new Person();
    person.setName("山本 太郎");
    ksession.insert(person);
    ksession.fireAllRules();

    assertTrue(messages.contains("メッセージ ルールにヒットしました"));

    ksession.dispose();
}
 
Example 20
Source File: ProcessWorkItemTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testWorkItemImmediateCompletion() {
	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" +
		"    <variables>\n" +
		"      <variable name=\"UserName\" >\n" +
		"        <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
		"        <value>John Doe</value>\n" +
		"      </variable>\n" +
 		"      <variable name=\"Person\" >\n" +
		"        <type name=\"org.jbpm.process.core.datatype.impl.type.ObjectDataType\" className=\"org.jbpm.integrationtests.test.Person\" />\n" +
		"      </variable>\n" +
		"      <variable name=\"MyObject\" >\n" +
		"        <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
		"      </variable>\n" +
		"      <variable name=\"Number\" >\n" +
		"        <type name=\"org.jbpm.process.core.datatype.impl.type.IntegerDataType\" />\n" +
		"      </variable>\n" +
		"    </variables>\n" +
        "  </header>\n" +
        "\n" +
        "  <nodes>\n" +
        "    <start id=\"1\" name=\"Start\" />\n" +
        "    <workItem id=\"2\" name=\"HumanTask\" >\n" +
        "      <work name=\"Human Task\" >\n" +
        "        <parameter name=\"ActorId\" >\n" +
        "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
        "          <value>#{UserName}</value>\n" +
        "        </parameter>\n" +
        "        <parameter name=\"Content\" >\n" +
        "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
        "          <value>#{Person.name}</value>\n" +
        "        </parameter>\n" +
        "        <parameter name=\"TaskName\" >\n" +
        "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
        "          <value>Do something</value>\n" +
        "        </parameter>\n" +
        "        <parameter name=\"Priority\" >\n" +
        "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
        "        </parameter>\n" +
        "        <parameter name=\"Comment\" >\n" +
        "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
        "        </parameter>\n" +
        "        <parameter name=\"Attachment\" >\n" +
        "          <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
        "        </parameter>\n" +
        "      </work>\n" +
        "      <mapping type=\"in\" from=\"MyObject\" to=\"Attachment\" />" +
        "      <mapping type=\"in\" from=\"Person.name\" to=\"Comment\" />" +
        "      <mapping type=\"out\" from=\"Result\" to=\"MyObject\" />" +
        "      <mapping type=\"out\" from=\"Result.length()\" to=\"Number\" />" +
        "    </workItem>\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( ResourceFactory.newReaderResource( source ), ResourceType.DRF );
    
    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kpkgs );        
    KieSession ksession = kbase.newKieSession();
	
    ImmediateTestWorkItemHandler handler = new ImmediateTestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("UserName", "John Doe");
    Person person = new Person();
    person.setName("John Doe");
    parameters.put("Person", person);
    WorkflowProcessInstance processInstance = (WorkflowProcessInstance)
    	ksession.startProcess("org.drools.actions", parameters);
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
}