Skip to content

Commit

Permalink
chapter7 add rule template array demo
Browse files Browse the repository at this point in the history
  • Loading branch information
secbr committed Jan 26, 2019
1 parent efa1b47 commit aec31c3
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
26 changes: 26 additions & 0 deletions drools-lesson2/src/main/java/com/secbro2/drools/demo/BaseDemo.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package com.secbro2.drools.demo;

import org.kie.api.KieServices;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;

import java.util.List;

/**
* @author zzs
Expand All @@ -20,4 +26,24 @@ protected static KieSession getKieSession(String sessionName) {
KieContainer container = kieServices.getKieClasspathContainer();
return container.newKieSession(sessionName);
}

protected static KieSession getKieSessionByDrl(String drlContent) {

KieHelper kieHelper = new KieHelper();
kieHelper.addContent(drlContent, ResourceType.DRL);

Results verify = kieHelper.verify();
boolean hasMessages = verify.hasMessages(Message.Level.WARNING, Message.Level.ERROR);
if (hasMessages) {
List<Message> messages = verify.getMessages(Message.Level.WARNING, Message.Level.ERROR);
for (Message message : messages) {
System.out.println("ERROR : " + message.getText());
}

throw new RuntimeException("verify has errors!");
}

return kieHelper.build().newKieSession();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.secbro2.drools.demo;

import org.drools.template.DataProvider;
import org.drools.template.DataProviderCompiler;
import org.drools.template.objects.ArrayDataProvider;
import org.kie.api.runtime.KieSession;

import java.io.InputStream;

/**
* @author zzs
*/
public class RuleTemplateArrayDemo extends BaseDemo {


public static void main(String[] args) {

InputStream template = RuleTemplateArrayDemo.class.getResourceAsStream("/com/template/template.drt");

DataProvider dataProvider = new ArrayDataProvider(new String[][]{
{"1", "Tom"}, {"2", "Lucy"}
});

DataProviderCompiler compiler = new DataProviderCompiler();

String drl = compiler.compile(dataProvider, template);

KieSession kieSession = getKieSessionByDrl(drl);

Person person = new Person(1,"");

kieSession.insert(person);

kieSession.fireAllRules();

System.out.println("Person's username is " + person.getUsername());


}

}
Binary file modified drools-lesson2/src/main/resources/com/template/template.xls
Binary file not shown.

0 comments on commit aec31c3

Please sign in to comment.