org.kie.api.builder.KieModule Java Examples

The following examples show how to use org.kie.api.builder.KieModule. 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: 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 #2
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public void createAndTestKieContainer(ReleaseId releaseId, KieBuilder kb, String kBaseName) throws IOException,
        ClassNotFoundException,
        InterruptedException {
    KieServices ks = KieServices.Factory.get();
    
    kb.buildAll();
    
    if ( kb.getResults().hasMessages(Level.ERROR) ) {
        fail("Unable to build KieModule\n" + kb.getResults( ).toString() );
    }
    KieRepository kr = ks.getRepository();
    KieModule kJar = kr.getKieModule(releaseId);
    assertNotNull( kJar );
    
    KieContainer kContainer = ks.newKieContainer(releaseId);
    KieBase kBase = kBaseName != null ? kContainer.getKieBase( kBaseName ) : kContainer.getKieBase();

    KieSession kSession = kBase.newKieSession();
    List list = new ArrayList();
    kSession.setGlobal( "list", list );
    kSession.fireAllRules();

    assertEquals( 1, list.size() );
    assertEquals( "org.kie.test.Message", list.get(0).getClass().getName() );       
}
 
Example #3
Source File: KieRepositoryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadingNotAKJar() {
    // DROOLS-1351
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    URLClassLoader urlClassLoader = new URLClassLoader( new URL[]{this.getClass().getResource( "/only-jar-pojo-not-kjar-no-kmodule-1.0.0.jar" )} );
    Thread.currentThread().setContextClassLoader( urlClassLoader );

    try {
        KieServices ks = KieServices.Factory.get();
        KieRepository kieRepository = ks.getRepository();
        ReleaseId releaseId = ks.newReleaseId( "org.test", "only-jar-pojo-not-kjar-no-kmodule", "1.0.0" );
        KieModule kieModule = kieRepository.getKieModule( releaseId );
        assertNull( kieModule );
    } finally {
        Thread.currentThread().setContextClassLoader( cl );
    }
}
 
Example #4
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidXsdTargetNamespace() {
    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" +
            "  </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);

    ks.newKieContainer( km.getReleaseId() );
}
 
