Search code examples
javadroolskie

How to load rules from a string in Drools 6.5


I have a set of rules in the form of a String that are passed as an argument to my function, which is not stored in any file. From what I read so far, there are many solutions to this for versions before 6, where I am guessing APIs were very different. (They suggest using KnowledgeBase, which is deprecated in 6.5)

This is my solution so far:

KieFileSystem kfs = kService.newKieFileSystem();
Resource drlResource = ResourceFactory.newByteArrayResource(rules.getBytes());
drlResource.setResourceType(ResourceType.DRL);
kfs.write(drlResource);
KieBuilder builder = kService.newKieBuilder(kfs).buildAll();

But when I run, this is throwing an error saying:

java.lang.RuntimeException: Resource does not have neither a source nor a target path. Impossible to add it to the bundle. Please set either the source or target name of the resource before adding it.ByteArrayResource[bytes=[105, 109, 112, 111, 114, 116, 32, 106, 97, 118, ...], encoding=null]
at org.drools.compiler.kie.builder.impl.KieFileSystemImpl.write(KieFileSystemImpl.java:95)

But I do not have a source file here, how can I convert a String into a rules resource?

I am using Drools 6.5.0.Final.


Solution

  • You might use this:

    String drl = "...";
    KieServices kieServices = KieServices.Factory.get();
    KieFileSystem kfs = kieServices.newKieFileSystem();
    kfs.write( "src/main/resources/simple.drl",
        kieServices.getResources().newReaderResource( new StringReader(drl) ) );
    KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
    

    It's right there in the Drools API - one just has to find it.

    Edit Javadoc has an index where you can look up method and type names. The interfaces are

    org.kie.api.KieServices 
    org.kie.api.builder.KieFileSystem
    org.kie.api.io.KieResources
    org.kie.api.io.Resource
    

    Javadoc: "The KieFileSystem is an in-memory file system used to ..." To see how it works, look at the source code.