Java Code Examples for org.kie.api.KieServices#newKieModuleModel()

The following examples show how to use org.kie.api.KieServices#newKieModuleModel() . 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: KieCompilationCacheTest.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("KBase2")
            .setEqualsBehavior( EqualityBehaviorOption.EQUALITY )
            .setEventProcessingMode( EventProcessingOption.STREAM )
            .addPackage("org.pkg1")
            .newKieSessionModel("KSession1");

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

    return kproj;
}
 
Example 2
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 3
Source File: ChangeSetBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieModuleModel createKieProjectWithPackages(KieServices ks, ReleaseId releaseId) {
    KieModuleModel kproj = ks.newKieModuleModel();

    KieBaseModel kieBaseModel1 = kproj.newKieBaseModel("KBase1")
            .setEqualsBehavior( EqualityBehaviorOption.EQUALITY )
            .setEventProcessingMode( EventProcessingOption.STREAM )
            .addPackage("org.pkg1");

    KieSessionModel ksession1 = kieBaseModel1.newKieSessionModel("KSession1")
            .setType( KieSessionType.STATEFUL )
            .setClockType( ClockTypeOption.get("realtime") );

    return kproj;
}
 
Example 4
Source File: WireListenerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void build(KieServices ks, ReleaseId releaseId) throws IOException {
    KieModuleModel kproj = ks.newKieModuleModel();

    KieSessionModel ksession1 = kproj.newKieBaseModel("KBase1").newKieSessionModel("KSession1").setDefault(true);

    ksession1.newListenerModel(RecordingWorkingMemoryEventListener.class.getName(), ListenerModel.Kind.RULE_RUNTIME_EVENT_LISTENER);

    KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML(kproj.toXML())
       .writePomXML( generatePomXml(releaseId) )
       .write("src/main/resources/KBase1/rules.drl", createDRL());

    KieBuilder kieBuilder = ks.newKieBuilder(kfs);
    assertTrue(kieBuilder.buildAll().getResults().getMessages().isEmpty());
}
 
Example 5
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 6
Source File: WireChannelTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void build(KieServices ks, ReleaseId releaseId) throws IOException {
    KieModuleModel kproj = ks.newKieModuleModel();

    KieSessionModel ksession1 = kproj.newKieBaseModel("KBase1").newKieSessionModel("KSession1").setDefault(true);
    
    ksession1.newChannelModel("testChannel", RecordingChannel.class.getName());

    KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML(kproj.toXML())
       .writePomXML( generatePomXml(releaseId) )
       .write("src/main/resources/KBase1/rules.drl", createDRL());

    KieBuilder kieBuilder = ks.newKieBuilder(kfs);
    assertTrue(kieBuilder.buildAll().getResults().getMessages().isEmpty());
}
 
Example 7
Source File: ListenersTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a new KieModule containing single KieBase and a stateful and stateless KieSessions with listeners
 * into KieRepository.
 *
 * @return created KIE module ReleaseId
 */
private ReleaseId prepareKieModule() {
    final KieServices ks = KieServices.Factory.get();

    KieModuleModel module = ks.newKieModuleModel();

    KieBaseModel baseModel = module.newKieBaseModel("defaultKBase");
    baseModel.setDefault(true);
    baseModel.addPackage("*");

    KieSessionModel sessionModel = baseModel.newKieSessionModel("defaultKSession");
    sessionModel.setDefault(true);
    sessionModel.setType(KieSessionModel.KieSessionType.STATEFUL);
    sessionModel.newListenerModel(MarkingAgendaEventListener.class.getName(), ListenerModel.Kind.AGENDA_EVENT_LISTENER);
    sessionModel.newListenerModel(MarkingRuntimeEventListener.class.getName(), ListenerModel.Kind.RULE_RUNTIME_EVENT_LISTENER);

    KieSessionModel statelessSessionModel = baseModel.newKieSessionModel("defaultStatelessKSession");
    statelessSessionModel.setDefault(true);
    statelessSessionModel.setType(KieSessionModel.KieSessionType.STATELESS);
    statelessSessionModel.newListenerModel(MarkingAgendaEventListener.class.getName(), ListenerModel.Kind.AGENDA_EVENT_LISTENER);
    statelessSessionModel.newListenerModel(MarkingRuntimeEventListener.class.getName(), ListenerModel.Kind.RULE_RUNTIME_EVENT_LISTENER);

    KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML(module.toXML());
    kfs.generateAndWritePomXML(RELEASE_ID);

    kfs.write("src/main/resources/" + PACKAGE_PATH + "/test.drl",
            ResourceFactory.newByteArrayResource(DRL.getBytes()));

    KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
    assertEquals(0, builder.getResults().getMessages().size(), "Unexpected compilation errors");

    ks.getRepository().addKieModule(builder.getKieModule());

    return RELEASE_ID;
}
 
