org.kie.internal.io.ResourceFactory Java Examples

The following examples show how to use org.kie.internal.io.ResourceFactory. 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: NamedConsequencesTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonCompilingIFAfterOR() {
    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" +
            "    $a: Cheese ( type == \"gorgonzola\" ) )\n" +
            "    if ( price > 10 ) do[t1]\n" +
            "    $b: Cheese ( type == \"cheddar\" )\n" +
            "then\n" +
            "    results.add( $b.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 #3
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSizeCheckInObject() {
    final String str = ""+
    "package org.drools.compiler.test \n" +
    "import " + Triangle.class.getCanonicalName() + "\n" +
    "global java.util.List list \n" +
    "rule \"show\" \n" + 
    "when  \n" + 
    "    $m : Triangle( deliveries.size == 0) \n" + 
    "then \n" + 
    "    list.add('r1'); \n" + 
    "end \n";

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

    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
}
 
Example #4
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void 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 #5
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 #6
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoMvelSyntaxInFunctions() {
    // JBRULES-3433
    final String str = "import java.util.*;\n" +
            "dialect \"mvel\"\n" +
            "function Integer englishToInt(String englishNumber) { \n" +
            "   Map m = [\"one\":1, \"two\":2, \"three\":3, \"four\":4, \"five\":5]; \n" +
            "   Object obj = m.get(englishNumber.toLowerCase()); \n" +
            "   return Integer.parseInt(obj.toString()); \n" +
            "}\n";

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

    assertTrue(kbuilder.hasErrors());
}
 
Example #7
Source File: KnowledgeBuilderImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void addPackageFromScoreCard(final String pmmlString, final String fileName) throws DroolsParserException, IOException  {
    final File dumpDir = this.configuration.getDumpDir();
    if (dumpDir != null) {
        final String dirName = dumpDir.getCanonicalPath().endsWith("/") ? dumpDir.getCanonicalPath() : dumpDir.getCanonicalPath() + "/";
        final String outputPath = dirName + fileName;
        try (final FileOutputStream fos = new FileOutputStream(outputPath)) {
            fos.write(pmmlString.getBytes());
        }
    }
    final Resource res = ResourceFactory.newByteArrayResource(pmmlString.getBytes());

    try {
        ResourceWithConfiguration resCon = new ResourceWithConfigurationImpl(res, null, null, null);
        addPackageForExternalType(ResourceType.PMML, Collections.singletonList(resCon));
    } catch (Exception e) {
        throw new DroolsParserException(e);
    }
}
 
Example #8
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 #9
Source File: UpdateTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void testModifyWithDialect(final String dialect) {
    final String str = "package org.drools.compiler\n" +
            "import java.util.List\n" +
            "rule \"test\"\n" +
            "    dialect \"" + dialect + "\"\n" +
            "when\n" +
            "    $l : List() from collect ( Person( alive == false ) );\n" +
            "then\n" +
            "    for(Object p : $l ) {\n" +
            "        Person p2 = (Person) p;\n" +
            "        modify(p2) { setAlive(true) }\n" +
            "    }\n" +
            "end";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());
}
 
Example #10
Source File: UpdateTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testMissingClosingBraceOnModify() throws Exception {
    // JBRULES-3436
    final String str = "package org.drools.compiler.test;\n" +
            "import org.drools.compiler.*\n" +
            "rule R1 when\n" +
            "   $p : Person( )" +
            "   $c : Cheese( )" +
            "then\n" +
            "   modify($p) { setCheese($c) ;\n" +
            "end\n";

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

    assertTrue(kbuilder.hasErrors());
}
 
