org.kie.api.KieServices Java Examples

The following examples show how to use org.kie.api.KieServices. 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: KieLoggersTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testKieConsoleLogger() 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";
    // get the resource
    Resource dt = ResourceFactory.newByteArrayResource( drl.getBytes() ).setTargetPath( "org/drools/integrationtests/hello.drl" );
    
    // create the builder
    KieSession ksession = getKieSession( dt );
    KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newConsoleLogger( ksession );

    ksession.insert( new Message("Hello World") );
    int fired = ksession.fireAllRules();
    assertEquals( 1, fired ); 
    
    logger.close();
}
 
Example #2
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 #3
Source File: LengthSlidingWindowTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompilationFailureWithUnknownWindow() {
    // DROOLS-841
    String drl =
            "import " + StockTick.class.getCanonicalName() + "\n" +
            "global java.util.List list;\n" +
            "declare StockTick @role( event ) end\n" +
            "declare window RhtStocksWindow\n" +
            "    StockTick() over window:length( 3 )\n" +
            "end\n" +
            "rule R\n" +
            "when \n" +
            "   accumulate( StockTick( company == \"RHT\", $price : price ) from window AbcStocksWindow; $total : sum($price) )\n"  +
            "then \n" +
            "    list.add($total);\n" +
            "end \n";

    KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
    Results results = ks.newKieBuilder( kfs ).buildAll().getResults();
    assertEquals(1, results.getMessages().size());
}
 
Example #4
Source File: HrmaxRulesTest.java    From qzr with Apache License 2.0 6 votes vote down vote up
/**
 * Each test should start with a fresh session. We also attach fresh event
 * listeners to that session, which we can use to track what rules have
 * fired and what facts have been inserted/modified/retracted.
 * 
 * @throws KieBuildException
 *             If there's a problem instantiating a new session.
 */
@Before
public void initialize() throws KieBuildException {
    if (kieSession != null) {
        kieSession.dispose();
    }

    this.kieServices = KieServices.Factory.get();
    this.kieContainer = kieServices.getKieClasspathContainer(); 
    
    this.kieSession = kieContainer.newKieSession("HrmaxSession");
    
    agendaEventListener = new TrackingAgendaEventListener();
    workingMemoryEventListener = new TrackingRuleRuntimeEventListener();

    kieSession.addEventListener(agendaEventListener);
    kieSession.addEventListener(workingMemoryEventListener);
}
 
Example #5
Source File: DeleteTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() {
    KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
    kfs.write(KieServices.Factory.get().getResources()
            .newClassPathResource(DELETE_TEST_DRL, DeleteTest.class));

    KieBuilder kbuilder = KieServices.Factory.get().newKieBuilder(kfs);
    kbuilder.buildAll();

    List<Message> res = kbuilder.getResults().getMessages(Level.ERROR);
    assertThat(res).isEmpty();

    KieBase kbase = KieServices.Factory.get()
            .newKieContainer(kbuilder.getKieModule().getReleaseId())
            .getKieBase();

    ksession = kbase.newKieSession();
}
 
Example #6
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static byte[] createJar(KieServices ks, String kmoduleContent, Predicate<String> classFilter, ReleaseId releaseId, Resource... resources) {
    KieFileSystem kfs = ks.newKieFileSystem().generateAndWritePomXML(releaseId).writeKModuleXML(kmoduleContent);
    for (int i = 0; i < resources.length; i++) {
        if (resources[i] != null) {
            kfs.write(resources[i]);
        }
    }
    KieBuilder kieBuilder = ks.newKieBuilder(kfs);
    ((InternalKieBuilder) kieBuilder).buildAll(classFilter);
    Results results = kieBuilder.getResults();
    if (results.hasMessages(Message.Level.ERROR)) {
        throw new IllegalStateException(results.getMessages(Message.Level.ERROR).toString());
    }
    InternalKieModule kieModule = (InternalKieModule) ks.getRepository()
            .getKieModule(releaseId);
    byte[] jar = kieModule.getBytes();
    return jar;
}
 
Example #7
Source File: KieHelloWorldTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testVeyifyNotExistingKieBase() throws Exception {
    // DROOLS-2757
    KieServices ks = KieServices.Factory.get();

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

    KieContainer kieContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId());
    try {
        kieContainer.verify( "notexistingKB" );
        fail("Verifying a not existing KieBase should throw a RuntimeException");
    } catch (RuntimeException e) {
        assertTrue( e.getMessage().contains( "notexistingKB" ) );
    }
}
 