Example 8
Source File: QueryCepFireUntilHaltTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void prepare() {
    String drl = "package org.drools.compiler.integrationtests\n" + 
            "import " + TestEvent.class.getCanonicalName() + "\n" +
            "declare TestEvent\n" + 
            "    @role( event )\n" + 
            "end\n" + 
            "query EventsFromStream\n" + 
            "    $event : TestEvent() from entry-point FirstStream\n" + 
            "end\n" + 
            "query ZeroToNineteenSeconds\n" + 
            "    $event : TestEvent() from entry-point FirstStream\n" + 
            "    $result : TestEvent ( this after [0s, 19s] $event) from entry-point SecondStream\n" + 
            "end\n";
    
    final KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();
    KieModuleModel kmodule = ks.newKieModuleModel();

    KieBaseModel baseModel = kmodule.newKieBaseModel("defaultKBase")
            .setDefault(true)
            .setEventProcessingMode(EventProcessingOption.STREAM);
    baseModel.newKieSessionModel("defaultKSession")
            .setDefault(true)
            .setClockType(ClockTypeOption.get("pseudo"));

    kfs.writeKModuleXML(kmodule.toXML());
    kfs.write( ResourceFactory.newByteArrayResource(drl.getBytes())
                              .setTargetPath("org/drools/compiler/integrationtests/queries.drl") );

    assertTrue(ks.newKieBuilder(kfs).buildAll().getResults().getMessages().isEmpty());
    ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
    
    firstEntryPoint = ksession.getEntryPoint("FirstStream");
    secondEntryPoint = ksession.getEntryPoint("SecondStream"); 
    clock = ksession.getSessionClock();

    this.startEngine();
}
 
Example 9
Source File: QueryCepTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void prepare() {
    String drl = "package org.drools.compiler.integrationtests\n" +
            "import " + TestEvent.class.getCanonicalName() + "\n" +
            "declare TestEvent\n" +
            "    @role( event )\n" + 
            "end\n" + 
            "query EventsFromStream\n" + 
            "    $event : TestEvent() from entry-point FirstStream\n" + 
            "end\n" + 
            "query ZeroToNineteenSeconds\n" + 
            "    $event : TestEvent() from entry-point FirstStream\n" + 
            "    $result : TestEvent ( this after [0s, 19s] $event) from entry-point SecondStream\n" + 
            "end\n";
    
    final KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();
    KieModuleModel kmodule = ks.newKieModuleModel();

    KieBaseModel baseModel = kmodule.newKieBaseModel("defaultKBase")
            .setDefault(true)
            .setEventProcessingMode(EventProcessingOption.STREAM);
    baseModel.newKieSessionModel("defaultKSession")
            .setDefault(true)
            .setClockType(ClockTypeOption.get("pseudo"));

    kfs.writeKModuleXML(kmodule.toXML());
    kfs.write( ResourceFactory.newByteArrayResource(drl.getBytes())
                              .setTargetPath("org/drools/compiler/integrationtests/queries.drl") );

    assertTrue(ks.newKieBuilder(kfs).buildAll().getResults().getMessages().isEmpty());
    ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
    
    firstEntryPoint = ksession.getEntryPoint("FirstStream");
    secondEntryPoint = ksession.getEntryPoint("SecondStream"); 
    clock = ksession.getSessionClock();
}
 
Example 10
Source File: KieFileSystemScannerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private InternalKieModule createKieJar( KieServices ks, ReleaseId releaseId, String... rules) throws IOException {
    KieModuleModel kproj = ks.newKieModuleModel();
    KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML(kproj.toXML());
    kfs.writePomXML(getPom(releaseId));

    for (String rule : rules) {
        String file = "org/test/" + rule + ".drl";
        kfs.write("src/main/resources/KBase1/" + file, createDRL(rule));
    }

    KieBuilder kieBuilder = ks.newKieBuilder(kfs);
    assertTrue(kieBuilder.buildAll().getResults().getMessages().isEmpty());
    return (InternalKieModule) kieBuilder.getKieModule();
}
 
