use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class MarshallingTest method testScheduledActivation.
@Test
@Ignore("This test is suspicious to say the least...")
public void testScheduledActivation() {
KnowledgeBaseImpl knowledgeBase = (KnowledgeBaseImpl) KnowledgeBaseFactory.newKnowledgeBase();
KnowledgePackageImpl impl = new KnowledgePackageImpl("test");
BuildContext buildContext = new BuildContext(knowledgeBase);
// simple rule that fires after 10 seconds
final RuleImpl rule = new RuleImpl("test-rule");
new RuleTerminalNode(1, new MockTupleSource(2), rule, rule.getLhs(), 0, buildContext);
final List<String> fired = new ArrayList<String>();
rule.setConsequence(new Consequence() {
public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
fired.add("a");
}
public String getName() {
return "default";
}
});
rule.setTimer(new DurationTimer(10000));
rule.setPackage("test");
impl.addRule(rule);
knowledgeBase.addPackages(Collections.singleton(impl));
SessionConfiguration config = SessionConfiguration.newInstance();
config.setClockType(ClockType.PSEUDO_CLOCK);
KieSession ksession = knowledgeBase.newKieSession(config, KieServices.get().newEnvironment());
PseudoClockScheduler scheduler = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock();
Marshaller marshaller = MarshallerFactory.newMarshaller(knowledgeBase);
ksession.insert("cheese");
assertTrue(fired.isEmpty());
// marshall, then unmarshall session
readWrite(knowledgeBase, ksession, config);
// the activations should fire after 10 seconds
assertTrue(fired.isEmpty());
scheduler.advanceTime(12, TimeUnit.SECONDS);
assertFalse(fired.isEmpty());
}
use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class Misc2Test method testCustomDynamicSalience.
@Test
public void testCustomDynamicSalience() {
String drl = "package org.drools.test; " + "import " + Person.class.getName() + "; " + "global java.util.List list; " + "rule A " + "when " + " $person : Person( name == 'a' ) " + "then" + " list.add( $person.getAge() ); " + "end " + "rule B " + "when " + " $person : Person( name == 'b' ) " + "then" + " list.add( $person.getAge() ); " + "end " + "";
KieHelper helper = new KieHelper();
helper.addContent(drl, ResourceType.DRL);
KieSession session = helper.build().newKieSession();
List<Integer> list = new ArrayList<Integer>();
session.setGlobal("list", list);
for (Rule r : session.getKieBase().getKiePackage("org.drools.test").getRules()) {
((RuleImpl) r).setSalience(new Salience() {
@Override
public int getValue(KnowledgeHelper khelper, Rule rule, WorkingMemory workingMemory) {
if (khelper == null) {
return 0;
}
InternalFactHandle h = (InternalFactHandle) khelper.getMatch().getFactHandles().get(0);
return ((Person) h.getObject()).getAge();
}
@Override
public int getValue() {
throw new IllegalStateException("Should not have been called...");
}
@Override
public boolean isDynamic() {
return true;
}
});
}
session.insert(new Person("a", 1));
session.insert(new Person("a", 5));
session.insert(new Person("a", 3));
session.insert(new Person("b", 4));
session.insert(new Person("b", 2));
session.insert(new Person("b", 6));
session.fireAllRules();
assertEquals(Arrays.asList(6, 5, 4, 3, 2, 1), list);
}
use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class DisposeCommandPublicAPITest method testDisposeCommand.
@Test
public void testDisposeCommand() {
InternalKnowledgeBase kBase;
RuleImpl rule;
InternalKnowledgePackage pkg;
kBase = 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);
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);
KieSession session = kBase.newKieSession();
Command dispose = KieServices.Factory.get().getCommands().newDispose();
session.insert("whatever");
session.fireAllRules();
session.execute(dispose);
try {
session.insert("whatever");
} catch (Exception e) {
Assert.assertEquals(e.getMessage(), "Illegal method call. This session was previously disposed.");
}
}
use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class ASMConsequenceBuilder method createConsequenceBytecode.
protected byte[] createConsequenceBytecode(RuleBuildContext ruleContext, final Map<String, Object> consequenceContext) {
final InvokerDataProvider data = new InvokerContext(consequenceContext);
final String name = (String) consequenceContext.get("consequenceName");
final Declaration[] declarations = (Declaration[]) consequenceContext.get("declarations");
final ClassGenerator generator = InvokerGenerator.createInvokerClassGenerator(data, ruleContext).setInterfaces(Consequence.class, CompiledInvoker.class);
generator.addMethod(ACC_PUBLIC, "getName", generator.methodDescr(String.class), new ClassGenerator.MethodBody() {
public void body(MethodVisitor mv) {
push(name);
mv.visitInsn(ARETURN);
}
}).addMethod(ACC_PUBLIC, "evaluate", generator.methodDescr(null, KnowledgeHelper.class, WorkingMemory.class), new String[] { "java/lang/Exception" }, new GeneratorHelper.EvaluateMethod() {
public void body(MethodVisitor mv) {
// Tuple tuple = knowledgeHelper.getTuple();
mv.visitVarInsn(ALOAD, 1);
invokeInterface(KnowledgeHelper.class, "getTuple", Tuple.class);
mv.visitVarInsn(ASTORE, 3);
// Declaration[] declarations = ((RuleTerminalNode)knowledgeHelper.getMatch().getTuple().getTupleSink()).getDeclarations();
mv.visitVarInsn(ALOAD, 1);
invokeInterface(KnowledgeHelper.class, "getMatch", Activation.class);
invokeInterface(Activation.class, "getTuple", Tuple.class);
invokeInterface(Tuple.class, "getTupleSink", Sink.class);
cast(RuleTerminalNode.class);
invokeVirtual(RuleTerminalNode.class, "getRequiredDeclarations", Declaration[].class);
mv.visitVarInsn(ASTORE, 4);
final String[] globals = data.getGlobals();
final String[] globalTypes = data.getGlobalTypes();
final Boolean[] notPatterns = (Boolean[]) consequenceContext.get("notPatterns");
int[] paramsPos = new int[declarations.length];
int offset = 5;
for (int i = 0; i < declarations.length; i++) {
int factPos = offset;
int objPos = ++offset;
paramsPos[i] = factPos;
// Object obj[i] = tuple.get(declarations[i]);
// org.kie.spi.Tuple
mv.visitVarInsn(ALOAD, 3);
// org.kie.rule.Declaration[]
mv.visitVarInsn(ALOAD, 4);
// i
push(i);
// declarations[i]
mv.visitInsn(AALOAD);
invokeInterface(Tuple.class, "get", InternalFactHandle.class, Declaration.class);
// fact[i]
mv.visitVarInsn(ASTORE, factPos);
// declarations[i].getValue((org.kie.common.InternalWorkingMemory)workingMemory, obj[i] );
// org.kie.rule.Declaration[]
mv.visitVarInsn(ALOAD, 4);
// i
push(i);
// declarations[i]
mv.visitInsn(AALOAD);
// WorkingMemory
mv.visitVarInsn(ALOAD, 2);
cast(InternalWorkingMemory.class);
// fact[i]
mv.visitVarInsn(ALOAD, factPos);
invokeInterface(InternalFactHandle.class, "getObject", Object.class);
String readMethod = declarations[i].getNativeReadMethodName();
boolean isObject = readMethod.equals("getValue");
String returnedType = isObject ? "Ljava/lang/Object;" : typeDescr(declarations[i].getTypeName());
mv.visitMethodInsn(INVOKEVIRTUAL, Declaration.class.getName().replace('.', '/'), readMethod, "(L" + InternalWorkingMemory.class.getName().replace('.', '/') + ";Ljava/lang/Object;)" + returnedType);
if (isObject)
mv.visitTypeInsn(CHECKCAST, internalName(declarations[i].getTypeName()));
// obj[i]
offset += store(objPos, declarations[i].getTypeName());
if (notPatterns[i]) {
mv.visitVarInsn(ALOAD, 1);
invokeInterface(KnowledgeHelper.class, "getWorkingMemory", WorkingMemory.class);
loadAsObject(objPos);
invokeInterface(WorkingMemory.class, "getFactHandle", FactHandle.class, Object.class);
cast(InternalFactHandle.class);
mv.visitVarInsn(ASTORE, factPos);
}
}
// @{ruleClassName}.@{methodName}(KnowledgeHelper, @foreach{declr : declarations} Object, FactHandle @end)
StringBuilder consequenceMethodDescr = new StringBuilder("(L" + KnowledgeHelper.class.getName().replace('.', '/') + ";");
// KnowledgeHelper
mv.visitVarInsn(ALOAD, 1);
for (int i = 0; i < declarations.length; i++) {
// obj[i]
load(paramsPos[i] + 1);
// fact[i]
mv.visitVarInsn(ALOAD, paramsPos[i]);
consequenceMethodDescr.append(typeDescr(declarations[i].getTypeName())).append("L" + FactHandle.class.getName().replace('.', '/') + ";");
}
// @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" );
for (int i = 0; i < globals.length; i++) {
// WorkingMemory
mv.visitVarInsn(ALOAD, 2);
push(globals[i]);
invokeInterface(WorkingMemory.class, "getGlobal", Object.class, String.class);
mv.visitTypeInsn(CHECKCAST, internalName(globalTypes[i]));
consequenceMethodDescr.append(typeDescr(globalTypes[i]));
}
consequenceMethodDescr.append(")V");
mv.visitMethodInsn(INVOKESTATIC, data.getInternalRuleClassName(), data.getMethodName(), consequenceMethodDescr.toString());
mv.visitInsn(RETURN);
}
});
return generator.generateBytecode();
}
use of org.drools.core.spi.KnowledgeHelper in project drools by kiegroup.
the class BaseMannersTest method getContinueProcessing.
/**
* <pre>
* rule continue() {
* Context context;
* when {
* context : Context( state == Context.CHECK_DONE )
* } then {
* context.setState( Context.ASSIGN_SEATS );
* }
* }
* </pre>
* @return
* @throws InvalidRuleException
*/
private RuleImpl getContinueProcessing() throws InvalidRuleException {
final RuleImpl rule = new RuleImpl("continueProcessng");
// -----------
// context : Context( state == Context.CHECK_DONE )
// -----------
final Pattern contextPattern = new Pattern(0, this.contextType, "context");
contextPattern.addConstraint(getLiteralConstraint(contextPattern, "state", Context.CHECK_DONE));
rule.addPattern(contextPattern);
final Declaration contextDeclaration = rule.getDeclaration("context");
// ------------
// context.setName( Context.ASSIGN_SEATS );
// ------------
final Consequence consequence = new Consequence() {
public void evaluate(KnowledgeHelper drools, WorkingMemory workingMemory) throws ConsequenceException {
try {
RuleImpl rule = drools.getRule();
LeftTuple tuple = (LeftTuple) drools.getTuple();
Context context = (Context) drools.get(contextDeclaration);
context.setState(Context.ASSIGN_SEATS);
drools.update(tuple.get(contextDeclaration), context);
// System.err.println( "continue processing" );
} catch (Exception e) {
e.printStackTrace();
throw new ConsequenceException(e);
}
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
public void writeExternal(ObjectOutput out) throws IOException {
}
public String getName() {
return "default";
}
};
rule.setConsequence(consequence);
return rule;
}
Aggregations