org.kie.api.runtime.KieContainer Java Examples

The following examples show how to use org.kie.api.runtime.KieContainer. 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: DroolsUtils.java    From spring-boot-start-current with Apache License 2.0 6 votes vote down vote up
private static KieContainer buildKieContainer ( List< String > ruleContents ) {
    // 获取的各种对象来完成规则构建、管理和执行等操作
    KieServices kieServices = KieServices.Factory.get();
    // 用于以编程方式定义组成KieModule的资源
    KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
    for ( String ruleContent : ruleContents ) {
        kieFileSystem.write( "src/main/resources/" + System.currentTimeMillis() + ".drl" , ruleContent );
    }
    // KieBuilder是KieModule中包含的资源的构建者
    KieBuilder kieBuilder = kieServices.newKieBuilder( kieFileSystem ).buildAll();

    // 如果有错误
    if ( kieBuilder.getResults().hasMessages() ) {
        LogUtils.getLogger().warn( kieBuilder.getResults().getMessages() );
        if ( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) ) {
            throw new RuntimeException( kieBuilder.getResults()
                                                  .getMessages()
                                                  .parallelStream()
                                                  .map( Message::getText ).collect( Collectors.joining( "," ) )
            );
        }
    }
    // 用来访问KBase和KSession等信息
    return kieServices.newKieContainer( kieServices.getRepository().getDefaultReleaseId() );
}
 
Example #2
Source File: DroolsAutoConfiguration.java    From spring-boot-starter-drools with MIT License 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(KieContainer.class)
public KieContainer kieContainer() throws IOException {
    final KieRepository kieRepository = getKieServices().getRepository();
    
    kieRepository.addKieModule(new KieModule() {
        public ReleaseId getReleaseId() {
            return kieRepository.getDefaultReleaseId();
        }
    });
    
    KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem()); 
    kieBuilder.buildAll();
    
    return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
}
 
Example #3
Source File: KieHelloWorldTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testClassLoaderStore() throws Exception {
    // DROOLS-1766
    String drl = "package org; declare Person name : String end";
    KieServices ks = KieServices.Factory.get();

    KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
    ks.newKieBuilder( kfs ).buildAll();

    KieContainer kcontainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId());

    KieProject kieProject = (( KieContainerImpl ) kcontainer).getKieProject();
    ResultsImpl messages = kieProject.verify();

    assertSame( kieProject.getClassLoader(), kcontainer.getClassLoader() );

    ProjectClassLoader pcl = (( ProjectClassLoader ) kieProject.getClassLoader());
    assertNotNull( pcl.getStore().get("org/Person.class") );
}
 
Example #4
Source File: SecurityPolicyTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializationUntrustedMvelConsequence() throws Exception {
    String drl = "package org.foo.bar\n" +
            "rule R1 dialect \"mvel\" when\n" +
            "then\n" +
            "    System.exit(0);" +
            "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);

        KieBase kbase = kc.getKieBase();
        kbase = SerializationHelper.serializeObject( kbase );
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.toString());
        // test succeeded. the policy in place prevented the rule from executing the System.exit().
    }
}
 
Example #5
Source File: KieContainerTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDefaultKieSessionModelEmptyKmodule() {
    KieServices kieServices = KieServices.Factory.get();
    String drl = "package org.drools.test\n" +
            "rule R1 when\n" +
            "   $m : Object()\n" +
            "then\n" +
            "end\n";
    Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" );
    resource.setTargetPath("org/drools/test/rules.drl");
    String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
            "</kmodule>";

    // Create an in-memory jar for version 1.0.0
    ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-testGetDefaultKieSessionModelEmptyKmodule", "1.0.0");
    createAndDeployJar(kieServices, kmodule, releaseId, resource);

    KieContainer kieContainer = kieServices.newKieContainer(releaseId);

    KieSessionModel sessionModel = kieContainer.getKieSessionModel(null);
    assertNotNull(sessionModel);
}
 
