org.kie.internal.builder.KnowledgeBuilder Java Examples

The following examples show how to use org.kie.internal.builder.KnowledgeBuilder. 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: ParallelBuildTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testParallelBuild() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    StringBuilder sb = new StringBuilder();
    int rc = 0;
    for (Class<?> c : classes) {
        sb.append("rule \"rule_" + rc++ + "\"\n");
        sb.append("  when\n");
        sb.append("    a : " + c.getName() + "()\n");
        sb.append("  then\n");
        sb.append("    System.out.print(\".\");\n");
        sb.append("end\n");
        sb.append("\n");
    }

    kbuilder.add(ResourceFactory.newByteArrayResource(sb.toString().getBytes(StandardCharsets.UTF_8)), ResourceType.DRL);
}
 
Example #2
Source File: MapConstraintTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapAccessWithVariable2() {
    final String str = "package org.drools.compiler;\n" +
            "import java.util.Map;\n" +
            "rule \"map access with variable\"\n" +
            "    when\n" +
            "        $key : String( )\n" +
            "        $p1 : Person( name == 'Bob', namedAddresses[$key] != null, $na : namedAddresses[$key] )\n" +
            "        $p2 : Person( name == 'Mark', namedAddresses[$key] == $na )\n" +
            "    then\n" +
            "end\n";

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

    assertTrue(kbuilder.hasErrors());
}
 
Example #3
Source File: SegmentMemoryPrototypeTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSegmentMemoryPrototype() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(DRL.getBytes()),
                  ResourceType.DRL );

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

    KieSession ksession = kbase.newKieSession();
    try {
        checkKieSession(ksession);
    } finally {
        ksession.dispose();
    }

    // Create a 2nd KieSession (that will use segment memory prototype) and check that it works as the former one
    KieSession ksession2 = kbase.newKieSession();
    try {
        checkKieSession(ksession2);
    } finally {
        ksession2.dispose();
    }
}
 
Example #4
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewClassPathResource() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    // newClassPathResource without specifying encoding
    kbuilder.add( ResourceFactory.newClassPathResource( "test_I18nPerson_utf8_forTestNewClassPathResource.drl", 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.set名称("山田花子");
    ksession.insert(i18nPerson);
    ksession.fireAllRules();

    assertTrue(list.contains("名称は山田花子です"));

    ksession.dispose();
}
 
Example #5
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testClassNameClashing() {
    String str = "";
    str += "package org.kie \n" +
    		"declare org.kie.Character \n" +
    		"    name : String \n" +
    		"end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

    if ( kbuilder.hasErrors() ) {
       fail( kbuilder.getErrors().toString() );
    }
}
 
Example #6
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
/**
 * 2 resources (containing a the same type declaration) are added to the
 * kbuilder.
 * The expectation here is to silently discard the second type declaration.
 */
@Test
public void testDuplicatedTypeDeclarationInDifferentResources() {
    //same package, different resources
    String str1 = "";
    str1 += "package org.drools.compiler \n" +
    		"declare org.drools.ClassA \n" +
    		"    name : String \n" +
    		"end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

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

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

}
 
Example #7
Source File: NamedConsequencesTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrongConsequenceName() {
    String str = "import org.drools.compiler.Cheese;\n " +
            "global java.util.List results;\n" +
            "\n" +
            "rule R1 dialect \"mvel\" when\n" +
            "    $a: Cheese ( type == \"stilton\" )\n" +
            "    $b: Cheese ( type == \"cheddar\" )\n" +
            "    if ( 200 < 400 ) break[t2]\n" +
            "then\n" +
            "    results.add( $b.getType() );\n" +
            "then[t1]\n" +
            "    results.add( $a.getType().toUpperCase() );\n" +
            "end\n";

    KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    builder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), ResourceType.DRL);
    assertTrue ( builder.hasErrors() );
}
 