Example #5
Source File: KieRepositoryImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a map that fulfills 2 purposes: <ol>
 * <li>It is a {@link NavigableMap} and thus can be used in the {@link KieModuleRepo#load(InternalKieScanner, ReleaseId, VersionRange)} method</li>
 * <li>It is a LRU cache, and thus will not grow without limit.
 * </ol>
 * @return a {@link NavigableMap} that is "backed" by a {@link LinkedHashMap} to enforce a LRU cache
 */
private NavigableMap<ComparableVersion, KieModule> createNewArtifactMap() {
    NavigableMap<ComparableVersion, KieModule> newArtifactMap = new TreeMap<ComparableVersion, KieModule>() {

        private final Map<ComparableVersion, KieModule> artifactMap = this;

        LinkedHashMap<ComparableVersion, Object> backingLRUMap = new LinkedHashMap<ComparableVersion, Object>(16, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry( Map.Entry<ComparableVersion, Object> eldest ) {
                boolean remove = (size() > MAX_SIZE_GA_VERSIONS_CACHE);
                if( remove ) {
                    artifactMap.remove(eldest.getKey());
                }
                return remove;
            }
        };

        @Override
        public KieModule put( ComparableVersion key, KieModule value ) {
            backingLRUMap.put(key, PRESENT);
            return super.put(key, value);
        }

    };
    return newArtifactMap;
}
 
Example #6
Source File: KieRepositoryImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieModule getKieModule(ReleaseId releaseId, PomModel pomModel) {
    KieModule kieModule = kieModuleRepo.load( null, releaseId );
    if (kieModule == null) {
        log.debug("KieModule Lookup. ReleaseId {} was not in cache, checking classpath",
                  releaseId.toExternalForm());
        kieModule = checkClasspathForKieModule(releaseId);
    }

    if (kieModule == null) {
        log.debug("KieModule Lookup. ReleaseId {} was not in cache, checking maven repository",
                  releaseId.toExternalForm());
        kieModule = loadKieModuleFromMavenRepo(releaseId, pomModel);
    }

    return kieModule;
}
 
Example #7
Source File: KieRepositoryImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
synchronized void store(KieModule kieModule) {
    ReleaseId releaseId = kieModule.getReleaseId();
    String ga = releaseId.getGroupId() + ":" + releaseId.getArtifactId();
    ComparableVersion comparableVersion = new ComparableVersion(releaseId.getVersion());

    NavigableMap<ComparableVersion, KieModule> artifactMap = kieModules.get(ga);
    if( artifactMap == null ) {
        artifactMap = createNewArtifactMap();
        kieModules.put(ga, artifactMap);
    }

    KieModule oldReleaseIdKieModule = oldKieModules.get(releaseId);
    // variable used in order to test race condition
    if (oldReleaseIdKieModule == null) {
        KieModule oldKieModule = artifactMap.get(comparableVersion);
        if (oldKieModule != null) {
            oldKieModules.put( releaseId, oldKieModule );
        }
    }
    artifactMap.put( comparableVersion, kieModule );
}
 
Example #8
Source File: DynamicRuleLoadTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testKJarUpgrade() throws Exception {
    // DROOLS-919
    KieServices ks = KieServices.Factory.get();

    // Create an in-memory jar for version 1.0.0
    ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" );
    KieModule km = createAndDeployJar( ks, releaseId1, drl1, drl2_1 );

    // Create a session and fire rules
    kieContainer = ks.newKieContainer( km.getReleaseId() );
    ksession = kieContainer.newKieSession();

    ksession.setGlobal( "test", this );
    ksession.insert( new Message( "Hi Universe" ) );
    ksession.fireAllRules();

    assertTrue( done );
}
 
Example #9
Source File: KieRepositoryImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
synchronized KieModule remove(ReleaseId releaseId) {
    KieModule removedKieModule = null;
    String ga = releaseId.getGroupId() + ":" + releaseId.getArtifactId();
    ComparableVersion comparableVersion = new ComparableVersion(releaseId.getVersion());

    NavigableMap<ComparableVersion, KieModule> artifactMap = kieModules.get(ga);
    if (artifactMap != null) {
        removedKieModule = artifactMap.remove(comparableVersion);
        if (artifactMap.isEmpty()) {
            kieModules.remove(ga);
        }
        oldKieModules.remove(releaseId);
    }

    return removedKieModule;
}
 
Example #10
Source File: KieRepositoryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadKjarFromClasspath() {
    // DROOLS-1335
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    URLClassLoader urlClassLoader = new URLClassLoader( new URL[]{this.getClass().getResource( "/kie-project-simple-1.0.0.jar" )} );
    Thread.currentThread().setContextClassLoader( urlClassLoader );

    try {
        KieServices ks = KieServices.Factory.get();
        KieRepository kieRepository = ks.getRepository();
        ReleaseId releaseId = ks.newReleaseId( "org.test", "kie-project-simple", "1.0.0" );
        KieModule kieModule = kieRepository.getKieModule( releaseId );
        assertNotNull( kieModule );
        assertEquals( releaseId, kieModule.getReleaseId() );
    } finally {
        Thread.currentThread().setContextClassLoader( cl );
    }
}
 
Example #11
Source File: KieRepositoryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testTryLoadNotExistingKjarFromClasspath() {
    // DROOLS-1335
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    URLClassLoader urlClassLoader = new URLClassLoader( new URL[]{this.getClass().getResource( "/kie-project-simple-1.0.0.jar" )} );
    Thread.currentThread().setContextClassLoader( urlClassLoader );

    try {
        KieServices ks = KieServices.Factory.get();
        KieRepository kieRepository = ks.getRepository();
        ReleaseId releaseId = ks.newReleaseId( "org.test", "kie-project-simple", "1.0.1" );
        KieModule kieModule = kieRepository.getKieModule( releaseId );
        assertNull( kieModule );
    } finally {
        Thread.currentThread().setContextClassLoader( cl );
    }
}
 
Example #12
Source File: TaxiFareConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public KieContainer kieContainer() {
    KieServices kieServices = KieServices.Factory.get();

    KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
    kieFileSystem.write(ResourceFactory.newClassPathResource(drlFile));
    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
    kieBuilder.buildAll();
    KieModule kieModule = kieBuilder.getKieModule();

    return kieServices.newKieContainer(kieModule.getReleaseId());
    
}
 
Example #13
Source File: KieHelloWorldTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testHelloWorldWithSpace() throws Exception {
    // DROOLS-2338
    final KieServices kieServices = KieServices.get();

    final Path dir = Paths.get("/tmp/t tt");
    Files.createDirectories(dir);
    final String text = "rule \"Hello world rule\"\n" +
            "when\n" +
            "then\n" +
            "    System.out.println(\"Hello world\");" +
            "end\n";
    final Path filePath = dir.resolve("one.drl");
    Files.write(filePath, text.getBytes());

    final KieFileSystem fs = kieServices.newKieFileSystem();

    fs.write( ResourceFactory.newUrlResource("file:/tmp/t%20tt/one.drl"));

    KieBuilder kieBuilder = kieServices.newKieBuilder(fs);
    kieBuilder.buildAll();
    KieModule kieModule = kieBuilder.getKieModule();

    KieSession ksession = kieServices.newKieContainer(kieModule.getReleaseId()).newKieSession();
    ksession.insert(new Object());

    int count = ksession.fireAllRules();

    assertEquals( 1, count );
}
 
Example #14
Source File: KieLoggersTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclarativeKieConsoleLoggerStateless() 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")
         .setType(KieSessionModel.KieSessionType.STATELESS)
         .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());

    StatelessKieSession ksession = kieContainer.newStatelessKieSession("KSession1");
    ksession.execute( new Message("Hello World") );

    KieRuntimeLogger logger = ksession.getLogger();
    assertNotNull(logger);
    logger.close();
}
 