Example #6
Source File: JbpmBpmn2TestCase.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieBase createKnowledgeBaseFromResources(Resource... process)
        throws Exception {

    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();
    if (process.length > 0) {
        KieFileSystem kfs = ks.newKieFileSystem();

        for (Resource p : process) {
            kfs.write(p);
        }

        KieBuilder kb = ks.newKieBuilder(kfs);

        kb.buildAll(); // kieModule is automatically deployed to KieRepository
                       // if successfully built.

        if (kb.getResults().hasMessages(Level.ERROR)) {
            throw new RuntimeException("Build Errors:\n"
                    + kb.getResults().toString());
        }
    }

    KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
    return kContainer.getKieBase();
}
 
Example #7
Source File: DroolsScoreExample.java    From tools-journey with Apache License 2.0 6 votes vote down vote up
public static void execute(KieContainer kc) throws Exception {
    // From the container, a session is created based on
    // its definition and configuration in the META-INF/kmodule.xml file
    KieSession ksession = kc.newKieSession("point-rulesKS");

    List<Order> orderList = getInitData();

    for (Order o : orderList) {
        ksession.insert(o);
        ksession.fireAllRules();
        // 执行完规则后, 执行相关的逻辑
        addScore(o);
    }

    ksession.dispose();

}
 
Example #8
Source File: BatchRunFluentTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetKieContainerTest() {
    KieServices kieServices = KieServices.Factory.get();
    KieContainer kieContainer = kieServices.newKieContainer(releaseId);

    ExecutableRunner<RequestContext> runner = ExecutableRunner.create(0L);

    ExecutableBuilder f = ExecutableBuilder.create();

    f.newApplicationContext("app1")
            .setKieContainer(kieContainer)
            .newSession()
            .insert("h1")
            .fireAllRules()
            .getGlobal("outS").out("outS1")
            .dispose();

    RequestContext requestContext = runner.execute(f.getExecutable());

    assertEquals("h1", requestContext.getOutputs().get("outS1"));
}
 
Example #9
Source File: KieServicesImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieContainer getKieClasspathContainer(String containerId, ClassLoader classLoader) {
    if ( classpathKContainer == null ) {
        // these are heavy to create, don't want to end up with two
        synchronized ( lock ) {
            if ( classpathKContainer == null ) {
                classpathClassLoader = classLoader;
                if (containerId == null) {
                	classpathKContainerId = UUID.randomUUID().toString();
                } else {
                	classpathKContainerId = containerId;
                }
                classpathKContainer = newKieClasspathContainer(classpathKContainerId, classLoader);
            } else if (classLoader != classpathClassLoader) {
                throw new IllegalStateException("There's already another KieContainer created from a different ClassLoader");
            }
        }
    } else if (classLoader != classpathClassLoader) {
        throw new IllegalStateException("There's already another KieContainer created from a different ClassLoader");
    }

    if (containerId != null && !classpathKContainerId.equals(containerId)) {
    	throw new IllegalStateException("The default global singleton KieClasspathContainer was already created with id "+classpathKContainerId);
    }
    
    return classpathKContainer;
}
 
Example #10
Source File: ApplyPmmlModelCommand.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
	public PMML4Result execute(Context context) {
		PMML4Result resultHolder = new PMML4Result(requestData.getCorrelationId());
		RequestContextImpl ctx = (RequestContextImpl)context;
		KieBase kbase = ((RegistryContext)context).lookup(KieBase.class);
		if (kbase == null) {
			System.out.println("KieBase not found in context!");
			return null;
		} else {
			KieContainer kcont =  ((KnowledgeBaseImpl)kbase).getKieContainer();
			kcont.getKieBaseNames().forEach(n -> {System.out.println(n);});
			kbase.getKiePackages().forEach(kp -> {
				System.out.println("Package: "+kp.getName());
			});
		}
		return null;
//		RuleUnitExecutor executor = RuleUnitExecutor.create().bind(kbase);
//		DataStore<PMMLRequestData> data = executor.newDataSource("request", this.requestData);
//		DataStore<PMML4Result> resultData = executor.newDataSource("results", resultHolder);
//		System.out.println("Setting result: "+resultHolder);
//		ctx.lookup(ExecutionResultImpl.class).setResult(this.outIdentifier, resultHolder);
//		return resultHolder;
	}
 
