org.kie.internal.builder.KnowledgeBuilderFactory Java Examples

The following examples show how to use org.kie.internal.builder.KnowledgeBuilderFactory. 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 testAccumulateWithPR() {

    String drl = "declare A end\n" +
                 " " +
                 "declare B\n" +
                 " value : String\n" +
                 "end\n" +
                 " " +
                 "rule Foo when\n" +
                 "    $s : A()\n" +
                 "    accumulate( String()\n" +
                 "                and\n" +
                 "                B( $val : value ),\n" +
                 "                $set : collectSet( $val )\n" +
                 "              )\n" +
                 "then end\n";

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

    assertTrue( kbuilder.getErrors().isEmpty() );
}
 
Example #3
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 #4
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public Collection<KiePackage> loadKnowledgePackages( KnowledgeBuilderConfiguration kbuilderConf, boolean serialize, String... classPathResources) {
    if (kbuilderConf == null) {
        kbuilderConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();
    }

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(kbuilderConf);
    for (String classPathResource : classPathResources) {
        kbuilder.add(ResourceFactory.newClassPathResource(classPathResource, getClass()), ResourceType.DRL);
    }

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

    Collection<KiePackage> knowledgePackages = null;
    if ( serialize ) {
        try {
            knowledgePackages = SerializationHelper.serializeObject(kbuilder.getKnowledgePackages(),  ((KnowledgeBuilderConfigurationImpl)kbuilderConf).getClassLoader() );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        knowledgePackages = kbuilder.getKnowledgePackages();
    }
    return knowledgePackages;
}
 
Example #5
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 #6
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 #7
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 #8
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSession( String ruleFile ) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    try {
        System.setProperty("drools.negatable", "on");
        kBuilder.add(ResourceFactory.newClassPathResource(ruleFile),
                     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.DEFEASIBLE );

    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #9
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 #10
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 #11
Source File: SegmentMemoryPrototypeTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSessionCache() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(DRL.getBytes()),
                  ResourceType.DRL );

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

    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kbase.newKieSession();
    try {
        checkKieSession(ksession);
    } finally {
        try {
            ksession.reset();
            checkKieSession(ksession);
        } finally {
            ksession.dispose();
        }
    }
}
 
Example #12
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 #13
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 #14
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddKPackageCollection() throws Exception {
    String rule = "package org.drools.compiler.test\n" +
                  "import org.drools.compiler.StockTick\n" +
                  "declare StockTick @role(event) end\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() );

    byte[] skpkg = DroolsStreamUtils.streamOut( kpkgs );

    kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( skpkg ), ResourceType.PKG );
    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

    kpkgs = kbuilder.getKnowledgePackages();
    assertEquals( 2, kpkgs.size() );
}
 
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: FunctionsTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testFunctionCallingFunctionWithEclipse() throws Exception {
    KnowledgeBuilderConfiguration kbconf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();
    kbconf.setProperty( "drools.dialect.java.compiler", "ECLIPSE" );
    KieBase kbase = loadKnowledgeBase( kbconf, "test_functionCallingFunction.drl" );
    KieSession ksession = createKnowledgeSession(kbase);

    final List<Integer> list = new ArrayList<Integer>();
    ksession.setGlobal( "results",
                        list );

    ksession.fireAllRules();

    assertEquals( 1,
                  list.size() );

    assertEquals( 12,
                  list.get( 0 ).intValue() );
}
 
Example #17
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypeReDeclarationPojo() {
    String str1 = "" +
                  "package org.drools \n" +
                  "import " + TypeDeclarationTest.class.getName() + ".ClassC; \n" +
                  "" +
                  "declare " + TypeDeclarationTest.class.getName() + ".ClassC \n" +
                  "    name : String \n" +
                  "    age : Integer \n" +
                  "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add( ResourceFactory.newByteArrayResource( str1.getBytes() ),
                  ResourceType.DRL );
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
}
 
Example #18
Source File: RuleExtensionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleExtendsNonexistingRule() {
    // 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" +
                    "\n" +
                    "rule \"ExtYes\" extends \"Bas\"\n" +
                    "when\n" +
                    "then\n" +
                    "  list.add( 1 );\n" +
                    "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL );
    assertTrue( kbuilder.hasErrors() );
    kbuilder.getErrors().iterator().next().toString().contains("Base");
}
 
Example #19
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDuplicateDeclaration() {
    String str = "";
    str += "package org.drools.compiler \n" +
            "declare Bean \n" +
            "    name : String \n" +
            "end \n" +
            "declare Bean \n" +
            "    age : int \n" +
            "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

    if ( ! kbuilder.hasErrors() ) {
        fail( "Two definitions with the same name are not allowed, but it was not detected! " );
    }
}
 