Example 11
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 12
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetKieBaseAfterKieSessionCreation() {
    final String KBASE_NAME = "kieBase";
    final String KSESSION_NAME = "kieSession";

    final String drl = "declare TestEvent\n" +
            "    @role( event )\n" +
            "    name : String\n" +
            "end\n" +
            "\n" +
            "declare window DeclaredTimeWindow\n" +
            "    TestEvent ( name == \"timeDec\" ) over window:time( 50ms ) from entry-point EventStream\n" +
            "end";

    final KieServices ks = KieServices.Factory.get();
    final KieFileSystem kfs = ks.newKieFileSystem();

    kfs.write( "src/main/resources/window.drl", drl );

    final KieModuleModel kmoduleModel = ks.newKieModuleModel();
    kmoduleModel.newKieBaseModel( KBASE_NAME )
            .addPackage( "*" )
            .newKieSessionModel( KSESSION_NAME )
            .setDefault( true )
            .setClockType( ClockTypeOption.get( "pseudo" ) );

    kfs.writeKModuleXML( kmoduleModel.toXML() );

    final KieBuilder builder = ks.newKieBuilder( kfs ).buildAll();
    assertEquals( 0, builder.getResults().getMessages().size() );
    ks.getRepository().addKieModule( builder.getKieModule() );

    final KieSession kieSession = ks.newKieContainer( ks.getRepository().getDefaultReleaseId() ).newKieSession( KSESSION_NAME );
    assertNotNull( kieSession );

    final KieBase kieBase = ks.newKieContainer( ks.getRepository().getDefaultReleaseId() ).getKieBase( KBASE_NAME );
    assertNotNull( kieBase );
}
 
Example 13
Source File: MTEntryPointsTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void initSession() {
    String str = "package org.jboss.brms\n" +
                 "\n" +
                 "import org.drools.compiler.integrationtests.MTEntryPointsTest.MessageEvent\n" +
                 "\n" +
                 "declare MessageEvent\n" +
                 "    @role( event )\n" +
                 "end\n" +
                 "\n" +
                 "rule \"sum of last event from first entry point\"\n" +
                 "    when\n" +
                 "\t    accumulate (\n" +
                 "\t        MessageEvent ($value : value) over window:length(1) from entry-point \"FirstStream\",\n" +
                 "\t        $sum : sum($value)\n" +
                 "\t    )\n" +
                 "    then\n" +
                 "end\n" +
                 "\n" +
                 "rule \"sum of last event from both entry points\"\n" +
                 "    when\n" +
                 "        accumulate (\n" +
                 "            MessageEvent ($value1 : value) over window:length(1) from entry-point \"FirstStream\",\n" +
                 "            $thirdSum1 : sum($value1)\n" +
                 "        )\n" +
                 "        accumulate (\n" +
                 "            MessageEvent ($value2 : value) over window:length(1) from entry-point \"SecondStream\",\n" +
                 "            $thirdSum2 : sum($value2)\n" +
                 "        )\n" +
                 "    then\n" +
                 "end\n" +
                 "\n";

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

    KieModuleModel kmoduleModel = ks.newKieModuleModel();
    kmoduleModel.newKieBaseModel("defaultKieBase")
                .addPackage("*")
                .setEventProcessingMode(EventProcessingOption.STREAM)
                .newKieSessionModel("defaultKieSession")
                .setDefault(true)
                .setClockType(ClockTypeOption.get("pseudo"));
    kfs.writeKModuleXML(kmoduleModel.toXML());

    KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
    assertEquals(0, builder.getResults().getMessages().size());
    ks.getRepository().addKieModule(builder.getKieModule());

    this.kieSession = ks.newKieContainer(ks.getRepository()
                                           .getDefaultReleaseId()).newKieSession();
}
 