Example #11
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 #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: KieBuilderSetImplTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
@Disabled("RHPAM-1184, RHDM-601")
public void testBuildPercentageAndWhiteSpaceInName() throws Exception {
    final KieServices ks = KieServices.Factory.get();
    final KieFileSystem kfs = ks.newKieFileSystem();

    kfs.write("src/main/resources/my rule 100% okay.rdrl",
              ResourceFactory.newInputStreamResource(this.getClass().getResourceAsStream("my rule 100% okay.rdrl")));

    final KieBuilderSetImpl kieBuilderSet = new KieBuilderSetImpl(kieBuilder(ks, kfs));

    kieBuilderSet.setFiles(new String[]{"src/main/resources/my rule 100% okay.rdrl"});

    final IncrementalResults build = kieBuilderSet.build();

    assertEquals(0, build.getAddedMessages().size());
    assertEquals(0, build.getRemovedMessages().size());
}
 
Example #14
Source File: ChangeSetTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomClassLoader() throws Exception {
    // JBRULES-3630
    String absolutePath = new File("file").getAbsolutePath();

    URL url = ChangeSetTest.class.getResource(ChangeSetTest.class.getSimpleName() + ".class");
    AtomicReference<File> jar = new AtomicReference<>();
    assertTimeoutPreemptively(Duration.ofSeconds(10), () -> {
        File file = new File( url.toURI() );
        while ( true ) {
            file = file.getParentFile();
            File j = new File( file, "/src/test/resources/org/drools/compiler/compiler/xml/changeset/changeset.jar" );
            if ( j.exists() ) {
                jar.set(j);
                break;
            }
        }
    }, "JAR not found in time.");

    ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{jar.get().toURI().toURL()}, getClass().getClassLoader());
    Resource changeSet = ResourceFactory.newClassPathResource("changeset1.xml", classLoader);
    KnowledgeBuilderConfiguration conf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, classLoader);
    KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder(conf);
    builder.add(changeSet, ResourceType.CHANGE_SET);
}
 
Example #15
Source File: NamedConsequencesTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutOfScopeNamedConsequencesWithOr2() {
    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( $c.getType() );\n" +
            "end\n";

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

    assertTrue(kbuilder.hasErrors());
}
 
Example #16
Source File: JavaInvokerTest.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
private static KieBase readKnowledgeBase() throws Exception {
    ProcessBuilderFactory.setProcessBuilderFactoryService(new ProcessBuilderFactoryServiceImpl());
    ProcessRuntimeFactory.setProcessRuntimeFactoryService(new ProcessRuntimeFactoryServiceImpl());
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("JavaInvoker.bpmn"),
                 ResourceType.BPMN2);
    kbuilder.add(ResourceFactory.newClassPathResource("JavaInvokerListResult.bpmn"),
                 ResourceType.BPMN2);
    return kbuilder.newKieBase();
}
 
Example #17
Source File: StartEventTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(10)
public void testTimerStartDateISO() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("StartProcess", 1);
    byte[] content = IoUtils.readBytesFromInputStream(this.getClass().getResourceAsStream("/BPMN2-TimerStartDate.bpmn2"));
    String processContent = new String(content, "UTF-8");

    OffsetDateTime plusTwoSeconds = OffsetDateTime.now().plusSeconds(2);

    processContent = processContent.replaceFirst("#\\{date\\}", plusTwoSeconds.toString());
    Resource resource = ResourceFactory.newReaderResource(new StringReader(processContent));
    resource.setSourcePath("/BPMN2-TimerStartDate.bpmn2");
    resource.setTargetPath("/BPMN2-TimerStartDate.bpmn2");
    KieBase kbase = createKnowledgeBaseFromResources(resource);

    ksession = createKnowledgeSession(kbase);
    ksession.addEventListener(countDownListener);
    final List<String> list = new ArrayList<>();
    ksession.addEventListener(new DefaultProcessEventListener() {
        public void beforeProcessStarted(ProcessStartedEvent event) {
            list.add(event.getProcessInstance().getId());
        }
    });
    assertThat(list.size()).isEqualTo(0);
    countDownListener.waitTillCompleted();
    assertThat(list.size()).isEqualTo(1);

}
 
Example #18
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddKPackageSingle() 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();

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

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

    kpkgs = kbuilder.getKnowledgePackages();
    assertEquals( 1, kpkgs.size() );
    kpkg = kpkgs.iterator().next();
    assertEquals( 1, kpkg.getRules().size() );
}
 