Example #8
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidPomXmlGAV() throws ClassNotFoundException, InterruptedException, IOException {
    String namespace = "org.kie.test";

    KieModuleModel kProj = createKieProject(namespace);
    
    ReleaseId releaseId = new ReleaseIdImpl( "", "", "" );
    
    KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
    generatePomXML( kfs, releaseId );
    
    generateMessageClass( kfs, namespace );
    generateRule( kfs, namespace );
    
    MemoryFileSystem mfs = ((KieFileSystemImpl)kfs).asMemoryFileSystem();
      
    KieBuilder kieBuilder = createKieBuilder( kfs );
    kieBuilder.buildAll();
    assertTrue( kieBuilder.getResults().hasMessages( Level.ERROR ) );
}
 
Example #9
Source File: StrictAnnotationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnknownAnnotation() {
    String str =
            "package org.simple \n" +
            "@Xyz rule yyy \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n";

    KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem()
                          .write( "src/main/resources/r1.drl", str )
                          .writeKModuleXML(ks.newKieModuleModel()
                                             .setConfigurationProperty(LanguageLevelOption.PROPERTY_NAME,
                                                                       LanguageLevelOption.DRL6_STRICT.toString())
                                             .toXML());
    Results results = ks.newKieBuilder( kfs ).buildAll().getResults();
    assertEquals(1, results.getMessages().size());
}
 
Example #10
Source File: OOPathCastTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidCast() {
    final String drl =
            "import org.drools.compiler.oopath.model.*;\n" +
                    "global java.util.List list\n" +
                    "\n" +
                    "rule R when\n" +
                    "  Man( $toy: /wife/children#Man/toys )\n" +
                    "then\n" +
                    "  list.add( $toy.getName() );\n" +
                    "end\n";

    final KieServices ks = KieServices.Factory.get();
    final KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
    final Results results = ks.newKieBuilder( kfs ).buildAll().getResults();
    assertTrue( results.hasMessages( Message.Level.ERROR ) );
}
 
Example #11
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static KieSession marshallAndUnmarshall(KieServices ks, KieBase kbase, KieSession ksession, KieSessionConfiguration sessionConfig) {
    // Serialize and Deserialize
    try {
        Marshaller marshaller = ks.getMarshallers().newMarshaller(kbase);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        marshaller.marshall(baos, ksession);
        marshaller = MarshallerFactory.newMarshaller(kbase);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        baos.close();
        ksession = marshaller.unmarshall(bais, sessionConfig, null);
        bais.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("unexpected exception :" + e.getMessage());
    }
    return ksession;
}
 
Example #12
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 #13
Source File: KieHelloWorldTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailingHelloWorld() throws Exception {
    String drl = "package org.drools.compiler.integrationtests\n" +
            "import " + Message.class.getCanonicalName() + "\n" +
            "rule R1 when\n" +
            "   $m : Message( nonExistentField == \"Hello World\" )\n" +
            "then\n" +
            "end\n";

    KieServices ks = KieServices.Factory.get();

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

    assertEquals( 1, kb.getResults().getMessages().size() );
}
 
Example #14
Source File: KieHelloWorldTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private KieModuleModel createKieProjectWithPackagesAnd2KieBases(KieServices ks) {
    KieModuleModel kproj = ks.newKieModuleModel();

    kproj.newKieBaseModel()
            .setEqualsBehavior( EqualityBehaviorOption.EQUALITY )
            .setEventProcessingMode( EventProcessingOption.STREAM )
            .addPackage("org.pkg1")
            .newKieSessionModel("KSession1");

    kproj.newKieBaseModel()
            .setEqualsBehavior( EqualityBehaviorOption.EQUALITY )
            .setEventProcessingMode( EventProcessingOption.STREAM )
            .addPackage("org.pkg2")
            .newKieSessionModel("KSession2");

    return kproj;
}
 
