Search code examples
javadroolskie

Cannot find a default KieSession


I am trying to create jar using KieModule. Please have a look at the code.

public static ReleaseId createKJarWithMultipleResources(String id, String[] resourceFiles) throws IOException {
        KieServices ks = KieServices.Factory.get();
        KieModuleModel kproj = ks.newKieModuleModel();
        KieFileSystem kfs = ks.newKieFileSystem();

        for (int i = 0; i < resourceFiles.length; i++) {

            kfs.write("src/main/resources/" + id.replaceAll("\\.", "/")
                    + "/" + i + ".drl", resourceFiles[i]);
        }

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

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

        KieBuilder kieBuilder = ks.newKieBuilder(kfs).buildAll();
        Results results = kieBuilder.getResults();
            if( results.hasMessages( org.kie.api.builder.Message.Level.ERROR ) ){
                System.out.println( results.getMessages() );
                throw new IllegalStateException( "### errors ###" );
            }
        KieModule kieModule = kieBuilder.getKieModule();
        return kieModule.getReleaseId();
    }

But when I try to use the jar using the following code :

KieContainer kieContainer =
kieServices.newKieContainer(createKJarWithMultipleResources("1", 
new String[] 
{new String(Files.readAllBytes(Paths.get("path to drl file")))}
));
KieSession kSession = kieContainer.newKieSession();

I get following error :

java.lang.RuntimeException: Cannot find a default KieSession
    at org.drools.compiler.kie.builder.impl.KieContainerImpl.findKieSessionModel(KieContainerImpl.java:628)
    at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:621)
    at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:604)
    at com.sample.DroolsTest.test2(DroolsTest.java:87)

Am I missing anything? Any help will be appreciated.


Solution

  • The problem was solved. I just had to change following lines in the code :

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

    Notice the setDefault(true), this was not there in original code.