问题
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.
回答1:
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.
回答2:
Hidden in the Drools code on GitHub there is a simple example which also shows you how to do this - it helped me to get it working: KieFileSystem example on GitHub
回答3:
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
kSession.insert(createCommlObject());
If you do a buildAll() as mentioned in Laune's answer, kie module will load all .drl files. If you want to load the .drl file of your choice then use
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("Rules.drl"), ResourceType.DRL);
来源:https://stackoverflow.com/questions/42927331/how-to-load-rules-from-a-string-in-drools-6-5