我不知道这是否是“接受”的方式,但是通过以下代码,我在Drools 6中使用以编程方式创建的规则进行文件。.drl
public KieContainer build(KieServices kieServices) {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
ReleaseId rid = kieServices.newReleaseId("com.example.rulesengine",
"model-test", "1.0-SNAPSHOT");
kieFileSystem.generateAndWritePomXML(rid);
kieFileSystem.write("src/main/resources/rules.drl",
getResource(kieServices, "rules.drl"));
addRule(kieFileSystem);
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
kieBuilder.buildAll();
if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
throw new RuntimeException("Build Errors:\n" +
kieBuilder.getResults().toString());
}
return kieServices.newKieContainer(rid);
}
private void addRule(KieFileSystem kieFileSystem) {
PackageDescrBuilder packageDescrBuilder = DescrFactory.newPackage();
packageDescrBuilder
.name("com.example.model")
.newRule()
.name("Is of valid age")
.lhs()
.pattern("Person").constraint("age < 18").end()
.pattern().id("$a", false).type("Action").end()
.end()
.rhs("$a.showBanner( false );")
.end();
String rules = new DrlDumper().dump(packageDescrBuilder.getDescr());
kieFileSystem.write("src/main/resources/rule-1.drl", rules);
}
private Resource getResource(KieServices kieServices, String resourcePath) {
try {
InputStream is = Resources.getResource(resourcePath).openStream(); //guava
return kieServices.getResources()
.newInputStreamResource(is)
.setResourceType(ResourceType.DRL);
} catch (IOException e) {
throw new RuntimeException("Failed to load drools resource file.", e);
}
}
我使用番石榴资源类。