Example #11
Source File: KieServicesTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisposeClearTheIDReference() {
	ReleaseId releaseId = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
       createAndDeployJar( ks, releaseId, createDRL("ruleA") );
       
	KieContainer c1 = ks.newKieContainer("id1", releaseId);
	try {
		ks.newKieClasspathContainer("id1");
		fail("should not allow repeated container IDs.");
	} catch (IllegalStateException is) {
		// ok.
	}
	
	((KieContainerImpl) c1).dispose();
	
	ks.newKieClasspathContainer("id1"); // now OK.
}
 
Example #12
Source File: BaseTest.java    From iot-ocp with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    KieServices kieServices = KieServices.Factory.get();

    KieContainer kContainer = kieServices.getKieClasspathContainer();
    Results verifyResults = kContainer.verify();
    for (Message m : verifyResults.getMessages()) {
        LOG.debug("Kie container message: {}", m);
    }

    KieBase kieBase = kContainer.getKieBase();
    LOG.debug("Created kieBase");

    for ( KiePackage kp : kieBase.getKiePackages() ) {
        for (Rule rule : kp.getRules()) {
            LOG.debug("kp " + kp + " rule " + rule.getName());
        }
    }

    session = kieBase.newKieSession();
    LOG.info(session.getGlobals().toString());
    Logger kieLogger = LoggerFactory.getLogger(this.getClass());
   // session.setGlobal("logger",kieLogger);
}
 
