org.kie.api.builder.KieRepository Java Examples

The following examples show how to use org.kie.api.builder.KieRepository. 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: KieModuleRepoTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private static KieContainerImpl createMockKieContainer(final ReleaseId projectReleaseId, final KieModuleRepo kieModuleRepo) throws Exception {

        // kie module
        final InternalKieModule mockKieProjectKieModule = mock(InternalKieModule.class);
        final ResourceProvider mockKieProjectKieModuleResourceProvider = mock(ResourceProvider.class);
        when(mockKieProjectKieModule.createResourceProvider()).thenReturn(mockKieProjectKieModuleResourceProvider);

        // kie project
        final KieModuleKieProject kieProject = new KieModuleKieProject(mockKieProjectKieModule);
        final KieModuleKieProject mockKieProject = spy(kieProject);
        doNothing().when(mockKieProject).init();
        doReturn(projectReleaseId).when(mockKieProject).getGAV();
        doReturn( new HashMap<String, KieBaseModel>() ).when( mockKieProject ).updateToModule( any( InternalKieModule.class ) );

        // kie repository
        final KieRepository kieRepository = new KieRepositoryImpl();
        final Field kieModuleRepoField = KieRepositoryImpl.class.getDeclaredField("kieModuleRepo");
        kieModuleRepoField.setAccessible(true);
        kieModuleRepoField.set(kieRepository, kieModuleRepo);
        kieModuleRepoField.setAccessible(false);

        // kie container
        final KieContainerImpl kieContainerImpl = new KieContainerImpl(mockKieProject, kieRepository);
        return kieContainerImpl;
    }
 
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: ReloadDroolsRulesService.java    From drools-examples with Apache License 2.0 6 votes vote down vote up
private  KieContainer loadContainerFromString(List<Rule> rules) {
    long startTime = System.currentTimeMillis();
    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();
    KieFileSystem kfs = ks.newKieFileSystem();

    for (Rule rule:rules) {
        String  drl=rule.getContent();
        kfs.write("src/main/resources/" + drl.hashCode() + ".drl", drl);
    }

    KieBuilder kb = ks.newKieBuilder(kfs);

    kb.buildAll();
    if (kb.getResults().hasMessages(Message.Level.ERROR)) {
        throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
    }
    long endTime = System.currentTimeMillis();
    System.out.println("Time to build rules : " + (endTime - startTime)  + " ms" );
    startTime = System.currentTimeMillis();
    KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
    endTime = System.currentTimeMillis();
    System.out.println("Time to load container: " + (endTime - startTime)  + " ms" );
    return kContainer;
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: KieBuilderImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private static void buildKieProject( ResultsImpl messages,
                                     KieModuleKieProject kProject,
                                     MemoryFileSystem trgMfs ) {
    kProject.init();
    kProject.verify( messages );

    if ( messages.filterMessages( Level.ERROR ).isEmpty() ) {
        InternalKieModule kModule = kProject.getInternalKieModule();
        if ( trgMfs != null ) {
            new KieMetaInfoBuilder( kModule ).writeKieModuleMetaInfo( trgMfs );
            kProject.writeProjectOutput(trgMfs, messages);
        }
        KieRepository kieRepository = KieServices.Factory.get().getRepository();
        kieRepository.addKieModule( kModule );
        for ( InternalKieModule kDep : kModule.getKieDependencies().values() ) {
            kieRepository.addKieModule( kDep );
        }
    }
}
 
Example #10
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Please note: the recommended way of getting a KieContainer is relying on {@link org.kie.api.KieServices KieServices} API,
 * for example: {@link org.kie.api.KieServices#newKieContainer(ReleaseId) KieServices.newKieContainer(...)}.
 * The direct manual call to KieContainerImpl constructor instead would not guarantee the consistency of the supplied containerId.
 */
public KieContainerImpl(String containerId, KieProject kProject, KieRepository kr) {
    this.kr = kr;
    this.kProject = kProject;
    this.containerId = containerId;
    kProject.init();
    initMBeans(containerId);
}
 
Example #11
Source File: DroolsConfig.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public KieContainer kieContainer() throws IOException {
    KieRepository kieRepository = kieServices.getRepository();
    kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
    kieBuilder.buildAll();
    return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
}
 
Example #12
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 #13
Source File: StartEventTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignalStartDynamic() throws Exception {

    KieBase kbase = createKnowledgeBase("BPMN2-SignalStart.bpmn2");
    ksession = createKnowledgeSession(kbase);
    // create KieContainer after session was created to make sure no runtime data
    // will be used during serialization (deep clone)
    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();
    KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
    kContainer.getKieBase();

    final List<String> list = new ArrayList<>();
    ksession.addEventListener(new DefaultProcessEventListener() {
        public void beforeProcessStarted(ProcessStartedEvent event) {
            logger.info("{}", event.getProcessInstance().getId());
            list.add(event.getProcessInstance().getId());
        }
    });
    ksession.signalEvent("MySignal", "NewValue");

    assertThat(getNumberOfProcessInstances("Minimal")).isEqualTo(1);
    // now remove the process from kbase to make sure runtime based listeners are removed from signal manager
    kbase.removeProcess("Minimal");
    assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { ksession.signalEvent("MySignal", "NewValue"); })
                .withMessageContaining("Unknown process ID: Minimal");
    // must be still one as the process was removed
    assertThat(getNumberOfProcessInstances("Minimal")).isEqualTo(1);

}
 
Example #14
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 #15
Source File: DroolsConfig.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public KieContainer kieContainer() throws IOException {
    KieRepository kieRepository = kieServices.getRepository();
    kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
    kieBuilder.buildAll();
    return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
}
 
Example #16
Source File: DroolsConfig.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public KieContainer kieContainer() throws IOException {
    KieRepository kieRepository = kieServices.getRepository();
    kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
    kieBuilder.buildAll();
    return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
}
 
Example #17
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
/**
 * Please note: the recommended way of getting a KieContainer is relying on {@link org.kie.api.KieServices KieServices} API,
 * for example: {@link org.kie.api.KieServices#newKieContainer(ReleaseId) KieServices.newKieContainer(...)}.
 * The direct manual call to KieContainerImpl constructor instead would not guarantee the consistency of the supplied containerId.
 */
public KieContainerImpl(String containerId, KieProject kProject, KieRepository kr, ReleaseId containerReleaseId) {
    this(containerId, kProject, kr);
    this.configuredReleaseId = containerReleaseId;
    this.containerReleaseId = containerReleaseId;
}
 
Example #18
Source File: KieServicesImpl.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public KieRepository getRepository() {
    return KieRepositoryImpl.INSTANCE;
}
 
Example #19
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testKieModuleDependencies() throws ClassNotFoundException, InterruptedException, IOException {
    KieServices ks = KieServices.Factory.get();
    
    String namespace1 = "org.kie.test1";
    ReleaseId releaseId1 = KieServices.Factory.get().newReleaseId(namespace1, "memory", "1.0");
    KieModuleModel kProj1 = createKieProject(namespace1);        
    KieFileSystem kfs1 = KieServices.Factory.get().newKieFileSystem();
    generateAll(kfs1, namespace1, releaseId1, kProj1);

    KieBuilder kb1 = createKieBuilder(kfs1);
    kb1.buildAll();        
    if ( kb1.getResults().hasMessages(Level.ERROR) ) {
        fail("Unable to build KieJar\n" + kb1.getResults( ).toString() );
    }
    KieRepository kr = ks.getRepository();
    KieModule kModule1 = kr.getKieModule(releaseId1);
    assertNotNull( kModule1 );
    
    
    String namespace2 = "org.kie.test2";
    ReleaseId releaseId2 = KieServices.Factory.get().newReleaseId(namespace2, "memory", "1.0");
    KieModuleModel kProj2 = createKieProject(namespace2);        
    KieBaseModelImpl kieBase2 = ( KieBaseModelImpl ) kProj2.getKieBaseModels().get( namespace2 );
    kieBase2.addInclude( namespace1 );
    
    KieFileSystem kfs2 = KieServices.Factory.get().newKieFileSystem();
    generateAll(kfs2, namespace2, releaseId2, kProj2);
    

    KieBuilder kb2 = createKieBuilder(kfs2);
    kb2.setDependencies( kModule1 );
    kb2.buildAll();        
    if ( kb2.getResults().hasMessages(Level.ERROR) ) {
        fail("Unable to build KieJar\n" + kb2.getResults( ).toString() );
    }
    KieModule kModule2= kr.getKieModule(releaseId2);
    assertNotNull( kModule2);
    
    KieContainer kContainer = ks.newKieContainer(releaseId2);
    KieBase kBase = kContainer.getKieBase( namespace2 );
    
    KieSession kSession = kBase.newKieSession();
    List list = new ArrayList();
    kSession.setGlobal( "list", list );
    kSession.fireAllRules();

    assertEquals( 2, list.size() );
    if ("org.kie.test1.Message".equals(list.get(0).getClass().getName())) {
        assertEquals( "org.kie.test2.Message", list.get(1).getClass().getName() );
    } else {
        assertEquals( "org.kie.test2.Message", list.get(0).getClass().getName() );
        assertEquals( "org.kie.test1.Message", list.get(1).getClass().getName() );
    }
}
 
Example #20
Source File: KieSessionFactory.java    From NiFi-Rule-engine-processor with Apache License 2.0 4 votes vote down vote up
public static StatelessKieSession getNewKieSession(String drlFileName) {
	KieServices kieServices = KieServices.Factory.get();
	
	KieResources kieResources = kieServices.getResources();
	KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
	KieRepository kieRepository = kieServices.getRepository();

	Resource resource = kieResources.newFileSystemResource(drlFileName);
	kieFileSystem.write(resource);

	KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);

	kb.buildAll();

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

	KieContainer kContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
	
	return kContainer.newStatelessKieSession();
}
 