Example #15
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 #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: 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 #18
Source File: MBeansMonitoringTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Copied from KieRepositoryTest to test JMX monitoring
 */
@Test
public void testLoadKjarFromClasspath() {
    // DROOLS-1335
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    URLClassLoader urlClassLoader = new URLClassLoader( new URL[]{this.getClass().getResource( "/kie-project-simple-1.0.0.jar" )} );
    Thread.currentThread().setContextClassLoader( urlClassLoader );
    
    MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();

    try {
        KieServices ks = KieServices.Factory.get();
        KieRepository kieRepository = ks.getRepository();
        ReleaseId releaseId = ks.newReleaseId( "org.test", "kie-project-simple", "1.0.0" );
        KieModule kieModule = kieRepository.getKieModule( releaseId );
        assertNotNull( kieModule );
        assertEquals( releaseId, kieModule.getReleaseId() );
        
        ks.newKieContainer("myID", releaseId);
        
        KieContainerMonitorMXBean c1Monitor = JMX.newMXBeanProxy(
                mbserver,
                DroolsManagementAgent.createObjectNameBy("myID"),
                KieContainerMonitorMXBean.class);
        
        assertTrue(c1Monitor.getConfiguredReleaseId().sameGAVof(releaseId));
        assertTrue(c1Monitor.getResolvedReleaseId().sameGAVof(releaseId));
    } finally {
        Thread.currentThread().setContextClassLoader( cl );
    }
}
 
Example #19
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testOldXsdTargetNamespace() {
    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" +
            "  </kbase>\n" +
            "</kmodule>";

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

    // Create an in-memory jar for version 1.0.0
    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);

    ks.newKieContainer( km.getReleaseId() );
}
 
Example #20
Source File: KieCompilationCacheTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheWigAccumulate() throws Exception {
    String drl1 = "package org.pkg1\n" +
            "rule R11 when\n" +
            "   Number() from accumulate(String(), \n" +
            "              init(int x = 0;)," +
            "              action(x++;)," +
            "              reverse(x--;)," +
            "              result(x))\n" +
            "then\n" +
            "end\n";

    KieServices ks = KieServices.Factory.get();

    ReleaseId releaseId = ks.newReleaseId("org.kie", "cache-accumulate", "1.0");

    KieFileSystem kfs = ks.newKieFileSystem()
            .generateAndWritePomXML(releaseId)
            .write("src/main/resources/KBase1/org/pkg1/r1.drl", drl1)
            .writeKModuleXML(createKieProjectWithPackagesAnd2KieBases(ks).toXML());
    ks.newKieBuilder( kfs ).buildAll();
    
    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 );
    
    KieSession ksession = ks.newKieContainer( km.getReleaseId() ).newKieSession("KSession1");
    ksession.insert(new String("Hello World"));
    assertEquals( 1, ksession.fireAllRules() );
}
 