Example #13
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 #14
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testKieModuleJar() {
    String str = "package org.drools.compiler.i18ntest;\n" +
            "import org.drools.compiler.I18nPerson;\n" +
            "\n" +
            "global java.util.List list;\n" +
            "rule \"名称 is 山田花子\"\n" +
            "    when\n" +
            "        p : I18nPerson( 名称 == \"山田花子\" )\n" +
            "    then\n" +
            "        list.add( \"名称は山田花子です\" );\n" +
            "end\n";

    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId("org.kie", "118ntest", "1.0.0");
    byte[] jar = createKJar(ks, releaseId, null, str);
    KieModule km = deployJar(ks, jar);
    KieContainer kc = ks.newKieContainer(km.getReleaseId());
    KieSession ksession = kc.newKieSession();

    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 #15
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 #16
Source File: KieContainerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMemoryFileSystemFolderUniqueness() {
    KieServices kieServices = KieServices.Factory.get();
    String drl = "package org.drools.test\n" +
                 "rule R1 when\n" +
                 "   $m : Object()\n" +
                 "then\n" +
                 "end\n";
    Resource resource = kieServices.getResources().newReaderResource( new StringReader( drl), "UTF-8" );
    resource.setTargetPath("org/drools/test/rules.drl");
    String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                     "<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
                     "  <kbase name=\"testKbase\" packages=\"org.drools.test\">\n" +
                     "    <ksession name=\"testKsession\"/>\n" +
                     "  </kbase>\n" +
                     "</kmodule>";

    // Create an in-memory jar for version 1.0.0
    ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-delete", "1.0.0");
    createAndDeployJar(kieServices, kmodule, releaseId, resource);

    KieContainer kieContainer = kieServices.newKieContainer(releaseId);

    KieModule kieModule = ((InternalKieContainer) kieContainer).getMainKieModule();
    MemoryFileSystem memoryFileSystem = ((MemoryKieModule) kieModule).getMemoryFileSystem();
    Folder rootFolder = memoryFileSystem.getFolder("");
    Object[] members = rootFolder.getMembers().toArray();
    assertEquals(2, members.length);
    Folder firstFolder = (Folder) members[0];
    Folder secondFolder = (Folder) members[1];
    assertEquals(firstFolder.getParent(), secondFolder.getParent());
}
 
Example #17
Source File: HelloWorldExample.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public static void execute(KieContainer kc) {
    // From the container, a session is created based on
    // its definition and configuration in the META-INF/kmodule.xml file
    KieSession ksession = kc.newKieSession("HelloWorldKS");

    // Once the session is created, the application can interact with it
    // In this case it is setting a global as defined in the
    // org/drools/examples/helloworld/HelloWorld.drl file
    ksession.setGlobal("list",
            new ArrayList<>());

    // The application can also setup listeners
    ksession.addEventListener(new DebugAgendaEventListener());
    ksession.addEventListener(new DebugRuleRuntimeEventListener());

    // To setup a file based audit logger, uncomment the next line
    // KieRuntimeLogger logger = ks.getLoggers().newFileLogger( ksession, "./helloworld" );

    // To setup a ThreadedFileLogger, so that the audit view reflects events whilst debugging,
    // uncomment the next line
    // KieRuntimeLogger logger = ks.getLoggers().newThreadedFileLogger( ksession, "./helloworld", 1000 );

    // The application can insert facts into the session
    final Message message = new Message();
    message.setMessage("Hello World");
    message.setStatus(Message.HELLO);
    ksession.insert(message);

    // and fire the rules
    ksession.fireAllRules();

    // Remove comment if using logging
    // logger.close();

    // and then dispose the session
    ksession.dispose();
}
 
Example #18
Source File: KieContainerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateToNonExistingRelease() {
    // DROOLS-1562
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId("org.kie", "test-release", "1.0.0");
    createAndDeployJar( ks, releaseId, createDRL("ruleA") );

    KieContainer kieContainer = ks.newKieContainer(releaseId);

    Results results = kieContainer.updateToVersion( ks.newReleaseId( "org.kie", "test-release", "1.0.1" ) );
    assertEquals( 1, results.getMessages( Level.ERROR ).size() );
    assertEquals( "1.0.0", ( (InternalKieContainer) kieContainer ).getContainerReleaseId().getVersion() );
}
 
Example #19
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatelessSessionDeclarativeChannelRegistration() {
    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\" type=\"stateless\">\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());
    
    StatelessKieSession statelessKieSession = kieContainer.newStatelessKieSession();
    assertEquals(1, statelessKieSession.getChannels().size());
    assertTrue(statelessKieSession.getChannels().keySet().contains("testChannel"));
}
 
Example #20
Source File: KieServicesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewKieClasspathIDs() {
	KieContainer c1 = ks.newKieClasspathContainer("id1");
	KieContainer c2 = ks.newKieClasspathContainer("id2");
	try {
		ks.newKieClasspathContainer("id2");
		fail("should not allow repeated container IDs.");
	} catch (IllegalStateException is) {
		// ok.
	}
}
 
Example #21
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 #22
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 #23
Source File: KieContainerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMainKieModule() {
    KieServices ks = KieServices.Factory.get();
    // Create an in-memory jar for version 1.0.0
    ReleaseId releaseId = ks.newReleaseId("org.kie", "test-delete", "1.0.0");
    createAndDeployJar( ks, releaseId, createDRL("ruleA") );

    KieContainer kieContainer = ks.newKieContainer(releaseId);
    KieModule kmodule = ((InternalKieContainer) kieContainer).getMainKieModule();
    assertEquals( releaseId, kmodule.getReleaseId() );
}
 
Example #24
Source File: KieCompilationCacheTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompilationCache() throws Exception {
    String drl = "package org.drools.compiler\n" +
            "declare type X\n" +
            "    foo : String\n" +
            "end\n"+
            "rule R1 when\n" +
            "   $m : X( foo == \"Hello World\" )\n" +
            "then\n" +
            "end\n";
    
    KieServices ks = KieServices.Factory.get();

    KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
    ks.newKieBuilder( kfs ).buildAll();
    
    ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
    InternalKieModule kieModule = (InternalKieModule) ks.getRepository().getKieModule( releaseId );
    byte[] jar = kieModule.getBytes();
    
    MemoryFileSystem mfs = MemoryFileSystem.readFromJar( jar );
    File file = mfs.getFile( KieBuilderImpl.getCompilationCachePath( releaseId, "KBase1") );
    assertNotNull( file );

    Resource jarRes = ks.getResources().newByteArrayResource( jar );
    KieModule km = ks.getRepository().addKieModule( jarRes );
    KieContainer kc = ks.newKieContainer( km.getReleaseId() );
    
    KieBase kbase = kc.getKieBase();
    FactType type = kbase.getFactType( "org.drools.compiler", "X" );
    FactField foo = type.getField( "foo" );
    Object x = type.newInstance();
    foo.set( x, "Hello World" );
    
    KieSession ksession = kc.newKieSession();
    ksession.insert(x);

    int count = ksession.fireAllRules();
    assertEquals( 1, count );
}
 
Example #25
Source File: RulesManager.java    From hacep with Apache License 2.0 5 votes vote down vote up
public KieContainer newKieContainer(String version) {
    ReleaseId releaseId = kieServices.newReleaseId(
            rulesConfiguration.getGroupId(),
            rulesConfiguration.getArtifactId(),
            StringUtils.isEmpty(version) ? rulesConfiguration.getVersion() : version);
    return kieServices.newKieContainer(releaseId);
}
 
Example #26
Source File: RulesManager.java    From hacep with Apache License 2.0 5 votes vote down vote up
public KieSession newKieSession(KieContainer kieContainer) {
    checkStatus();
    if (!StringUtils.isEmpty(rulesConfiguration.getKieSessionName())) {
        return kieContainer.newKieSession(rulesConfiguration.getKieSessionName());
    }
    return kieContainer.newKieSession();
}
 
Example #27
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 #28
Source File: KieFileSystemScannerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSnapshot() throws Exception {
    Path tempDir = Files.createTempDirectory(FileSystems.getDefault().getPath("./target"), null);
    File file = null;

    try {
        KieServices ks = KieServices.Factory.get();
        ReleaseId releaseId = ks.newReleaseId( "org.kie", "scanner-test", "1.0-SNAPSHOT" );

        createKieJar( ks, releaseId, "R1" );

        KieContainer kieContainer = ks.newKieContainer( releaseId );

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

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

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

        file = write( createKieJar( ks, releaseId, "R2" ), tempDir, releaseId );
        ksession = kieContainer.newKieSession();
        checkKSession( ksession, "R1" );

        scanner.scanNow();
        ksession = kieContainer.newKieSession();
        checkKSession( ksession, "R2" );
    } finally {
        if (file != null) {
            file.delete();
        }
        Files.delete(tempDir);
    }
}
 
Example #29
Source File: KieServicesImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieScanner newKieScanner(KieContainer kieContainer) {
    KieScannerFactoryService scannerFactoryService = ServiceRegistry.getInstance().get(KieScannerFactoryService.class);
    if (scannerFactoryService == null) {
        throw new RuntimeException( "Cannot instance a maven based KieScanner, is kie-ci on the classpath?" );
    }
    InternalKieScanner scanner = (InternalKieScanner)scannerFactoryService.newKieScanner();
    scanner.setKieContainer(kieContainer);
    return scanner;
}
 
Example #30
Source File: RulesManager.java    From hacep with Apache License 2.0 5 votes vote down vote up
public KieSession deserializeOrCreate(KieContainer kieContainer, byte[] buffer) {
    if (buffer == null) {
        if (LOGGER.isDebugEnabled()) LOGGER.debug("Buffer empty, creating new KieSession");
        return newKieSession(kieContainer);
    }

    Marshaller marshaller = createSerializableMarshaller(getKieBase(kieContainer));
    return KieSessionByteArraySerializer.readSession(marshaller, buffer);
}