use of org.drools.model.functions.Predicate1 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.model.functions.Predicate1 in project drools by kiegroup.
the class ToStringTest method testToString.
/**
* Users may depend on seeing {@link Rule#toString()} in log files giving useful information, in order to understand
* the rules that are being created. The format is not required to be backwards compatible - this test merely checks
* that it does not change unknowingly.
*/
@Test
public void testToString() {
Variable<Person> markV = declarationOf(Person.class);
Variable<Integer> markAge = declarationOf(Integer.class);
Variable<Person> olderV = declarationOf(Person.class);
Variable<Double> resultAvg = declarationOf(Double.class);
Variable<Integer> age = declarationOf(Integer.class);
String person = "Mark";
Function1<Person, String> nameGetter = Person::getName;
Function1<Person, Integer> ageGetter = Person::getAge;
Predicate1<Person> markPredicate = p -> p.getName().equals(person);
PatternDSL.PatternDef<Person> pattern1 = pattern(markV).expr("exprA", markPredicate, alphaIndexedBy(String.class, Index.ConstraintType.EQUAL, 0, nameGetter, person)).bind(markAge, ageGetter);
Predicate1<Person> notMarkPredicate = markPredicate.negate();
Predicate2<Person, Integer> agePredicate = (p1, someAge) -> p1.getAge() > someAge;
Function1<Integer, Integer> ageCaster = int.class::cast;
PatternDSL.PatternDef<Person> pattern2 = pattern(olderV).expr("exprB", notMarkPredicate, alphaIndexedBy(String.class, Index.ConstraintType.NOT_EQUAL, 1, nameGetter, person)).expr("exprC", markAge, agePredicate, betaIndexedBy(int.class, Index.ConstraintType.GREATER_THAN, 0, ageGetter, ageCaster));
AccumulateFunction<AverageAccumulateFunction.AverageData> f = new AverageAccumulateFunction();
Supplier<AccumulateFunction<AverageAccumulateFunction.AverageData>> accumulateSupplier = () -> f;
org.drools.model.functions.accumulate.AccumulateFunction actualAccumulate = accFunction(accumulateSupplier, age);
ExprViewItem<Person> accumulate = accumulate(pattern(olderV).expr("exprD", notMarkPredicate).bind(age, ageGetter), actualAccumulate.as(resultAvg));
Rule rule = rule("beta").build(pattern1, pattern2, accumulate, on(olderV, markV).execute((drools, p1, p2) -> drools.insert(p1.getName() + " is older than " + p2.getName())));
String pattern1toString = "PatternImpl (type: PATTERN, inputVars: null, " + "outputVar: " + markV + ", " + "constraint: Constraint for 'exprA' (index: AlphaIndex #0 (EQUAL, left: lambda " + System.identityHashCode(nameGetter) + ", right: " + person + ")))";
String pattern2toString = "PatternImpl (type: PATTERN, inputVars: null, " + "outputVar: " + olderV + ", " + "constraint: MultipleConstraints (constraints: [" + "Constraint for 'exprB' (index: AlphaIndex #1 (NOT_EQUAL, left: lambda " + System.identityHashCode(nameGetter) + ", right: " + person + ")), " + "Constraint for 'exprC' (index: BetaIndex #0 (GREATER_THAN, left: lambda " + System.identityHashCode(ageGetter) + ", right: lambda " + System.identityHashCode(ageCaster) + "))]))";
String accumulatePatternToString = "PatternImpl (type: PATTERN, inputVars: null, " + "outputVar: " + olderV + ", " + "constraint: Constraint for 'exprD' (index: null))";
String accumulateToString = "AccumulatePatternImpl (functions: [" + actualAccumulate + "], " + "condition: " + accumulatePatternToString + ", " + "pattern: " + accumulatePatternToString + ")";
String consequenceToString = "ConsequenceImpl (variables: [" + olderV + ", " + markV + "], language: java, breaking: false)";
String expectedToString = "Rule: defaultpkg.beta (" + "view: CompositePatterns of AND (vars: null, patterns: [" + pattern1toString + ", " + pattern2toString + ", " + accumulateToString + ", NamedConsequenceImpl 'default' (breaking: false)], " + "consequences: {default=" + consequenceToString + "}), consequences: {default=" + consequenceToString + "})";
Assertions.assertThat(rule).hasToString(expectedToString);
}
use of org.drools.model.functions.Predicate1 in project drools by kiegroup.
the class PatternDSLTest method testPatternsAfterAccMovedToEvalsOnResultPattern.
@Test
public void testPatternsAfterAccMovedToEvalsOnResultPattern() throws Exception {
final Global<List> var_results = D.globalOf(List.class, "defaultpkg", "results");
final Variable<String> var_$key = D.declarationOf(String.class);
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<Integer> p1 = a -> a > 0;
Predicate1<Long> p2 = c -> c > 0;
Rule rule1 = D.rule("R1").build(D.accumulate(// Patterns
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.accFunction(org.drools.core.base.accumulators.CountAccumulateFunction::new).as(var_$countOfPersons)), // Filter
D.pattern(var_$sumOfAges).expr(p1), D.pattern(var_$countOfPersons).expr(p2), // Consequence
D.on(var_$sumOfAges, var_$countOfPersons, var_results).execute(($ages, $counts, results) -> results.add($ages + ":" + $counts)));
Model model = new ModelImpl().addRule(rule1).addGlobal(var_results);
KieBase kbase = KieBaseBuilder.createKieBaseFromModel(model);
RuleImpl rule = (RuleImpl) kbase.getKiePackage("defaultpkg").getRules().toArray()[0];
// Ensure there is only a single root child
assertEquals(1, rule.getLhs().getChildren().size());
// The expression must be merged up into the acc pattern
Pattern p = (Pattern) rule.getLhs().getChildren().get(0);
assertSame(Object[].class, ((ClassObjectType) p.getObjectType()).getClassType());
LambdaConstraint l0 = (LambdaConstraint) p.getConstraints().get(0);
assertSame(p1, ((Predicate1.Impl) l0.getEvaluator().getConstraint().getPredicate1()).getLambda());
LambdaConstraint l1 = (LambdaConstraint) p.getConstraints().get(1);
assertSame(p2, ((Predicate1.Impl) l1.getEvaluator().getConstraint().getPredicate1()).getLambda());
KieSession ksession = kbase.newKieSession();
List<String> results = new ArrayList<String>();
ksession.setGlobal("results", results);
ksession.insert(new Person("Mark", 42));
ksession.fireAllRules();
assertEquals("[42:1]", results.toString());
}
use of org.drools.model.functions.Predicate1 in project drools by kiegroup.
the class BaseBetaConstraintsTest method getCheeseTypeConstraint.
protected BetaNodeFieldConstraint getCheeseTypeConstraint(final String identifier, Operator operator) {
if (useLambdaConstraint) {
Pattern pattern = new Pattern(0, new ClassObjectType(Cheese.class));
Predicate1<Cheese> predicate;
if (operator == Operator.BuiltInOperator.EQUAL.getOperator()) {
predicate = new Predicate1.Impl<Cheese>(_this -> EvaluationUtil.areNullSafeEquals(_this.getType(), identifier));
} else if (operator == Operator.BuiltInOperator.NOT_EQUAL.getOperator()) {
predicate = new Predicate1.Impl<Cheese>(_this -> !EvaluationUtil.areNullSafeEquals(_this.getType(), identifier));
} else if (operator == Operator.BuiltInOperator.GREATER.getOperator()) {
predicate = new Predicate1.Impl<Cheese>(_this -> EvaluationUtil.greaterThan(_this.getType(), identifier));
} else if (operator == Operator.BuiltInOperator.GREATER_OR_EQUAL.getOperator()) {
predicate = new Predicate1.Impl<Cheese>(_this -> EvaluationUtil.greaterOrEqual(_this.getType(), identifier));
} else if (operator == Operator.BuiltInOperator.LESS.getOperator()) {
predicate = new Predicate1.Impl<Cheese>(_this -> EvaluationUtil.lessThan(_this.getType(), identifier));
} else if (operator == Operator.BuiltInOperator.GREATER_OR_EQUAL.getOperator()) {
predicate = new Predicate1.Impl<Cheese>(_this -> EvaluationUtil.lessOrEqual(_this.getType(), identifier));
} else {
throw new RuntimeException(operator + " is not supported");
}
return LambdaConstraintTestUtil.createLambdaConstraint1(Cheese.class, pattern, predicate, null);
} else {
ClassFieldAccessorStore store = new ClassFieldAccessorStore();
store.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
store.setEagerWire(true);
InternalReadAccessor extractor = store.getReader(Cheese.class, "type");
Declaration declaration = new Declaration(identifier, extractor, new Pattern(0, new ClassObjectType(Cheese.class)));
String expression = "type " + operator.getOperatorString() + " " + identifier;
return new MVELConstraintTestUtil(expression, operator.getOperatorString(), declaration, extractor);
}
}
Aggregations