Example 14
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrossPackageDeclares() {
    String pkg1 =
            "package org.drools.compiler.test1; " +
            "import org.drools.compiler.test2.GrandChild; " +
            "import org.drools.compiler.test2.Child; " +
            "import org.drools.compiler.test2.BarFuu; " +

            "declare FuBaz foo : String end " +

            "declare Parent " +
            "   unknown : BarFuu " +
            "end " +

            "declare GreatChild extends GrandChild " +
            "   father : Child " +
            "end "
            ;

    String pkg2 =
            "package org.drools.compiler.test2; " +
            "import org.drools.compiler.test1.Parent; " +
            "import org.drools.compiler.test1.FuBaz; " +

            "declare BarFuu " +
            "   baz : FuBaz " +
            "end " +

            "declare Child extends Parent " +
            "end " +

            "declare GrandChild extends Child " +
            "   notknown : FuBaz " +
            "end "
            ;

    KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();

    kfs.generateAndWritePomXML( ks.newReleaseId( "test", "foo", "1.0" ) );
    KieModuleModel km = ks.newKieModuleModel();
    km.newKieBaseModel( "rules" )
            .addPackage( "org.drools.compiler.test2" )
            .addPackage( "org.drools.compiler.test1" );
    kfs.writeKModuleXML( km.toXML() );

    KieResources kr = ks.getResources();
    Resource r1 = kr.newByteArrayResource( pkg1.getBytes() )
            .setResourceType( ResourceType.DRL )
            .setSourcePath( "org/drools/compiler/test1/p1.drl" );
    Resource r2 = kr.newByteArrayResource( pkg2.getBytes() )
            .setResourceType( ResourceType.DRL )
            .setSourcePath( "org/drools/compiler/test2/p2.drl" );

    kfs.write( r1 );
    kfs.write( r2 );

    KieBuilder builder = ks.newKieBuilder( kfs );
    builder.buildAll();

    assertEquals( Collections.emptyList(), builder.getResults().getMessages( Message.Level.ERROR ) );

    KieContainer kc = ks.newKieContainer(builder.getKieModule().getReleaseId());
    FactType ft = kc.getKieBase( "rules" ).getFactType( "org.drools.compiler.test2", "Child" );

    assertNotNull( ft );
    assertNotNull( ft.getFactClass() );
    assertEquals( "org.drools.compiler.test1.Parent", ft.getFactClass().getSuperclass().getName() );
}
 
Example 15
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testKieBuilderWithDotFiles() {
    // BZ-1044409
    final String KBASE_NAME = "kieBase";
    final String KSESSION_NAME = "kieSession";

    //This can be any DRL, or any file recognised by drools-compiler
    final String drl = "declare TestEvent\n" +
            "  name : String\n" +
            "end\n";

    final String dotDrl = "Meta-data used by kie-wb";

    final KieServices ks = KieServices.Factory.get();
    final KieFileSystem kfs = ks.newKieFileSystem();

    kfs.write( "src/main/resources/drlFile.drl", drl );
    kfs.write( "src/main/resources/.drlFile.drl", dotDrl );

    final KieModuleModel kmoduleModel = ks.newKieModuleModel();
    kmoduleModel.newKieBaseModel( KBASE_NAME )
            .addPackage( "*" )
            .newKieSessionModel( KSESSION_NAME )
            .setDefault( true );

    kfs.writeKModuleXML( kmoduleModel.toXML() );

    final KieBuilder builder = ks.newKieBuilder( kfs ).buildAll();
    for ( final org.kie.api.builder.Message m : builder.getResults().getMessages() ) {
        System.out.println( m );
    }
    assertEquals( 0, builder.getResults().getMessages().size() );

    ks.getRepository().addKieModule( builder.getKieModule() );

    final KieSession kieSession = ks.newKieContainer( ks.getRepository().getDefaultReleaseId() ).newKieSession( KSESSION_NAME );
    assertNotNull( kieSession );

    final KieBase kieBase = ks.newKieContainer( ks.getRepository().getDefaultReleaseId() ).getKieBase( KBASE_NAME );
    assertNotNull( kieBase );
}
 
