Java Code Examples for org.kie.api.runtime.KieContainer#newKieSession()

The following examples show how to use org.kie.api.runtime.KieContainer#newKieSession() . 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: HrMaxQuizService.java    From qzr with Apache License 2.0 6 votes vote down vote up
@Autowired
public HrMaxQuizService(KieContainer kieContainer, SimpMessagingTemplate template) {
    
    log.info("Initialising a new quiz session.");
    
    this.kieSession = kieContainer.newKieSession("HrmaxSession");
    
    this.agendaEventPublisher = new PublishingAgendaEventListener(template);
    this.agendaEventListener = new LoggingAgendaEventListener();
    this.ruleRuntimeEventListener = new LoggingRuleRuntimeEventListener();

    this.kieSession.addEventListener(agendaEventPublisher);
    this.kieSession.addEventListener(agendaEventListener);
    this.kieSession.addEventListener(ruleRuntimeEventListener);
    
    this.kieSession.fireAllRules();
}
 
Example 2
Source File: WireListenerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testWireListener() throws Exception {
    KieServices ks = KieServices.Factory.get();

    ReleaseId releaseId = ks.newReleaseId("org.kie", "listener-test", "1.0");
    build(ks, releaseId);
    KieContainer kieContainer = ks.newKieContainer(releaseId);

    KieSession ksession = kieContainer.newKieSession();
    ksession.fireAllRules();

    assertEquals(1, insertEvents.size());
    assertEquals(1, updateEvents.size());
    assertEquals(1, retractEvents.size());
}
 
Example 3
Source File: WireChannelTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testWireChannel() throws Exception {
    KieServices ks = KieServices.Factory.get();

    ReleaseId releaseId = ks.newReleaseId("org.kie", "listener-test", "1.0");
    build(ks, releaseId);
    KieContainer kieContainer = ks.newKieContainer(releaseId);

    KieSession ksession = kieContainer.newKieSession();
    ksession.fireAllRules();
    
    assertEquals(1, channelMessages.size());
    assertEquals("Test Message", channelMessages.get(0));
}
 
Example 4
Source File: MemoryLeakTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
@Disabled("The checkReachability method is not totally reliable and can fall in an endless loop." +
        "We need to find a better way to check this.")
public void testLeakAfterSessionDispose() {
    // DROOLS-1655
    String drl =
            "import " + Person.class.getCanonicalName() + "\n" +
            "rule R when\n" +
            "    $p : Person()\n" +
            "then\n" +
            "end\n";

    KieContainer kContainer = new KieHelper().addContent( drl, ResourceType.DRL ).getKieContainer();
    KieSession ksession = kContainer.newKieSession();
    KieBase kBase = ksession.getKieBase();

    ksession.insert( new Person("Mario", 40) );
    ksession.fireAllRules();

    checkReachability( ksession, Person.class::isInstance, true );
    checkReachability( kBase, ksession::equals, true );
    checkReachability( kContainer, ksession::equals, true );

    ksession.dispose();

    checkReachability( kContainer, Person.class::isInstance, false );
    checkReachability( kBase, ksession::equals, false );
    checkReachability( kContainer, ksession::equals, false );
}
 
Example 5
Source File: DemoTest.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void test1() throws Exception{
    //通过此URL可以访问到maven仓库中的jar包
    //URL地址构成:http://ip地址:Tomcat端口号/WorkBench工程名/maven2/坐标/版本号/xxx.jar
    String url =
            "http://122.**.**.48:8080/drools-wb/maven2/com/fwcloud/fwcloud-demo1/1.0.1/fwcloud-demo1-1.0.1.jar";

    KieServices kieServices = KieServices.Factory.get();

    //通过Resource资源对象加载jar包
    UrlResource resource = (UrlResource) kieServices.getResources().newUrlResource(url);
    //通过Workbench提供的服务来访问maven仓库中的jar包资源,需要先进行Workbench的认证
    resource.setUsername("admin");
    resource.setPassword("admin");
    resource.setBasicAuthentication("enabled");

    //将资源转换为输入流,通过此输入流可以读取jar包数据
    InputStream inputStream = resource.getInputStream();

    //创建仓库对象,仓库对象中保存Drools的规则信息
    KieRepository repository = kieServices.getRepository();

    //通过输入流读取maven仓库中的jar包数据,包装成KieModule模块添加到仓库中
    KieModule kieModule =
            repository.
                    addKieModule(kieServices.getResources().newInputStreamResource(inputStream));

    //基于KieModule模块创建容器对象,从容器中可以获取session会话
    KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
    KieSession session = kieContainer.newKieSession();

    Person person = new Person();
    person.setAge(10);
    session.insert(person);

    session.fireAllRules();
    session.dispose();
}
 
