use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class MVELConsequence method evaluate.
@Override
public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
// same as lambda consequence...
Tuple tuple = knowledgeHelper.getTuple();
Declaration[] declarations = ((RuleTerminalNode) knowledgeHelper.getMatch().getTuple().getTupleSink()).getRequiredDeclarations();
Variable[] vars = consequence.getVariables();
// ...but the facts are association of Variable and its value, preserving order.
Map<Variable, Object> facts = new LinkedHashMap<>();
int declrCounter = 0;
for (Variable var : vars) {
if (var.isFact()) {
Declaration declaration = declarations[declrCounter++];
InternalFactHandle fh = tuple.get(declaration);
facts.put(var, declaration.getValue((InternalWorkingMemory) workingMemory, fh.getObject()));
} else {
facts.put(var, workingMemory.getGlobal(var.getName()));
}
}
ScriptBlock scriptBlock = null;
try {
scriptBlock = (ScriptBlock) consequence.getBlock();
} catch (ClassCastException e) {
throw new RuntimeException("I tried to access a ScriptBlock but it was not. So something is thinking is a MVEL consequence but did not set the MVEL script textual representation", e);
}
String originalRHS = scriptBlock.getScript();
String name = context.getRule().getPackageName() + "." + context.getRule().getName();
String expression = MVELConsequenceBuilder.processMacros(originalRHS);
String[] globalIdentifiers = new String[] {};
String[] default_inputIdentifiers = new String[] { "this", "drools", "kcontext", "rule" };
String[] inputIdentifiers = Stream.concat(Arrays.asList(default_inputIdentifiers).stream(), facts.entrySet().stream().map(kv -> kv.getKey().getName())).collect(Collectors.toList()).toArray(new String[] {});
String[] default_inputTypes = new String[] { "org.drools.core.spi.KnowledgeHelper", "org.drools.core.spi.KnowledgeHelper", "org.drools.core.spi.KnowledgeHelper", "org.kie.api.definition.rule.Rule" };
String[] inputTypes = Stream.concat(Arrays.asList(default_inputTypes).stream(), facts.entrySet().stream().map(kv -> kv.getKey().getType().getName())).collect(Collectors.toList()).toArray(new String[] {});
// ^^ please notice about inputTypes, it is to use the Class.getName(), because is later used by the Classloader internally in MVEL to load the class,
// do NOT replace with getCanonicalName() otherwise inner classes will not be loaded correctly.
int languageLevel = 4;
boolean strictMode = true;
boolean readLocalsFromTuple = false;
EvaluatorWrapper[] operators = new EvaluatorWrapper[] {};
Declaration[] previousDeclarations = new Declaration[] {};
Declaration[] localDeclarations = new Declaration[] {};
String[] otherIdentifiers = new String[] {};
MVELCompilationUnit cu = new MVELCompilationUnit(name, expression, globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, strictMode, readLocalsFromTuple);
// TODO unfortunately the MVELDialectRuntimeData would be the one of compile time
// the one from runtime is not helpful, in fact the dialect registry for runtime is empty:
// MVELDialectRuntimeData runtimeData = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
MVELDialectRuntimeData runtimeData = new MVELDialectRuntimeData();
// this classloader will be used by the CompilationUnit to load the imports.
runtimeData.onAdd(null, Thread.currentThread().getContextClassLoader());
runtimeData.addPackageImport(context.getPkg().getName());
runtimeData.addPackageImport("java.lang");
// therefore we assume for the ScriptBlock all available KBPackages are the default available and imported for the scope of the Script itself.
for (KiePackage kp : context.getKnowledgePackages()) {
if (!kp.getName().equals(context.getPkg().getName())) {
runtimeData.addPackageImport(kp.getName());
}
}
// sometimes here it was passed as a 2nd argument a String?? similar to `rule R in file file.drl`
Serializable cuResult = cu.getCompiledExpression(runtimeData);
ExecutableStatement compiledExpression = (ExecutableStatement) cuResult;
// TODO the part above up to the ExecutableStatement compiledExpression should be cached.
Map<String, Object> mvelContext = new HashMap<>();
mvelContext.put("this", knowledgeHelper);
mvelContext.put("drools", knowledgeHelper);
mvelContext.put("kcontext", knowledgeHelper);
mvelContext.put("rule", knowledgeHelper.getRule());
for (Entry<Variable, Object> kv : facts.entrySet()) {
mvelContext.put(kv.getKey().getName(), kv.getValue());
}
CachingMapVariableResolverFactory cachingFactory = new CachingMapVariableResolverFactory(mvelContext);
VariableResolverFactory factory = cu.getFactory(knowledgeHelper, ((AgendaItem) knowledgeHelper.getMatch()).getTerminalNode().getRequiredDeclarations(), knowledgeHelper.getRule(), knowledgeHelper.getTuple(), null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver());
cachingFactory.setNextFactory(factory);
MVEL.executeExpression(compiledExpression, knowledgeHelper, cachingFactory);
}
use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class ReteooRuleBaseMultiThreadedTest method setUp.
@Before
public void setUp() {
this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
pkg = new KnowledgePackageImpl("org.droos.test");
pkg.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
JavaDialectRuntimeData data = new JavaDialectRuntimeData();
data.onAdd(pkg.getDialectRuntimeRegistry(), kBase.getRootClassLoader());
pkg.getDialectRuntimeRegistry().setDialectData("java", data);
// we need to add one rule to the package because the previous deadlock was encountered
// while removing rules from a package when said package is removed from the rulebase
rule = new RuleImpl("Test");
rule.setDialect("java");
rule.setConsequence(new Consequence() {
public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
}
public String getName() {
return "default";
}
});
pkg.addRule(rule);
kBase.addPackage(pkg);
}
use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class RuleBaseEventSupportTest method setUp.
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Before
public void setUp() throws Exception {
kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
listener1 = new TestRuleBaseListener("(listener-1) ");
listener2 = new TestRuleBaseListener("(listener-2) ");
kBase.addEventListener(listener1);
kBase.addEventListener(listener2);
final RuleImpl rule1 = new RuleImpl("test1");
final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
final Pattern pattern = new Pattern(0, cheeseObjectType);
ClassFieldAccessorStore store = new ClassFieldAccessorStore();
store.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
store.setEagerWire(true);
final ClassFieldReader extractor = store.getReader(Cheese.class, "type");
final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");
final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);
pattern.addConstraint(constraint);
rule1.addPattern(pattern);
rule1.setConsequence(new Consequence() {
private static final long serialVersionUID = 510l;
public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public String getName() {
return "default";
}
});
final RuleImpl rule2 = new RuleImpl("test2");
final ClassObjectType cheeseObjectType2 = new ClassObjectType(Cheese.class);
final Pattern pattern2 = new Pattern(0, cheeseObjectType2);
final FieldValue field2 = FieldFactory.getInstance().getFieldValue("stilton");
final MvelConstraint constraint2 = new MvelConstraintTestUtil("type == \"stilton\"", field, extractor);
pattern2.addConstraint(constraint2);
rule2.addPattern(pattern2);
rule2.setConsequence(new Consequence() {
private static final long serialVersionUID = 510l;
public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public String getName() {
return "default";
}
});
pkg = new KnowledgePackageImpl("org.drools.test1");
pkg.addRule(rule1);
pkg.addRule(rule2);
}
use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class KnowledgeBaseEventSupportTest method setUp.
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Before
public void setUp() throws Exception {
kbase = KnowledgeBaseFactory.newKnowledgeBase();
listener1 = new TestRuleBaseListener("(listener-1) ");
listener2 = new TestRuleBaseListener("(listener-2) ");
kbase.addEventListener(listener1);
kbase.addEventListener(listener2);
final RuleImpl rule1 = new RuleImpl("test1");
final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
final Pattern pattern = new Pattern(0, cheeseObjectType);
ClassFieldAccessorStore store = new ClassFieldAccessorStore();
store.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
store.setEagerWire(true);
final ClassFieldReader extractor = store.getReader(Cheese.class, "type");
final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");
final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);
pattern.addConstraint(constraint);
rule1.addPattern(pattern);
rule1.setConsequence(new Consequence() {
private static final long serialVersionUID = 510l;
public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public String getName() {
return "default";
}
});
final RuleImpl rule2 = new RuleImpl("test2");
final ClassObjectType cheeseObjectType2 = new ClassObjectType(Cheese.class);
final Pattern pattern2 = new Pattern(0, cheeseObjectType2);
final FieldValue field2 = FieldFactory.getInstance().getFieldValue("stilton");
final MvelConstraint constraint2 = new MvelConstraintTestUtil("type == \"stilton\"", field, extractor);
pattern2.addConstraint(constraint2);
rule2.addPattern(pattern2);
rule2.setConsequence(new Consequence() {
private static final long serialVersionUID = 510l;
public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public String getName() {
return "default";
}
});
pkg = new KnowledgePackageImpl("org.drools.test1");
pkg.addRule(rule1);
pkg.addRule(rule2);
}
use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class AgendaEventSupportTest method testAgendaEventListener.
// public void testIsSerializable() {
// assertTrue( Serializable.class.isAssignableFrom( AgendaEventSupport.class ) );
// }
@Test
@Ignore
public void testAgendaEventListener() throws Exception {
InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
// create a simple package with one rule to test the events
InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools.test");
final RuleImpl rule = new RuleImpl("test1");
rule.setEager(true);
rule.setAgendaGroup("test group");
final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
final Pattern pattern = new Pattern(0, cheeseObjectType);
pkg.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
pkg.getClassFieldAccessorStore().setEagerWire(true);
final ClassFieldReader extractor = pkg.getClassFieldAccessorStore().getReader(Cheese.class, "type");
final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");
final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);
pattern.addConstraint(constraint);
rule.addPattern(pattern);
rule.setConsequence(new Consequence() {
public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public String getName() {
// TODO Auto-generated method stub
return null;
}
});
pkg.addRule(rule);
kbase.addPackages(Collections.singleton(pkg));
// create a new working memory and add an AgendaEventListener
KieSession ksession = kbase.newKieSession();
final List agendaList = new ArrayList();
final AgendaEventListener agendaEventListener = new AgendaEventListener() {
public void matchCancelled(MatchCancelledEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void matchCreated(MatchCreatedEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void afterMatchFired(AfterMatchFiredEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void agendaGroupPopped(AgendaGroupPoppedEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void agendaGroupPushed(AgendaGroupPushedEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void beforeMatchFired(BeforeMatchFiredEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void beforeRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void afterRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void beforeRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) {
assertNotNull(event.getKieRuntime());
agendaList.add(event);
}
};
ksession.addEventListener(agendaEventListener);
assertEquals(1, ksession.getAgendaEventListeners().size());
// assert the cheese fact
final Cheese cheddar = new Cheese("cheddar", 15);
FactHandle cheddarHandle = ksession.insert(cheddar);
InternalAgenda agenda = (InternalAgenda) ksession.getAgenda();
agenda.evaluateEagerList();
// should be one MatchCreatedEvent
assertEquals(1, agendaList.size());
MatchCreatedEvent createdEvent = (MatchCreatedEvent) agendaList.get(0);
assertSame(cheddarHandle, createdEvent.getMatch().getFactHandles().toArray()[0]);
// clear the agenda to check CLEAR events occur
ksession.getAgenda().clear();
MatchCancelledEvent cancelledEvent = (MatchCancelledEvent) agendaList.get(1);
assertEquals(MatchCancelledCause.CLEAR, cancelledEvent.getCause());
agendaList.clear();
// update results in an MatchCreatedEvent
cheddar.setPrice(14);
ksession.update(cheddarHandle, cheddar);
agenda.evaluateEagerList();
assertEquals(1, agendaList.size());
createdEvent = (MatchCreatedEvent) agendaList.get(0);
assertSame(cheddarHandle, createdEvent.getMatch().getFactHandles().toArray()[0]);
agendaList.clear();
// update should not result in cancelation+activation events
cheddar.setPrice(14);
ksession.update(cheddarHandle, cheddar);
assertEquals(0, agendaList.size());
// cancelledEvent = (ActivationCancelledEvent) agendaList.get( 0 );
// assertEquals( ActivationCancelledCause.WME_MODIFY, cancelledEvent.getCause() );
// assertSame( cheddarHandle,
// cancelledEvent.getActivation().toFactHandles().toArray()[0] );
// createdEvent = (ActivationCreatedEvent) agendaList.get( 1 );
// assertSame( cheddarHandle,
// createdEvent.getActivation().toFactHandles().toArray()[0] );
// agendaList.clear();
// retract results in a ActivationCancelledEvent, note the object is not resolveable now as it no longer exists
ksession.retract(cheddarHandle);
assertEquals(1, agendaList.size());
cancelledEvent = (MatchCancelledEvent) agendaList.get(0);
// invalidated handles no longer set the object to null
assertNotNull(((InternalFactHandle) cancelledEvent.getMatch().getFactHandles().toArray()[0]).getObject());
// re-assert the fact so we can test the agenda group events
cheddarHandle = ksession.insert(cheddar);
agendaList.clear();
// setFocus results in an AgendaGroupPushedEvent
ksession.getAgenda().getAgendaGroup("test group").setFocus();
assertEquals(1, agendaList.size());
final AgendaGroupPushedEvent pushedEvent = (AgendaGroupPushedEvent) agendaList.get(0);
assertEquals("test group", pushedEvent.getAgendaGroup().getName());
agendaList.clear();
// fireAllRules results in a BeforeActivationFiredEvent and an AfterActivationFiredEvent
// the AgendaGroup becomes empty, which results in a popped event.
ksession.fireAllRules();
assertEquals(3, agendaList.size());
final BeforeMatchFiredEvent beforeEvent = (BeforeMatchFiredEvent) agendaList.get(0);
assertSame(cheddarHandle, beforeEvent.getMatch().getFactHandles().toArray()[0]);
final AfterMatchFiredEvent afterEvent = (AfterMatchFiredEvent) agendaList.get(1);
assertSame(cheddarHandle, afterEvent.getMatch().getFactHandles().toArray()[0]);
final AgendaGroupPoppedEvent poppedEvent = (AgendaGroupPoppedEvent) agendaList.get(2);
assertEquals("test group", poppedEvent.getAgendaGroup().getName());
}
Aggregations