Example #8
Source File: PropertyReactivityTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPRBindingOnNonexistingAttributes(){
    final String str =
            "package org.drools.test;\n" +
            "\n" +
            "import " + Klass4.class.getCanonicalName() + ";\n" +
            "\n" +
            "global java.util.List list;\n" +
            "\n" +

            "rule \"Get Person name\"\n" +
            "salience 1\n" +
            "when\n" +
            "  $x : Klass4( $name: nonexistingName )\n" +
            "then\n" +
            "  list.add( $fullName );\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 #9
Source File: NamedConsequencesTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutOfScopeNamedConsequencesWithOr1() {
    String str = "import org.drools.compiler.Cheese;\n " +
            "global java.util.List results;\n" +
            "\n" +
            "rule R1 when\n" +
            "    ( $a: Cheese ( type == \"stilton\" )\n" +
            "    or\n" +
            "    $b: Cheese ( type == \"gorgonzola\" ) do[t1] )\n" +
            "    $c: Cheese ( type == \"cheddar\" )\n" +
            "then\n" +
            "    results.add( $c.getType() );\n" +
            "then[t1]\n" +
            "    results.add( $a.getType() );\n" +
            "end\n";

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

    assertTrue(kbuilder.hasErrors());
}
 
Example #10
Source File: SerializedPackageMergeTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private StatelessKieSession getSession(boolean serialize) throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    for ( String drl : DRLs ) {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( ResourceFactory.newInputStreamResource(getClass().getResourceAsStream(drl)),
                      ResourceType.DRL );
        
        assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());
        
        Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();

        Collection<KiePackage> newCollection = null;
        if ( serialize ) {
            newCollection = new ArrayList<KiePackage>();
            for( KiePackage kpkg : kpkgs) {
                kpkg = SerializationHelper.serializeObject(kpkg);
                newCollection.add( kpkg );
            }
        } else {
            newCollection = kpkgs;
        }
        kbase.addPackages( newCollection );
    }
    return kbase.newStatelessKieSession();
}
 
Example #11
Source File: JTMSTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromString( String drlString) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    try {
        System.setProperty("drools.negatable", "on");
        kBuilder.add(ResourceFactory.newByteArrayResource(drlString.getBytes()),
                     ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
            fail();
        }
    } finally {
        System.setProperty("drools.negatable", "off");
    }

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

    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.JTMS );
    
    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #12
Source File: JTMSTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromFile( String ruleFile ) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add( ResourceFactory.newClassPathResource( ruleFile, getClass() ),
            ResourceType.DRL );
    if ( kBuilder.hasErrors() ) {
        System.err.println( kBuilder.getErrors() );
        fail();
    }

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

    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.JTMS );
    
    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #13
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallActivity() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-CallActivity.bpmn2"), ResourceType.BPMN2);
    kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-CallActivitySubProcess.bpmn2"), ResourceType.BPMN2);
    if (!kbuilder.getErrors().isEmpty()) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
            logger.error("{}", error);
        }
        throw new IllegalArgumentException("Errors while parsing knowledge base");
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession ksession = createKnowledgeSession(kbase);
    
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("x", "oldValue");
    ProcessInstance processInstance = ksession.startProcess("ParentProcess", params);
    assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED);
    assertThat(((WorkflowProcessInstance) processInstance).getVariable("y")).isEqualTo("new value");
}
 
Example #14
Source File: ParallelCompilationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieBase call() throws Exception {
    final Reader source = new InputStreamReader(ParallelCompilationTest.class.getResourceAsStream(DRL_FILE));

    final Properties props = new Properties();
    props.setProperty("drools.dialect.java.compiler", "JANINO");
    props.setProperty("drools.dialect.java.compiler.lnglevel", "1.6");
    KieBase result;

    final KnowledgeBuilderConfiguration configuration = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(props, ParallelCompilationTest.class.getClass().getClassLoader());
    final KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder(configuration);

    Thread.sleep(Math.round(Math.random()*250));

    Resource newReaderResource = ResourceFactory.newReaderResource(source);
    //synchronized (RuleUtil.class)
    {
        builder.add(newReaderResource, ResourceType.DRL);
    }
    result = builder.newKieBase();

    return result;
}
 
Example #15
Source File: AgendaFilterTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetListeners() {
    // JBRULES-3378
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    if (kbuilder.hasErrors()) {
        throw new RuntimeException(kbuilder.getErrors().toString());
    }

    KieSession ksession = kbuilder.newKieBase().newKieSession();

    ksession.getAgendaEventListeners();
    ksession.getProcessEventListeners();
    ksession.getRuleRuntimeEventListeners();

    ksession.dispose();
}
 