Example #15
Source File: KieHelloWorldTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testHelloWorldWithWildcardPackages() throws Exception {
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId("org.kie", "hello-world", "1.0");

    KieFileSystem kfs = ks.newKieFileSystem()
            .generateAndWritePomXML( releaseId )
            .write( "src/main/resources/org/pkg1/test/r1.drl", createDrlWithGlobal( "org.pkg1.test", "R1" ) )
            .write( "src/main/resources/org/pkg2/test/r2.drl", createDrlWithGlobal( "org.pkg2.test", "R2" ) )
            .writeKModuleXML( createKieProjectWithPackages( ks, "org.pkg1.*" ).toXML() );
    ks.newKieBuilder( kfs ).buildAll();

    KieSession ksession = ks.newKieContainer(releaseId).newKieSession("KSession1");
    ksession.insert(new Message("Hello World"));

    List<String> list = new ArrayList<String>();
    ksession.setGlobal("list", list);
    assertEquals( 1, ksession.fireAllRules() );
    assertEquals( 1, list.size() );
    assertEquals( "R1", list.get( 0 ) );
}
 
Example #16
Source File: StrictAnnotationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testImportedAnnotation() {
    String str =
            "package org.simple \n" +
            "import " + Xyz.class.getCanonicalName() + " \n" +
            "@Xyz rule yyy \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n";

    KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem()
                          .write( "src/main/resources/r1.drl", str )
                          .writeKModuleXML(ks.newKieModuleModel()
                                             .setConfigurationProperty(LanguageLevelOption.PROPERTY_NAME,
                                                                       LanguageLevelOption.DRL6_STRICT.toString())
                                             .toXML());
    Results results = ks.newKieBuilder( kfs ).buildAll().getResults();
    assertEquals(0, results.getMessages().size());
}
 
Example #17
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 #18
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnknownField() throws InstantiationException, IllegalAccessException {
    // DROOLS-546
    String drl = "package org.test; " +
                 "declare Pet" +
                 " " +
                 "end \n";

    KieBuilder kieBuilder = build(drl);

    assertFalse( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );
    KieBase kieBase = KieServices.Factory.get().newKieContainer( kieBuilder.getKieModule().getReleaseId() ).getKieBase();

    FactType factType = kieBase.getFactType("org.test", "Pet");
    Object instance = factType.newInstance();
    factType.get(instance, "unknownField");
    factType.set(instance, "unknownField", "myValue");
}
 
Example #19
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 #20
Source File: StrictAnnotationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testStirctWatchWithoutQuotes() {
    String str =
            "package com.sample;\n" +
            "import " + MyClass.class.getCanonicalName() + ";\n" +
            "rule R1 when\n" +
            "    @Watch( !value ) $m : MyClass( value < 10 )\n" +
            "then \n" +
            "    modify( $m ) { setValue( $m.getValue()+1 ) };\n" +
            "end\n";

    KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem()
                          .write( "src/main/resources/r1.drl", str )
                          .writeKModuleXML(ks.newKieModuleModel()
                                             .setConfigurationProperty(LanguageLevelOption.PROPERTY_NAME,
                                                                       LanguageLevelOption.DRL6_STRICT.toString())
                                             .toXML());
    Results results = ks.newKieBuilder( kfs ).buildAll().getResults();
    assertEquals(1, results.getMessages().size());
}
 
Example #21
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeclareExtendsWithFullyQualifiedName() {
    String drl = "package org.drools.extends.test; \n" +
                 "" +
                 "declare org.drools.extends.test.Foo end \n" +
                 "declare org.drools.extends.test.Bar extends org.drools.extends.test.Foo end \n" +
                 "";
    KieServices kieServices = KieServices.Factory.get();
    KieFileSystem kfs = kieServices.newKieFileSystem();
    kfs.write( kieServices.getResources().newByteArrayResource( drl.getBytes() )
                       .setSourcePath( "test.drl" )
                       .setResourceType( ResourceType.DRL ) );
    KieBuilder kieBuilder = kieServices.newKieBuilder( kfs );
    kieBuilder.buildAll();

    assertFalse( kieBuilder.getResults().hasMessages( Message.Level.ERROR ) );

}
 
Example #22
Source File: ProtobufMarshaller.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public ReadSessionResult unmarshallWithMessage(final InputStream stream,
                                               KieSessionConfiguration config,
                                               Environment environment) throws IOException, ClassNotFoundException {
    if ( config == null ) {
        config = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    }

    if ( environment == null ) {
        environment = KieServices.get().newEnvironment();
    }

    MarshallerReaderContext context = getMarshallerReaderContext(stream, environment);
    int id = ((KnowledgeBaseImpl) this.kbase).nextWorkingMemoryCounter();
    ReadSessionResult readSessionResult = ProtobufInputMarshaller.readSession(context,
                                                                              id,
                                                                              environment,
                                                                              (SessionConfiguration) config,
                                                                              initializer);
    context.close();
    if ( ((SessionConfiguration) config).isKeepReference() ) {
        ((KnowledgeBaseImpl) this.kbase).addStatefulSession(readSessionResult.getSession());
    }
    return readSessionResult;
}
 