Example #21
Source File: SimulateTestBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected ReleaseId createKJar(String... pairs) throws IOException {
    KieServices ks = KieServices.Factory.get();
    KieModuleModel kproj = ks.newKieModuleModel();
    KieFileSystem kfs = ks.newKieFileSystem();

    for ( int i = 0; i < pairs.length; i += 2 ) {
        String id = pairs[i];
        String rule = pairs[i + 1];

        kfs.write( "src/main/resources/" + id.replaceAll( "\\.", "/" ) + "/rule" + i + ".drl", rule );

        KieBaseModel kBase1 = kproj.newKieBaseModel( id )
                .setEqualsBehavior( EqualityBehaviorOption.EQUALITY )
                .setEventProcessingMode( EventProcessingOption.STREAM )
                .addPackage( id );

        KieSessionModel ksession1 = kBase1.newKieSessionModel(id + ".KSession1")
                .setType(KieSessionModel.KieSessionType.STATEFUL)
                .setClockType(ClockTypeOption.get("pseudo"));
    }

    kfs.writeKModuleXML(kproj.toXML());

    // buildAll() automatically adds the module to the kieRepository
    KieBuilder kieBuilder = ks.newKieBuilder(kfs).buildAll();
    assertTrue(kieBuilder.getResults().getMessages().isEmpty());
    
    KieModule kieModule = kieBuilder.getKieModule();
    return kieModule.getReleaseId();
}
 
Example #22
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 #23
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 #24
Source File: DynamicRuleLoadTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public void updateToVersion() {
    KieServices ks = KieServices.Factory.get();

    // Create a new jar for version 1.1.0
    ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" );
    KieModule km = createAndDeployJar( ks, releaseId2, drl1, drl2_2 );

    // try to update the container to version 1.1.0
    kieContainer.updateToVersion( releaseId2 );

    // create and use a new session
    ksession.insert( new Message( "Hello World" ) );
}
 
Example #25
Source File: KieModuleRepoTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Runnable getStoreArtifactRunnable(final KieModuleRepo kieModuleRepo, final String groupId, final String artifactId,
        final String version, final CyclicBarrier storeOperationBarrier, final CyclicBarrier threadsFinishedBarrier) {
    return () -> {
        final ReleaseIdImpl firstReleaseId = new ReleaseIdImpl(groupId, artifactId, version);
        final KieModule firstKieModule = mock(KieModule.class);
        when(firstKieModule.getReleaseId()).thenReturn(firstReleaseId);
        waitFor(storeOperationBarrier);
        kieModuleRepo.store(firstKieModule);
        waitFor(threadsFinishedBarrier);
    };
}
 
Example #26
Source File: KieModuleRepoTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private static int countKieModules( final Map<String, NavigableMap<ComparableVersion, KieModule>> kieModulesCache ) {
   int numKieModules = 0;
   for( final NavigableMap<ComparableVersion, KieModule> map : kieModulesCache.values() ) {
       numKieModules += map.size();
   }
   return numKieModules;
}
 
Example #27
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 #28
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static KieModule createAndDeployJar(KieServices ks, ReleaseId releaseId, String... drls) {
    byte[] jar = createJar(ks, releaseId, drls);

    // Deploy jar into the repository
    KieModule km = deployJarIntoRepository(ks, jar);
    return km;
}
 
Example #29
Source File: SimulateTestBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static ReleaseId createKJarWithMultipleResources(String id,
                                                    String[] resources,
                                                    ResourceType[] types) {
    KieServices ks = KieServices.Factory.get();
    KieModuleModel kproj = ks.newKieModuleModel();
    KieFileSystem kfs = ks.newKieFileSystem();

    for ( int i = 0; i < resources.length; i++ ) {
        String res = resources[i];
        String type = types[i].getDefaultExtension();

        kfs.write( "src/main/resources/" + id.replaceAll( "\\.", "/" ) + "/org/test/res" + i + "." + type, res );
    }

    KieBaseModel kBase1 = kproj.newKieBaseModel( id )
            .setEqualsBehavior( EqualityBehaviorOption.EQUALITY )
            .setEventProcessingMode( EventProcessingOption.STREAM );

    KieSessionModel ksession1 = kBase1.newKieSessionModel( id + ".KSession1" )
            .setDefault(true)
            .setType(KieSessionModel.KieSessionType.STATEFUL)
            .setClockType( ClockTypeOption.get( "pseudo" ) );

    kfs.writeKModuleXML(kproj.toXML());

    KieBuilder kieBuilder = ks.newKieBuilder(kfs).buildAll();
    assertTrue(kieBuilder.getResults().getMessages().isEmpty());
    
    KieModule kieModule = kieBuilder.getKieModule();
    return kieModule.getReleaseId();
}
 
Example #30
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static KieModule createAndDeployJar(KieServices ks,
        String kmoduleContent,
        Predicate<String> classFilter,
        ReleaseId releaseId,
        Resource... resources) {
    byte[] jar = createJar(ks, kmoduleContent, classFilter, releaseId, resources);

    KieModule km = deployJarIntoRepository(ks, jar);
    return km;
}