Example #16
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieSession genSession(String[] sources, int numerrors)  {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    for (String source : sources)
        kbuilder.add( ResourceFactory.newClassPathResource(source, getClass()), ResourceType.DRL );
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if ( kbuilder.getErrors().size() > 0 ) {
        for ( KnowledgeBuilderError error : kbuilder.getErrors() ) {
            System.err.println( error );
        }
    }
    assertEquals(numerrors, errors.size() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    kbase.addPackages( kbuilder.getKnowledgePackages() );

    return createKnowledgeSession(kbase);

}
 
Example #17
Source File: JBRULESTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testJBRULES3030() {
    final String str = "package org.drools.compiler\n" +
            "rule X\n" +
            "when\n" +
            "    $gp : GrandParent()" +
            "    $ch : ChildHolder( child == $gp )\n" +
            "then\n" +
            "end\n";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    assertFalse(kbuilder.hasErrors());
}
 
Example #18
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddPackageSingle() throws Exception {
    String rule = "package org.drools.compiler.test\n" +
                  "import org.drools.compiler.StockTick\n" +
                  "rule R1 when\n" +
                  "   StockTick()\n" +
                  "then\n" +
                  "end\n";

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

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

    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();
    assertEquals( 2, kpkgs.size() );
    KiePackage kpkg = kpkgs.iterator().next();
    assertEquals( 1, kpkg.getRules().size() );
}
 
Example #19
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatelessKieSession getSession2(final Resource resource) throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( resource, ResourceType.DRL );
    
    if (kbuilder.hasErrors() ) {
        System.out.println( kbuilder.getErrors() );
    }
    
    assertFalse( kbuilder.hasErrors() );
    final Collection<KiePackage> pkgs = kbuilder.getKnowledgePackages();

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    
   
    kbase.addPackages( pkgs );
    kbase    = SerializationHelper.serializeObject( kbase );
    final StatelessKieSession session = kbase.newStatelessKieSession();

    session.setGlobal( "list",
                       this.list );
    session.setGlobal( "cheesery",
                       this.cheesery );
    return session;
}
 
Example #20
Source File: ExecutionFlowControlTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRuleFlowUpgrade() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    // Set the system property so that automatic conversion can happen
    System.setProperty( "drools.ruleflow.port", "true" );

    kbuilder.add( ResourceFactory.newClassPathResource("ruleflow.drl", ExecutionFlowControlTest.class), ResourceType.DRL);
    kbuilder.add( ResourceFactory.newClassPathResource("ruleflow40.rfm", ExecutionFlowControlTest.class), ResourceType.DRF);
    KieBase kbase = kbuilder.newKieBase();
    final KieSession ksession = kbase.newKieSession();
    final List list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.fireAllRules();
    assertEquals(0, list.size());
    final ProcessInstance processInstance = ksession.startProcess("0");
    assertEquals( ProcessInstance.STATE_COMPLETED,
            processInstance.getState() );
    
    assertEquals( 4,
                  list.size() );
    assertEquals( "Rule1",
                  list.get( 0 ) );
    list.subList(1,2).contains( "Rule2" );
    list.subList(1,2).contains( "Rule3" );
    assertEquals( "Rule4",
                  list.get( 3 ) );
    assertEquals( ProcessInstance.STATE_COMPLETED,
                  processInstance.getState() );
    // Reset the system property so that automatic conversion should not happen
    System.setProperty("drools.ruleflow.port", "false");
}
 
Example #21
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclareInheritance() throws Exception {
    String s1 = "package org.drools;\n" +
                "import org.drools.compiler.integrationtests.ExtendsTest.*;\n" +
                "\n" +
                "declare A \n" +
                " @role( event )" +
                " @typesafe( false )\n" +
                "end\n" +
                "" +
                "declare C @role( event ) @typesafe( false ) end \n" +
                "" +
                "rule R \n" +
                "when " +
                "   $x : C( this.x == 1 ) \n" +
                "then\n" +
                "   System.out.println( $x ); \n" +
                "end\n" +
                "";

    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(  );
    kBuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL );
    if ( kBuilder.hasErrors() ) {
        System.err.println( kBuilder.getErrors() );
    }
    assertFalse( kBuilder.hasErrors() );

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

    KieSession knowledgeSession = knowledgeBase.newKieSession();
    FactHandle h = knowledgeSession.insert( new X() );

    assertTrue( ( (InternalFactHandle) h ).isEvent() );

}
 
Example #22
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogicalInsertionsLoop() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_LogicalInsertionsLoop.drl",
                                                        getClass() ),
                  ResourceType.DRL );
    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kpkgs );
    kbase = SerializationHelper.serializeObject(kbase);
    final KieSession session = createKnowledgeSession(kbase);
    try {
        final List l = new ArrayList();
        final Person a = new Person( "a" );
        session.setGlobal( "a",
                           a );
        session.setGlobal( "l",
                           l );

        session.fireAllRules();
        Collection< ? > list = session.getObjects( new ClassObjectFilter( a.getClass() ) );
        assertEquals(0, list.size(), "a still asserted.");
        assertEquals(10, l.size(), "Rule has not fired (looped) expected number of times");
    } finally {
        session.dispose();
    }
}
 