Example 16
Source File: KieHelloWorldTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeclarativeCalendars() {
    String weekendCalendarSource =
            "package org.mypackage;\n" +
            "\n" +
            "public class WeekendCalendar implements org.kie.api.time.Calendar {\n" +
            "        @Override\n" +
            "        public boolean isTimeIncluded( long timestamp ) {\n" +
            "            java.util.Calendar c = java.util.Calendar.getInstance();\n" +
            "            c.setTimeInMillis(timestamp);\n" +
            "            final int day = c.get(java.util.Calendar.DAY_OF_WEEK);\n" +
            "            return day == java.util.Calendar.SATURDAY || day == java.util.Calendar.SUNDAY;\n" +
            "        }\n" +
            "    }";

    String weekdayCalendarSource =
            "package org.mypackage;\n" +
            "\n" +
            "public class WeekdayCalendar implements org.kie.api.time.Calendar {\n" +
            "        @Override\n" +
            "        public boolean isTimeIncluded( long timestamp ) {\n" +
            "            java.util.Calendar c = java.util.Calendar.getInstance();\n" +
            "            c.setTimeInMillis(timestamp);\n" +
            "            final int day = c.get(java.util.Calendar.DAY_OF_WEEK);\n" +
            "            return day != java.util.Calendar.SATURDAY && day != java.util.Calendar.SUNDAY;\n" +
            "        }\n" +
            "    }";

    String drl =
            "package org.mypackage;\n" +
            "\n" +
            "global java.util.List list\n" +
            " \n" +
            "rule \"weekend\"\n" +
            "    calendars \"weekend\"\n" +
            "    \n" +
            "    when\n" +
            "    then\n" +
            "        list.add(\"weekend\");\n" +
            "end\n" +
            " \n" +
            "rule \"weekday\"\n" +
            "    calendars \"weekday\"\n" +
            "\n" +
            "    when\n" +
            "    then\n" +
            "       list.add(\"weekday\");\n" +
            "end";

    KieServices ks = KieServices.Factory.get();

    ReleaseId releaseId = ks.newReleaseId( "org.kie", "hello-calendar", "1.0" );

    KieModuleModel kproj = ks.newKieModuleModel();

    kproj.newKieBaseModel().newKieSessionModel("KSession1")
            .addCalendar( "weekend", "org.mypackage.WeekendCalendar" )
            .addCalendar( "weekday", "org.mypackage.WeekdayCalendar" )
            .setDefault( true );

    KieFileSystem kfs = ks.newKieFileSystem()
            .generateAndWritePomXML(releaseId)
            .write("src/main/resources/org/mypackage/r1.drl", drl)
            .write("src/main/java/org/mypackage/WeekendCalendar.java", weekendCalendarSource)
            .write("src/main/java/org/mypackage/WeekdayCalendar.java", weekdayCalendarSource)
            .writeKModuleXML(kproj.toXML());
    ks.newKieBuilder( kfs ).buildAll();

    KieSession ksession = ks.newKieContainer(releaseId).newKieSession("KSession1");

    ArrayList<String> list = new ArrayList<>();
    ksession.setGlobal("list", list);

    ksession.fireAllRules();
    ksession.dispose();

    assertEquals(1, list.size());
}
 
Example 17
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testFiredRuleDoNotRefireAfterUnblock() {
    // BZ-1038076
    String drl =
            "package org.drools.compiler.integrationtests\n" +
            "\n" +
            "import org.kie.api.runtime.rule.Match\n" +
            "import java.util.List\n" +
            "\n" +
            "global List list\n" +
            "\n" +
            "rule startAgenda\n" +
            "salience 100\n" +
            "when\n" +
            "    String( this == 'startAgenda' )\n" +
            "then\n" +
            "    drools.getKnowledgeRuntime().getAgenda().getAgendaGroup(\"agenda\").setFocus();\n" +
            "    list.add(kcontext.getRule().getName());\n" +
            "end\n" +
            "\n" +
            "rule sales @department('sales')\n" +
            "agenda-group \"agenda\"\n" +
            "when\n" +
            "    $s : String( this == 'fireRules' )\n" +
            "then\n" +
            "    list.add(kcontext.getRule().getName());\n" +
            "end\n" +
            "\n" +
            "rule salesBlocker salience 10\n" +
            "when\n" +
            "    $s : String( this == 'fireBlockerRule' )\n" +
            "    $i : Match( department == 'sales' )\n" +
            "then\n" +
            "    kcontext.blockMatch( $i );\n" +
            "    list.add(kcontext.getRule().getName());\n" +
            "end\n";

    final KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();
    KieModuleModel kmodule = ks.newKieModuleModel();

    KieBaseModel baseModel = kmodule.newKieBaseModel("defaultKBase")
                                    .setDefault(true)
                                    .setDeclarativeAgenda(DeclarativeAgendaOption.ENABLED);
    baseModel.newKieSessionModel("defaultKSession")
             .setDefault(true);

    kfs.writeKModuleXML(kmodule.toXML());
    kfs.write("src/main/resources/block_rule.drl", drl);
    KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll();
    assertEquals( 0, kieBuilder.getResults().getMessages( org.kie.api.builder.Message.Level.ERROR ).size() );

    KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();

    List<String> list = new DebugList<String>();

    ksession.setGlobal("list", list);

    // first run
    ksession.insert("startAgenda");
    ksession.insert("fireRules");
    FactHandle fireBlockerRule = ksession.insert("fireBlockerRule");
    ksession.fireAllRules();
    String[] expected = { "startAgenda", "sales", "salesBlocker" };

    assertEquals(expected.length, list.size());
    for (int i = 0; i < list.size(); i++) {
        assertEquals(expected[i], list.get(i));
    }

    // second run
    ksession.delete(fireBlockerRule);
    list.clear();
    ksession.fireAllRules();
    assertEquals(0, list.size());

    ksession.dispose();
    list.clear();
}
 