Example #23
Source File: UnmarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMarshallWithTimer() throws Exception {
    // DROOLS-2210
    String drl =
            "declare String @role(event) end\n" +
            "\n" +
            "rule R1 when\n" +
            "        $s : String( ) over window:time( 5s )\n" +
            "    then\n" +
            "        delete( $s );\n" +
            "end\n";

    KieBase kBase = initializeKnowledgeBase( drl );

    KieSession ksession = kBase.newKieSession();
    ksession.insert( "test" );
    assertEquals( 1, ksession.fireAllRules() );

    Marshaller marshaller = KieServices.get().getMarshallers().newMarshaller(kBase);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    marshaller.marshall( baos, ksession );

    ksession.dispose();

    ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() );
    ksession = marshaller.unmarshall( bais );
    assertEquals( 0, ksession.fireAllRules() );
}
 
Example #24
Source File: BusinessRulesBean.java    From iot-ocp with Apache License 2.0 5 votes vote down vote up
public Measure processRules(@Body Measure measure) {
	
	KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(
			kieHost, kieUser,
			kiePassword);
	
	Set<Class<?>> jaxBClasses = new HashSet<Class<?>>();
	jaxBClasses.add(Measure.class);
	
	config.addJaxbClasses(jaxBClasses);
	config.setMarshallingFormat(MarshallingFormat.JAXB);
	RuleServicesClient client = KieServicesFactory.newKieServicesClient(config)
			.getServicesClient(RuleServicesClient.class);

       List<Command<?>> cmds = new ArrayList<Command<?>>();
	KieCommands commands = KieServices.Factory.get().getCommands();
	cmds.add(commands.newInsert(measure));
	
    GetObjectsCommand getObjectsCommand = new GetObjectsCommand();
    getObjectsCommand.setOutIdentifier("objects");

	
	cmds.add(commands.newFireAllRules());
	cmds.add(getObjectsCommand);
	BatchExecutionCommand myCommands = CommandFactory.newBatchExecution(cmds,
			"DecisionTableKS");
	ServiceResponse<ExecutionResults> response = client.executeCommandsWithResults("iot-ocp-businessrules-service", myCommands);
			
	List responseList = (List) response.getResult().getValue("objects");
	
	Measure responseMeasure = (Measure) responseList.get(0);
	
	return responseMeasure;

}
 
Example #25
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 #26
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotExistingInclude() throws Exception {
    String drl = "package org.drools.compiler.integrationtests\n" +
                 "declare CancelFact\n" +
                 " cancel : boolean = true\n" +
                 "end\n" +
                 "rule R1 when\n" +
                 " $m : CancelFact( cancel == true )\n" +
                 "then\n" +
                 "end\n";

    KieServices ks = KieServices.Factory.get();

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

    KieModuleModel module = ks.newKieModuleModel();

    final String defaultBaseName = "defaultKBase";
    KieBaseModel defaultBase = module.newKieBaseModel(defaultBaseName)
                                     .addInclude( "notExistingKB1" )
                                     .addInclude( "notExistingKB2" );
    defaultBase.setDefault(true);
    defaultBase.addPackage( "*" );
    defaultBase.newKieSessionModel("defaultKSession").setDefault( true );

    kfs.writeKModuleXML( module.toXML() );
    KieBuilder kb = ks.newKieBuilder( kfs ).buildAll();
    assertEquals( 2, kb.getResults().getMessages().size() );
}
 
Example #27
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 #28
Source File: KieLoggersTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatelessKieSession getStatelessKieSession(Resource dt) {
    KieServices ks = populateKieFileSystem( dt );

    // get the session
    StatelessKieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newStatelessKieSession();
    return ksession;
}
 
Example #29
Source File: BusPassRulesTest.java    From buspass-ws with Apache License 2.0 5 votes vote down vote up
@Before
public void initialize() {
    if (kieSession != null) {
        kieSession.dispose();
    }
    this.kieServices = KieServices.Factory.get();
    this.kieContainer = kieServices.getKieClasspathContainer();
    this.kieSession = kieContainer.newKieSession("BusPassSession");
}
 
Example #30
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() );
}