Example #23
Source File: RemoveRuleTest.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 #24
Source File: RuleExtensionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRuleExtendsNonExistingWithCompositeKBuilder() {
    // 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 \"ase\"\n" +
                    "when\n" +
                    "then\n" +
                    "  list.add( 1 );\n" +
                    "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    CompositeKnowledgeBuilder ckb = kbuilder.batch();

    ckb.add( ResourceFactory.newByteArrayResource( str.getBytes() ), ResourceType.DRL )
            .add( ResourceFactory.newByteArrayResource( str2.getBytes() ), ResourceType.DRL )
            .build();

    assertTrue( kbuilder.hasErrors() );
}
 
Example #25
Source File: JavaDialectBinaryEqualityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KiePackage getKnowledgePackage2() {
    
    String str = "";
    str += "package org.drools.compiler.test\n";
    str += "import " + Person.class.getName() + ";\n";
    str += "global java.util.List list\n";
    str += "rule rule1 dialect\"java\" \n";
    str += "when\n";
    str += "   $p : Person( age : age == ( 18 + 18 ), eval( age == 36 ))\n";
    str += "   eval( $p.getAge() == 36 )\n";
    str += "then\n";
    str += "   System.out.println( $p );\n";
    str += "   list.add( $p );\n";
    str += "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<Person> list = new ArrayList<Person>();
    KieSession ksession = kbase.newKieSession();
    ksession.setGlobal( "list", list );
    ksession.insert( new Person("darth", 36) );
    ksession.fireAllRules();
    
    assertEquals( new Person( "darth", 36 ), list.get( 0 ) );

    return kbase.getPackage( "org.drools.compiler.test" );
}
 
Example #26
Source File: JavaDialectBinaryEqualityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KiePackage getKnowledgePackage1() {
  
    String str = "";
    str += "package org.drools.compiler.test\n";
    str += "import " + Person.class.getName() + ";\n";
    str += "global java.util.List list\n";
    str += "rule rule1 dialect\"java\" \n";
    str += "when\n";
    str += "   $p : Person( age : age == ( 17 + 17 ), eval( age == 34 ))\n";
    str += "   eval( $p.getAge() == 34 )\n";
    str += "then\n";
    str += "   list.add( $p );\n";
    str += "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<Person> list = new ArrayList<Person>();
    KieSession ksession = kbase.newKieSession();
    ksession.setGlobal( "list", list );
    ksession.insert( new Person("darth", 34) );
    ksession.fireAllRules();
    
    assertEquals( new Person( "darth", 34 ), list.get( 0 ) );
    
    return kbase.getPackage( "org.drools.compiler.test" );
}
 
Example #27
Source File: RulesDeployer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void deploy(DeploymentEntity deployment, Map<String, Object> deploymentSettings) {
    LOGGER.debug("Processing deployment {}", deployment.getName());

    KnowledgeBuilder knowledgeBuilder = null;

    DeploymentManager deploymentManager = Context
            .getProcessEngineConfiguration()
            .getDeploymentManager();

    Map<String, ResourceEntity> resources = deployment.getResources();
    for (String resourceName : resources.keySet()) {
        LOGGER.info("Processing resource {}", resourceName);
        if (resourceName.endsWith(".drl")) { // is only parsing .drls sufficient? what about other rule dsl's? (@see ResourceType)
            if (knowledgeBuilder == null) {
                knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
            }
            ResourceEntity resourceEntity = resources.get(resourceName);
            byte[] resourceBytes = resourceEntity.getBytes();
            Resource droolsResource = ResourceFactory.newByteArrayResource(resourceBytes);
            knowledgeBuilder.add(droolsResource, ResourceType.DRL);
        }
    }

    if (knowledgeBuilder != null) {
        KieBase knowledgeBase = knowledgeBuilder.newKieBase();
        deploymentManager.getKnowledgeBaseCache().add(deployment.getId(), knowledgeBase);
    }
}
 
Example #28
Source File: CamelSqlTest.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
private KieBase createBase() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource(PROCESS_DEFINITION),
                 ResourceType.BPMN2);
    assertFalse(kbuilder.getErrors().toString(),
                kbuilder.hasErrors());

    return kbuilder.newKieBase();
}
 
Example #29
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPackageImports() {
    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());
    }
    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());

    final KieSession ksession = createKnowledgeSession(kbase);
    final int result = ksession.fireAllRules();
    assertEquals(1, result);
    final Collection<? extends Object> insertedObjects = ksession.getObjects();
    assertEquals(3, insertedObjects.size());
}
 
Example #30
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;
}