Example #21
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 2 votes vote down vote up
/**
 * Please note: the recommended way of getting a KieContainer is relying on {@link org.kie.api.KieServices KieServices} API,
 * for example: {@link org.kie.api.KieServices#newKieContainer(ReleaseId) KieServices.newKieContainer(...)}.
 * The direct manual call to KieContainerImpl constructor instead would not guarantee the consistency of the supplied containerId.
 */
public KieContainerImpl(KieProject kProject, KieRepository kr, ReleaseId containerReleaseId) {
    this("impl"+UUID.randomUUID(), kProject, kr, containerReleaseId);
}
 
Example #22
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 2 votes vote down vote up
/**
 * Please note: the recommended way of getting a KieContainer is relying on {@link org.kie.api.KieServices KieServices} API,
 * for example: {@link org.kie.api.KieServices#newKieContainer(ReleaseId) KieServices.newKieContainer(...)}.
 * The direct manual call to KieContainerImpl constructor instead would not guarantee the consistency of the supplied containerId.
 */
public KieContainerImpl(KieProject kProject, KieRepository kr) {
    this("impl"+UUID.randomUUID(), kProject, kr);
}
 
Example #23
Source File: KieServices.java    From kogito-runtimes with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the KieRepository, a singleton acting as a repository for all the available KieModules
 * @return repository
 */
KieRepository getRepository();