Example 6
Source File: KieLoggersTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclarativeKieConsoleLogger() throws Exception {
    String drl = "package org.drools.integrationtests\n" +
                 "import org.drools.compiler.Message;\n" +
                 "rule \"Hello World\"\n" +
                 "    when\n" +
                 "        m : Message( myMessage : message )\n" +
                 "    then\n" +
                 "end";

    KieServices ks = KieServices.Factory.get();
    KieModuleModel kproj = ks.newKieModuleModel();

    kproj.newKieBaseModel("KBase1").newKieSessionModel("KSession1").setConsoleLogger("logger");

    KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML(kproj.toXML());
    kfs.write("src/main/resources/KBase1/rule.drl", drl);

    KieModule kieModule = ks.newKieBuilder(kfs).buildAll().getKieModule();
    KieContainer kieContainer = ks.newKieContainer(kieModule.getReleaseId());

    KieSession ksession = kieContainer.newKieSession("KSession1");
    ksession.insert( new Message("Hello World") );
    int fired = ksession.fireAllRules();
    assertEquals(1, fired);

    KieRuntimeLogger logger = ksession.getLogger();
    assertNotNull(logger);
    logger.close();
}
 
Example 7
Source File: SeveralKieSessionsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Tests evaluation of a backward chaining family relationships example with
 * two KieSessions created from the same KieBase.
 *
 * KieSessions are constructed using different KieContainer instances.
 */
@Test
public void testFamilyWithTwoKieSessionsFromKieContainer() throws Exception {
    final KieServices ks = KieServices.Factory.get();

    final KieContainer kieContainer = ks.newKieContainer(kieModuleId);
    final KieSession ksession = kieContainer.newKieSession();
    performTestAndDispose(ksession);

    final KieContainer kieContainerOther = ks.newKieContainer(kieModuleId);
    final KieSession ksessionOther = kieContainerOther.newKieSession();
    performTestAndDispose(ksessionOther);
}
 
Example 8
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclarativeChannelRegistration() {
    final String drl1 = "package org.drools.compiler\n" +
            "rule R1 when\n" +
            "   $m : Message()\n" +
            "then\n" +
            "end\n";

    final String kmodule = "<kmodule xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
            "         xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
            "  <kbase name=\"kbase1\">\n" +
            "    <ksession name=\"ksession1\" default=\"true\">\n" +
            "       <channels>\n" +
            "         <channel name=\"testChannel\" type=\"org.drools.compiler.integrationtests.KieBuilderTest$MockChannel\" />\n" +
            "       </channels>\n" +
            "    </ksession>" +
            "  </kbase>\n" +
            "</kmodule>";

    final KieServices ks = KieServices.Factory.get();

    final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" );
    final Resource r1 = ResourceFactory.newByteArrayResource( drl1.getBytes() ).setResourceType( ResourceType.DRL ).setSourcePath( "kbase1/drl1.drl" );
    final KieModule km = createAndDeployJar( ks,
                                       kmodule,
                                       releaseId1,
                                       r1);

    KieContainer kieContainer = ks.newKieContainer( km.getReleaseId());
    
    KieSession kieSession = kieContainer.newKieSession();
    assertEquals(1, kieSession.getChannels().size());
    assertTrue(kieSession.getChannels().keySet().contains("testChannel"));
}
 
Example 9
Source File: SecurityPolicyTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testUntrustedMVELEnabled() throws Exception {
    String drl = "package org.foo.bar\n" +
            "import "+MaliciousExitHelper.class.getName().replace('$', '.')+" \n" +
            "rule R1 dialect \"mvel\" enabled( MaliciousExitHelper.isEnabled() ) \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 10
Source File: KieFileSystemScannerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoNotUpgradeOnOlderVersion() throws Exception {
    Path tempDir = Files.createTempDirectory(FileSystems.getDefault().getPath("./target"), null);
    File file2 = null;

    try {
        KieServices ks = KieServices.Factory.get();
        ReleaseId releaseIdNew = ks.newReleaseId( "org.kie", "scanner-test", "1.1.0" );
        ReleaseId releaseIdOld = ks.newReleaseId( "org.kie", "scanner-test", "1.0.0" );

        createKieJar( ks, releaseIdNew, "R1" );

        KieContainer kieContainer = ks.newKieContainer( releaseIdNew );

        KieSession ksession = kieContainer.newKieSession();
        checkKSession( ksession, "R1" );

        KieScanner scanner = ks.newKieScanner( kieContainer, tempDir.toString() );

        file2 = write( createKieJar( ks, releaseIdOld, "R2" ), tempDir, releaseIdOld );
        scanner.scanNow();
        ksession = kieContainer.newKieSession();
        checkKSession( ksession, "R1" );
    } finally {
        if (file2 != null) {
            file2.delete();
        }
        Files.delete(tempDir);
    }
}
 
Example 11
Source File: DroolsBeanFactory.java    From tutorials with MIT License 4 votes vote down vote up
public KieSession getKieSession(Resource dt) {
    KieFileSystem kieFileSystem = kieServices.newKieFileSystem()
        .write(dt);

    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem)
        .buildAll();

    KieRepository kieRepository = kieServices.getRepository();

    ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId();

    KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId);

    KieSession ksession = kieContainer.newKieSession();

    return ksession;
}
 
