我在运行Java程序时遇到空指针异常
addPackageFromDrl
无法正常工作,因此从builder.getPackage()
返回的pkg为空。
我正在使用Drools 6
private static RuleBase readRules() throws DroolsParserException, IOException {
Reader source = new InputStreamReader(
MessageDroolsTest1.class.getClassLoader().getResourceAsStream( "rule.drl" ) );
System.out.println("Source:" + source);
PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( source );
System.out.println("Builder:" + builder);
Package pkg = builder.getPackage();
System.out.println("Package:" + pkg);
RuleBase ruleBase = RuleBaseFactory.newRuleBase();
ruleBase.addPackage( pkg );
return ruleBase;
}
我尝试了另一种方法,但仍然遇到运行时异常。
private static KnowledgeBase createKnowledgeBase() {
KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
//Add drl file into builder
File drl = new File("rules.drl");
builder.add(ResourceFactory.newFileResource(drl), ResourceType.DRL);
if (builder.hasErrors()) {
throw new RuntimeException(builder.getErrors().toString());
}
KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
//Add to Knowledge Base packages from the builder which are actually the rules from the drl file.
knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages());
return knowledgeBase;
}
错误
Exception in thread "main" org.drools.RuntimeDroolsException:
Unable to load dialect 'org.drools.rule.builder.dialect.java.JavaDialectConfiguration:
java:org.drools.rule.builder.dialect.java.JavaDialectConfiguration'
答案 0 :(得分:0)
这对我有用,至少对于正确的DRL文件。
我建议您添加
System.out.println("Builder:" + builder);
if( builder.hasErrors() ){
System.out.println("Builder has errors!");
}
如果这表明存在错误,请使用其他方法检索消息。
Drools 6引入了一整套新类(Knowledge *),您应该使用它。建议不要使用内部API(或Drools 5中使用的内容),并且您的代码可能会因任何版本更改而中断。
**后来**
6.x的简单构建过程:
public void build() throws Exception {
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
FileInputStream fis = new FileInputStream( "simple.drl" );
kfs.write( "src/main/resources/simple.drl",
kieServices.getResources().newInputStreamResource( fis ) );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
System.out.println( results.getMessages() );
throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
kieServices.newKieContainer( kieServices.getRepository().getDefaultReleaseId() );
KieBase kieBase = kieContainer.getKieBase();
kieSession = kieContainer.newKieSession();
}