Example 18
Source File: KieHelloWorldTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testHelloWorldWithKBaseInclude() 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();

    // define first kbase
    final String defaultBaseName = "defaultKBase";
    KieBaseModel defaultBase = module.newKieBaseModel(defaultBaseName);
    defaultBase.setDefault(true);
    defaultBase.addPackage("*");
    defaultBase.newKieSessionModel("defaultKSession").setDefault(true);

    // define second kbase including resources of the first one
    final String includingBaseName = "includingKBase";
    KieBaseModel includingBase = module.newKieBaseModel(includingBaseName);
    includingBase.setDefault(false);
    includingBase.addInclude(defaultBaseName);
    includingBase.newKieSessionModel("includingKSession").setDefault(false);

    kfs.writeKModuleXML(module.toXML());
    KieBuilder kb = ks.newKieBuilder( kfs ).buildAll();
    assertEquals( 0, kb.getResults().getMessages().size() );

    KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
    FactType factType = ksession.getKieBase().getFactType("org.drools.compiler.integrationtests", "CancelFact");
    assertNotNull(factType);
    ksession.insert(factType.newInstance());

    int count = ksession.fireAllRules();

    assertEquals( 1, count );
}
 
Example 19
Source File: QueryInRHSCepTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void withInsertBeforeQueryCloudTest() {
	String drl = "package org.drools.compiler.integrationtests\n" +
            "import " + SolicitFirePojo.class.getCanonicalName() + "\n" +
            "import " + QueryItemPojo.class.getCanonicalName() + "\n" +
            "global java.util.List myGlobal \n"+
            "query \"myQuery\"\n" + 
            "    $r : QueryItemPojo()\n" + 	
            "end\n" + 
            "rule \"drools-usage/WLHxG8S\"\n" +
            " no-loop\n" +
            " when\n" +
            " SolicitFirePojo()\n" +
            " then\n" +
            " insert(new QueryItemPojo());\n" +
            " myGlobal.add(drools.getKieRuntime().getQueryResults(\"myQuery\"));\n"+
            " end\n";
    System.out.println(drl);
    final KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();
    KieModuleModel kmodule = ks.newKieModuleModel();

    KieBaseModel baseModel = kmodule.newKieBaseModel("defaultKBase")
            .setDefault(true)
            .setEventProcessingMode(EventProcessingOption.CLOUD)
            ;
    baseModel.newKieSessionModel("defaultKSession")
            .setDefault(true)
            ;

    kfs.writeKModuleXML(kmodule.toXML());
    kfs.write( ResourceFactory.newByteArrayResource(drl.getBytes())
                              .setTargetPath("org/drools/compiler/integrationtests/"+this.getClass().getName()+".drl") );

    assertTrue(ks.newKieBuilder(kfs).buildAll().getResults().getMessages().isEmpty());
    ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
    
    myGlobal = new ArrayList<>();
    ksession.setGlobal("myGlobal", myGlobal);
    
    ksession.insert(new QueryItemPojo());
    ksession.insert(new SolicitFirePojo());
    int fired = ksession.fireAllRules();
    assertEquals(1, fired);
    assertEquals(1, myGlobal.size());
    assertEquals(2, ((QueryResults) myGlobal.get(0)).size()); // notice 1 is manually inserted, 1 get inserted from rule's RHS, for a total of 2.
}
 
Example 20
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testEmptyProjectXml() throws ClassNotFoundException, InterruptedException, IOException {
    String namespace = "org.kie.test";
    
    KieServices ks = KieServices.Factory.get();
    
    KieModuleModel kProj = ks.newKieModuleModel();
    
    
    ReleaseId releaseId = KieServices.Factory.get().newReleaseId(namespace, "memory", "1.0");
    
    KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
    generateKProjectXML( kfs, namespace, kProj );
    generatePomXML(kfs, releaseId);
    generateMessageClass( kfs, namespace );
    generateRule( kfs, namespace );
    
    MemoryFileSystem mfs = ((KieFileSystemImpl)kfs).asMemoryFileSystem();
           
    createAndTestKieContainer(releaseId, createKieBuilder(kfs), null );
}