Example 12
Source File: GroupingTest.java    From phreak-examples with Apache License 2.0 4 votes vote down vote up
@Before
public void initSession() {
    final KieContainer kcontainer = KieServices.Factory.get().getKieClasspathContainer();
    this.ksession = kcontainer.newKieSession("groupingKSession");
}
 
Example 13
Source File: DroolsBeanFactory.java    From tutorials with MIT License 4 votes vote down vote up
public KieSession getKieSession(){
    getKieRepository();
    KieFileSystem kieFileSystem = kieServices.newKieFileSystem();

    kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/BackwardChaining.drl"));
    kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl"));
    kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.xls"));
    
    
    KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
    kb.buildAll();
    KieModule kieModule = kb.getKieModule();

    KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId());

    return kContainer.newKieSession();

}
 
Example 14
Source File: KieContainerTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSharedTypeDeclarationsUsingFactTypes() throws Exception {
    String type = "package org.drools.test\n" +
                  "declare Message\n" +
                  "   message : String\n" +
                  "end\n";

    String drl1 = "package org.drools.test\n" +
                  "rule R1 when\n" +
                  "   $m : Message()\n" +
                  "then\n" +
                  "   if ($m.getClass() != new Message(\"Test\").getClass()) {\n" +
                  "       throw new RuntimeException();\n" +
                  "   }\n" +
                  "end\n";

    String drl2 = "package org.drools.test\n" +
                  "rule R2_2 when\n" +
                  "   $m : Message( message == \"Hello World\" )\n" +
                  "then\n" +
                  "   if ($m.getClass() != new Message(\"Test\").getClass()) {\n" +
                  "       throw new RuntimeException();\n" +
                  "   }\n" +
                  "end\n";

    KieServices ks = KieServices.Factory.get();
    // Create an in-memory jar for version 1.0.0
    ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
    createAndDeployJar( ks, releaseId1, type, drl1, drl2 );

    KieContainer kieContainer = ks.newKieContainer(releaseId1);
    KieContainer kieContainer2 = ks.newKieContainer(releaseId1);

    KieSession ksession = kieContainer.newKieSession();
    KieSession ksession2 = kieContainer2.newKieSession();

    insertMessageFromTypeDeclaration( ksession );
    assertEquals( 2, ksession.fireAllRules() );

    ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-delete", "1.0.1");
    createAndDeployJar( ks, releaseId2, type, null, drl2 );

    kieContainer.updateToVersion(releaseId2);

    // test with the old ksession ...
    ksession = kieContainer.newKieSession();
    insertMessageFromTypeDeclaration( ksession );
    assertEquals( 1, ksession.fireAllRules() );

    // ... and with a brand new one
    ksession = kieContainer.newKieSession();
    insertMessageFromTypeDeclaration (ksession );
    assertEquals( 1, ksession.fireAllRules() );

    // check that the second kieContainer hasn't been affected by the update of the first one
    insertMessageFromTypeDeclaration( ksession2 );
    assertEquals( 2, ksession2.fireAllRules() );

    ksession2 = kieContainer2.newKieSession();
    insertMessageFromTypeDeclaration( ksession2 );
    assertEquals( 2, ksession2.fireAllRules() );
}
 