Example #19
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(10)
public void testActionNodeIsDroolsAction() throws Exception {
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            .name("ActionNodeActionProcess")
            .version("1")
            .startNode(1)
                .name("Start")
                .done()
            .endNode(3)
                .name("End")
                .done()
            .actionNode(2)
                .name("printTextActionNode")
                .action("java",
                        "System.out.println(\"test print\");",
                        true)
                .done()
            .connection(1, 2)
            .connection(2, 3);
    RuleFlowProcess process = factory.validate().getProcess();

    assertNotNull(process);

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2");
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    ProcessInstance pi = ksession.startProcess("org.jbpm.process");

    assertNotNull(pi);

    assertEquals(ProcessInstance.STATE_COMPLETED,
                 pi.getState());

    ksession.dispose();
}
 
Example #20
Source File: SecurityPolicyTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testUntrustedMVELSalience() throws Exception {
    String drl = "package org.foo.bar\n" +
            "import "+MaliciousExitHelper.class.getName().replace('$', '.')+" \n" +
            "rule R1 dialect \"mvel\" salience( MaliciousExitHelper.exit() ) \n" +
            "when\n" +
            "then\n" +
            "end\n";

    try {
        KieServices ks = KieServices.Factory.get();
        KieFileSystem kfs = ks.newKieFileSystem().write(ResourceFactory.newByteArrayResource(drl.getBytes())
                .setSourcePath("org/foo/bar/r1.drl"));
        ks.newKieBuilder(kfs).buildAll();

        ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
        KieContainer kc = ks.newKieContainer(releaseId);

        KieSession ksession = kc.newKieSession();
        ksession.fireAllRules();
        fail("The security policy for the rule should have prevented this from executing...");
    } catch (PropertyAccessException e) {
        // weak way of testing but couldn't find a better way
        if( e.toString().contains( "The security policy should have prevented" ) ) {
            fail("The security policy for the rule should have prevented this from executing...");
        } else {
            // test succeeded
        }
    }
}
 
Example #21
Source File: StrEvaluatorTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBase readKnowledgeBase() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newInputStreamResource(getClass().getResourceAsStream("strevaluator_test.drl")),
            ResourceType.DRL );
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (errors.size() > 0) {
        for (KnowledgeBuilderError error: errors) {
            System.err.println(error);
        }
        throw new IllegalArgumentException("Could not parse knowledge." + errors.toArray());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    return kbase;
}
 
Example #22
Source File: TypeDeclarationMergingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotOverwritePOJOMetadata() {
    final String eventClassName = PositionAnnotatedEvent.class.getCanonicalName();
    // should add metadata to metadata already defined in POJO
    String str =
            "package org.drools.compiler.test \n" +
            "declare " + eventClassName + "\n" +
            " @role(event)\n" +
            "end \n" +
            "rule 'sample rule' \n" +
            "when \n" +
            " " + eventClassName + "( 'value1', 'value2'; ) \n" +
            "then \n" +
            "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    try {
        kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
                ResourceType.DRL );
    } catch (IndexOutOfBoundsException e) {
        final String msg = e.getMessage();
        if ( "Error trying to access field at position 0".equals( msg ) ) {
            fail( "@Position declared in POJO was ignored." );
        } else {
            fail( "Check the test, unexpected error message: " + msg );
        }
    }
    assertFalse(kbuilder.hasErrors(),  "Check the test, unexpected error message: " + kbuilder.getErrors());
}
 
Example #23
Source File: WorkingMemoryActionsSerializationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void before() {
    ruleCalls.clear();

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase( );
    kbase.addPackages( kbuilder.getKnowledgePackages() );

    ksession = kbase.newKieSession();

    ksession.addEventListener(new DefaultAgendaEventListener() {
        @Override
        public void afterMatchFired(final AfterMatchFiredEvent event) {
            final String name = event.getMatch().getRule().getName();
            System.out.println(name + " fired!");
            synchronized (ruleCalls) {
                Integer calls = ruleCalls.get(name);
                if (calls == null) {
                    calls = 1;
                } else {
                    calls++;
                }
                ruleCalls.put(name, calls);
            }
        }
    });

    // Using fire until halt. If firaAllRules is called it works. But for other reasons, I need to run fireUntilHalt

    new Thread(ksession::fireUntilHalt).start();

}
 
