use of org.drools.core.rule.Pattern in project drools by kiegroup.
the class PatternDSLTest method testOr.
@Test
public void testOr() {
Result result = new Result();
Variable<Person> personV = declarationOf(Person.class);
Variable<Person> markV = declarationOf(Person.class);
Variable<String> nameV = declarationOf(String.class);
Rule rule = rule("or").build(or(pattern(personV).expr("exprA", p -> p.getName().equals("Mark")), and(pattern(markV).expr("exprA", p -> p.getName().equals("Mark")), pattern(personV).expr("exprB", markV, (p1, p2) -> p1.getAge() > p2.getAge()))), pattern(nameV).expr("exprC", personV, (s, p) -> s.equals(p.getName())), on(nameV).execute(result::setValue));
Model model = new ModelImpl().addRule(rule);
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel(model);
KieSession ksession = kieBase.newKieSession();
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("Mario", result.getValue());
}
use of org.drools.core.rule.Pattern in project drools by kiegroup.
the class PatternDSLTest method test2AccRewriteToNested.
@Test
public void test2AccRewriteToNested() throws Exception {
final Global<List> var_results = D.globalOf(List.class, "defaultpkg", "results");
final Variable<Person> var_$p = D.declarationOf(Person.class);
Variable<Integer> var_$age = D.declarationOf(Integer.class);
Variable<Integer> var_$sumOfAges = D.declarationOf(Integer.class);
Variable<Long> var_$countOfPersons = D.declarationOf(Long.class);
Predicate1<Long> cp = c -> c > 0;
Rule rule1 = D.rule("R1").build(D.accumulate(D.pattern(var_$p).bind(var_$age, person -> person.getAge(), D.reactOn("age")), D.accFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction::new, var_$age).as(var_$sumOfAges)), D.accumulate(D.pattern(var_$sumOfAges), D.accFunction(org.drools.core.base.accumulators.CountAccumulateFunction::new).as(var_$countOfPersons)), // Filter
D.pattern(var_$countOfPersons).expr(cp), // Consequence
D.on(var_$countOfPersons, var_results).execute((drools, i, results) -> {
Activation activation = (Activation) ((org.drools.modelcompiler.consequence.DroolsImpl) drools).asKnowledgeHelper().getMatch();
results.add(i + ":" + activation.getObjectsDeep());
}));
Model model = new ModelImpl().addRule(rule1).addGlobal(var_results);
KieBase kbase = KieBaseBuilder.createKieBaseFromModel(model);
RuleImpl rule = (RuleImpl) kbase.getKiePackage("defaultpkg").getRules().toArray()[0];
// Should only be a single child
assertEquals(1, rule.getLhs().getChildren().size());
// Check correct result type and the filter was moved up
Pattern p1 = (Pattern) rule.getLhs().getChildren().get(0);
assertSame(Long.class, ((ClassObjectType) p1.getObjectType()).getClassType());
LambdaConstraint l0 = (LambdaConstraint) p1.getConstraints().get(0);
assertSame(cp, ((Predicate1.Impl) l0.getEvaluator().getConstraint().getPredicate1()).getLambda());
// The second acc was sucessfully nested inside
Accumulate acc = (Accumulate) p1.getSource();
assertEquals(1, acc.getNestedElements().size());
Pattern p2 = (Pattern) acc.getNestedElements().get(0);
assertSame(Integer.class, ((ClassObjectType) p2.getObjectType()).getClassType());
KieSession ksession = kbase.newKieSession();
List<String> results = new ArrayList<String>();
ksession.setGlobal("results", results);
ksession.insert(new Person("Mark", 42));
ksession.fireAllRules();
assertEquals("[1:[1]]", results.toString());
}
use of org.drools.core.rule.Pattern in project drools by kiegroup.
the class PatternDSLTest method testAccumulate.
@Test
public void testAccumulate() {
Result result = new Result();
Variable<Person> person = declarationOf(Person.class);
Variable<Integer> resultSum = declarationOf(Integer.class);
Variable<Double> resultAvg = declarationOf(Double.class);
Variable<Integer> age = declarationOf(Integer.class);
Rule rule = rule("accumulate").build(accumulate(pattern(person).expr(p -> p.getName().startsWith("M")).bind(age, Person::getAge), accFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction::new, age).as(resultSum), accFunction(org.drools.core.base.accumulators.AverageAccumulateFunction::new, age).as(resultAvg)), on(resultSum, resultAvg).execute((sum, avg) -> result.setValue("total = " + sum + "; average = " + avg)));
Model model = new ModelImpl().addRule(rule);
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel(model);
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("total = 77; average = 38.5", result.getValue());
}
use of org.drools.core.rule.Pattern in project drools by kiegroup.
the class PatternDSLTest method testBetaWithBinding.
@Test
public void testBetaWithBinding() {
Variable<Person> markV = declarationOf(Person.class);
Variable<Integer> markAge = declarationOf(Integer.class);
Variable<Person> olderV = declarationOf(Person.class);
Rule rule = rule("beta").build(pattern(markV).expr("exprA", p -> p.getName().equals("Mark"), alphaIndexedBy(String.class, Index.ConstraintType.EQUAL, 1, p -> p.getName(), "Mark"), reactOn("name", "age")).bind(markAge, p -> p.getAge(), reactOn("age")), pattern(olderV).expr("exprB", p -> !p.getName().equals("Mark"), alphaIndexedBy(String.class, Index.ConstraintType.NOT_EQUAL, 1, p -> p.getName(), "Mark"), reactOn("name")).expr("exprC", markAge, (p1, age) -> p1.getAge() > age, betaIndexedBy(int.class, Index.ConstraintType.GREATER_THAN, 0, p -> p.getAge(), int.class::cast), reactOn("age")), on(olderV, markV).execute((drools, p1, p2) -> drools.insert(p1.getName() + " is older than " + p2.getName())));
Model model = new ModelImpl().addRule(rule);
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel(model);
KieSession ksession = kieBase.newKieSession();
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
FactHandle markFH = ksession.insert(mark);
FactHandle edsonFH = ksession.insert(edson);
FactHandle marioFH = ksession.insert(mario);
ksession.fireAllRules();
Collection<String> results = getObjectsIntoList(ksession, String.class);
Assertions.assertThat(results).containsExactlyInAnyOrder("Mario is older than Mark");
ksession.delete(marioFH);
ksession.fireAllRules();
mark.setAge(34);
ksession.update(markFH, mark, "age");
ksession.fireAllRules();
results = getObjectsIntoList(ksession, String.class);
Assertions.assertThat(results).containsExactlyInAnyOrder("Mario is older than Mark", "Edson is older than Mark");
}
use of org.drools.core.rule.Pattern in project drools by kiegroup.
the class MVELConsequenceBuilderTest method testImperativeCodeError.
@Test
public void testImperativeCodeError() throws Exception {
InternalKnowledgePackage pkg = CoreComponentFactory.get().createKnowledgePackage("pkg1");
final RuleDescr ruleDescr = new RuleDescr("rule 1");
ruleDescr.setConsequence("if (cheese.price == 10) { cheese.price = 5; }");
Properties properties = new Properties();
properties.setProperty("drools.dialect.default", "mvel");
KnowledgeBuilderConfigurationImpl cfg1 = new KnowledgeBuilderConfigurationImpl(properties);
KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg, cfg1);
PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(pkg.getName());
DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect(pkgRegistry.getDialect());
final RuleBuildContext context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);
final InstrumentedDeclarationScopeResolver declarationResolver = new InstrumentedDeclarationScopeResolver();
final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);
final Pattern pattern = new Pattern(0, cheeseObjeectType);
final PatternExtractor extractor = new PatternExtractor(cheeseObjeectType);
final Declaration declaration = new Declaration("cheese", extractor, pattern);
final Map<String, Declaration> map = new HashMap<String, Declaration>();
map.put("cheese", declaration);
declarationResolver.setDeclarations(map);
context.setDeclarationResolver(declarationResolver);
final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
final Cheese cheddar = new Cheese("cheddar", 10);
final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
final AgendaItem item = new AgendaItemImpl(0, tuple, 10, null, null, null);
final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
kbHelper.setActivation(item);
try {
((MVELConsequence) context.getRule().getConsequence()).compile((MVELDialectRuntimeData) pkgBuilder.getPackageRegistry(pkg.getName()).getDialectRuntimeRegistry().getDialectData("mvel"));
context.getRule().getConsequence().evaluate(kbHelper, ksession);
fail("should throw an exception, as 'if' is not allowed");
} catch (Exception e) {
}
assertEquals(10, cheddar.getPrice());
}
Aggregations