Example 15
Source File: TestKieSessionUpdate.java    From hacep with Apache License 2.0 4 votes vote down vote up
@Test
public void testContainerUpdate() throws IOException, URISyntaxException {
    ArrayList<Object> globalList = new ArrayList<>();

    KieServices ks = KieServices.Factory.get();

    ReleaseIdImpl releaseIdV1 = new ReleaseIdImpl("it.redhat.test.update", "rules", "1.0.0");
    KieContainer kieContainer = KieAPITestUtils.setupKieContainerFromTemplates(releaseIdV1, "rules/globals-v1-rule.drl");

    KieSession kieSession = kieContainer.newKieSession();
    kieSession.setGlobal("list", globalList);

    Assert.assertEquals(0, globalList.size());

    kieSession.insert(1L);
    kieSession.fireAllRules();

    Assert.assertEquals(1, globalList.size());
    Assert.assertEquals(1L, globalList.get(0));

    kieSession.insert(2L);
    kieSession.fireAllRules();

    Assert.assertEquals(2, globalList.size());
    Assert.assertEquals(1L, globalList.get(0));
    Assert.assertEquals(3L, globalList.get(1));

    ReleaseIdImpl releaseIdV2 = new ReleaseIdImpl("it.redhat.test.update", "rules", "2.0.0");
    KieAPITestUtils.buildReleaseFromTemplates(releaseIdV2, "rules/globals-v2-rule.drl");

    kieContainer.updateToVersion(releaseIdV2);
    kieSession.insert(4L);
    kieSession.fireAllRules();

    Assert.assertEquals(3, globalList.size());
    Assert.assertEquals(1L, globalList.get(0));
    Assert.assertEquals(3L, globalList.get(1));
    Assert.assertEquals(14L, globalList.get(2));

    kieSession.dispose();
}
 
Example 16
Source File: ModificationTest.java    From phreak-examples with Apache License 2.0 4 votes vote down vote up
@Before
public void initSession() {
    final KieContainer kcontainer = KieServices.Factory.get().getKieClasspathContainer();
    this.ksession = kcontainer.newKieSession("modificationKSession");
}
 
Example 17
Source File: Laziness3Test.java    From phreak-examples with Apache License 2.0 4 votes vote down vote up
@Before
public void initSession() {
    final KieContainer kcontainer = KieServices.Factory.get().getKieClasspathContainer();
    this.ksession = kcontainer.newKieSession("laziness3KSession");
}
 
Example 18
Source File: TestKieSessionUpdate.java    From hacep with Apache License 2.0 4 votes vote down vote up
@Test
public void testContainerUpdateAfterSerialization() throws IOException, URISyntaxException {
    ArrayList<Object> globalList = new ArrayList<>();

    KieServices ks = KieServices.Factory.get();

    ReleaseIdImpl releaseIdV1 = new ReleaseIdImpl("it.redhat.test.serialized", "rules", "1.0.0");
    KieContainer kieContainer = KieAPITestUtils.setupKieContainerFromTemplates(releaseIdV1, "rules/globals-v1-rule.drl");

    KieSession kieSession = kieContainer.newKieSession();
    kieSession.setGlobal("list", globalList);

    Assert.assertEquals(0, globalList.size());

    kieSession.insert(1L);
    kieSession.fireAllRules();

    Assert.assertEquals(1, globalList.size());
    Assert.assertEquals(1L, globalList.get(0));

    kieSession.insert(2L);
    kieSession.fireAllRules();

    Assert.assertEquals(2, globalList.size());
    Assert.assertEquals(1L, globalList.get(0));
    Assert.assertEquals(3L, globalList.get(1));

    KieSessionByteArraySerializer serializer = new KieSessionByteArraySerializer();
    byte[] buffer = serializer.writeObject(createSerializableMarshaller(kieContainer.getKieBase()), kieSession);
    kieSession.dispose();

    ReleaseIdImpl releaseIdV2 = new ReleaseIdImpl("it.redhat.test.serialized", "rules", "2.0.0");
    KieAPITestUtils.buildReleaseFromTemplates(releaseIdV2, "rules/globals-v2-rule.drl");

    kieContainer.updateToVersion(releaseIdV2);

    KieSession serializedSession = serializer.readSession(createSerializableMarshaller(kieContainer.getKieBase()), buffer);
    serializedSession.setGlobal("list", globalList);

    serializedSession.insert(4L);
    serializedSession.fireAllRules();

    Assert.assertEquals(3, globalList.size());
    Assert.assertEquals(1L, globalList.get(0));
    Assert.assertEquals(3L, globalList.get(1));
    Assert.assertEquals(14L, globalList.get(2));
}
 
Example 19
Source File: KnowledgeSessionHelper.java    From droolscourse with Apache License 2.0 2 votes vote down vote up
public static KieSession getStatefulKnowledgeSession(KieContainer kieContainer, String sessionName) {
  
	KieSession kSession = kieContainer.newKieSession(sessionName);
 
	return kSession;
}
 
Example 20
Source File: KnowledgeSessionHelper.java    From droolscourse with Apache License 2.0 2 votes vote down vote up
public static KieSession getStatefulKnowledgeSession(KieContainer kieContainer, String sessionName) {

        KieSession kSession = kieContainer.newKieSession(sessionName);

        return kSession;
    }