Example #24
Source File: SimpleBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void createKSession() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(ruleString.getBytes()), ResourceType.DRL );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    assertFalse( kbuilder.hasErrors() );
    kbase.addPackages( kbuilder.getKnowledgePackages() );

    ksession = createKnowledgeSession(kbase);
}
 
Example #25
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessFactory() throws Exception {
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .actionNode(2)
                .name("Action")
                .action("java",
                        "System.out.println(\"Action\");")
                .done()
            .endNode(3)
                .name("End")
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3);
    RuleFlowProcess process = factory.validate().getProcess();
    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    ksession.startProcess("org.jbpm.process");
    ksession.dispose();
}
 
Example #26
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * 2 resources (containing different declarations of the same type ) are added
 * to the kbuilder.
 * The expectation here is that the compilation fails because we are
 * trying to add an incompatible re-definition of the declared type:
 * it introduces a new field 'lastName'
 */
@Test
public void testTypeReDeclarationWithExtraField2() {
    //same package, different resources
    String str1 = "";
    str1 += "package org.drools.compiler \n" +
    		"declare org.drools.ClassA \n" +
    		"    name : String \n" +
    		"    age : Integer \n" +
    		"end \n";

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

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

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

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

}
 
Example #27
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 #28
Source File: FireAllRulesCommandTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatelessKieSession getSession(String drl) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

    if (kbuilder.hasErrors()) {
        System.err.println(kbuilder.getErrors());
    }
    assertFalse(kbuilder.hasErrors());

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

    return kbase.newStatelessKieSession();
}
 
Example #29
Source File: PropertySpecificTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDuplicatePropertyNamesInWatchAnnotation() throws Exception {
    String rule = "package org.drools.compiler.integrationtests\n" +
            "dialect \"mvel\"\n" +
            "declare A\n" +
            "    s : String\n" +
            "end\n" +
            "declare B\n" +
            "    @propertyReactive\n" +
            "    on : boolean\n" +
            "    s : String\n" +
            "end\n" +
            "rule R1\n" +
            "when\n" +
            "    A($s : s)\n" +
            "    $b : B(s != $s) @watch( s, !s )\n" +
            "then\n" +
            "    modify($b) { setS($s) }\n" +
            "end\n" +
            "rule R2\n" +
            "when\n" +
            "    $b : B(on == false)\n" +
            "then\n" +
            "    modify($b) { setOn(true) }\n" +
            "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL );
    assertEquals(1, kbuilder.getErrors().size());
}
 
Example #30
Source File: Query3Test.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * @throws java.lang.Exception
 */
@BeforeEach
public void setUp() throws Exception {
    String text = "";
    text += "package org.drools.integrationtests\n";
    text += "import " + Query3Test.Bar.class.getCanonicalName() + "\n";
    text += "import " + Query3Test.Foo.class.getCanonicalName() + "\n";
    text += "import " + Query3Test.Foo2.class.getCanonicalName() + "\n";
    text += "query \"testDifferent\"\n";
    text += "    foo : Foo();\n";
    text += "    bar : Bar(id == foo.id)\n";
    text += "end\n";
    text += "query \"testSame\"\n";
    text += "    foo : Foo();\n";
    text += "    foo2 : Foo(id == foo.id);\n";
    text += "end\n";
    text += "query \"testExtends\"\n";
    text += "    foo : Foo();\n";
    text += "    foo2 : Foo2(id == foo.id);\n";
    text += "end\n";

    KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    knowledgeBuilder.add( ResourceFactory.newByteArrayResource(text.getBytes()),
                          ResourceType.DRL );
    assertFalse( knowledgeBuilder.hasErrors() );
    knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
    knowledgeBase.addPackages( knowledgeBuilder.getKnowledgePackages() );
}