Example #20
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 #21
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
/**
 * The same resource (containing a type declaration) is added twice in the
 * kbuilder.
 */
@Test
public void testDuplicatedTypeDeclarationWith2FieldsInSameResource() {
    //same package, different resources
    String str1 = "";
    str1 += "package org.drools.compiler \n" +
    		"declare org.drools.ClassA \n" +
    		"    name : String \n" +
    		"    lastName : String \n" +
    		"end \n";

    Resource resource = ResourceFactory.newByteArrayResource( str1.getBytes());

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add( resource, ResourceType.DRL );

    kbuilder.add( resource, ResourceType.DRL );

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

}
 
Example #22
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 #23
Source File: SerializedPackageMergeTwoSteps1Test.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildAndSerializePackagesInTwoSteps1() {
	String str1 =
			"package com.sample.packageA\n" +
					"import org.drools.compiler.Person\n" +
					"global java.util.List list\n" +
					"rule R1 when\n" +
					"  $p : Person( name == \"John\" )\n" +
					"then\n" +
					"  list.add($p);" +
					"end\n";

	String str2 =
			"package com.sample.packageB\n" +
					"import org.drools.compiler.Person\n" +
					"global java.util.List list\n" +
					"rule R2 when\n" +
					"  $p : Person()\n" +
					"then\n" +
					"  list.add($p);" +
					"end\n";

	// Create 2 knowledgePackages separately
	KnowledgeBuilder builder1 = KnowledgeBuilderFactory.newKnowledgeBuilder();
	builder1.add( ResourceFactory.newByteArrayResource( str1.getBytes() ), ResourceType.DRL );
	Collection<KiePackage> knowledgePackages1 = builder1.getKnowledgePackages();

	// serialize the first package to a file
	writeKnowledgePackage(knowledgePackages1, BINPKG[0]);

	KnowledgeBuilder builder2 = KnowledgeBuilderFactory.newKnowledgeBuilder();
	builder2.add( ResourceFactory.newByteArrayResource( str2.getBytes() ), ResourceType.DRL );
	Collection<KiePackage> knowledgePackages2 = builder2.getKnowledgePackages();

	// serialize the second package to a file
	writeKnowledgePackage(knowledgePackages2, BINPKG[1]);               
}
 
Example #24
Source File: DslTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithExpanderDSL() throws Exception {
    //final PackageBuilder builder = new PackageBuilder();
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add( ResourceFactory.newClassPathResource( "test_expander.dsl", getClass() ),
                          ResourceType.DSL );
    kbuilder.add(ResourceFactory.newClassPathResource("rule_with_expander_dsl.dslr", getClass()),
            ResourceType.DSLR);

    checkDSLExpanderTest(kbuilder);
}
 
Example #25
Source File: HelloWorldTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBase readKnowledgeBase() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("Sample.drl", HelloWorldTest.class),
        ResourceType.DRL);
    if (kbuilder.hasErrors()) {
       fail( kbuilder.getErrors().toString() );
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    return kbase;
}
 
Example #26
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 #27
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 #28
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 #29
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test @Disabled("Fails because of JBRULES-3435. But the JBRULES-2853 part works fine. Support for i18n properties must be fixed in mvel")
public void readDrlInEncodingUtf8() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_I18nPerson_utf8.drl", "UTF-8", 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");
    i18nPerson.setИмя("Value 3");
    i18nPerson.set名称("Value 4");
    ksession.insert(i18nPerson);
    ksession.fireAllRules();

    assertTrue(list.contains("garçon"));
    assertTrue(list.contains("élève"));
    assertTrue(list.contains("имя"));
    assertTrue(list.contains("名称"));
    ksession.dispose();
}
 
Example #30
Source File: KieService.java    From Liudao with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 规则集上线
 *
 * @param packageName
 */
public void addPackage(String packageName) {
    try {
        File path = new File(this.getClass().getClassLoader().getResource(packageName).toURI().getPath());
        if (path.isDirectory()) {
            KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
            File[] files = path.listFiles();
            for (File file : files) {
                if (file.getName().endsWith(".drl")) {
                    kbuilder.add(ResourceFactory.newClassPathResource(packageName + "/" + file.getName()), ResourceType.DRL);
                    if (kbuilder.hasErrors()) {
                        logger.error("Unable to compile drl. " + packageName + file.getName());
                        return;
                    } else {
                        String ruleName = file.getName().replace(".drl", "");
                        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();
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}