Search in sources :

Example 76 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class CrossProductTest method setUp.

@Before
public void setUp() throws Exception {
    final ObjectType list1ObjectType = new ClassObjectType(String.class);
    final ObjectType list2ObjectType = new ClassObjectType(String.class);
    final RuleImpl rule = new RuleImpl("rule-1");
    final Pattern list1Pattern = new Pattern(0, list1ObjectType, "s1");
    final Pattern list2Pattern = new Pattern(1, list2ObjectType, "s2");
    rule.addPattern(list1Pattern);
    rule.addPattern(list2Pattern);
    final Declaration s1Declaration = rule.getDeclaration("s1");
    final Declaration s2Declaration = rule.getDeclaration("s2");
    this.values = new ArrayList();
    rule.setConsequence(new Consequence() {

        private static final long serialVersionUID = 510l;

        public void evaluate(final KnowledgeHelper knowledgeHelper, final ReteEvaluator reteEvaluator) throws Exception {
            final String s1 = (String) knowledgeHelper.get(s1Declaration);
            final String s2 = (String) knowledgeHelper.get(s2Declaration);
            CrossProductTest.this.values.add(new String[] { s1, s2 });
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        }

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            return "default";
        }
    });
    this.pkg = CoreComponentFactory.get().createKnowledgePackage("org.drools");
    this.pkg.addRule(rule);
}
Also used : ReteEvaluator(org.drools.core.common.ReteEvaluator) Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectOutput(java.io.ObjectOutput) ArrayList(java.util.ArrayList) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) IOException(java.io.IOException) IOException(java.io.IOException) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration) ObjectInput(java.io.ObjectInput) Before(org.junit.Before)

Example 77 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class AccumulateVisitor method replaceBindingWithPatternBinding.

private MethodCallExpr replaceBindingWithPatternBinding(MethodCallExpr bindExpression, MethodCallExpr lastPattern) {
    // This method links a binding expression, used to evaluate the accumulated value,
    // to the last pattern in a multi-pattern accumulate like the following
    // 
    // accumulate( $c : Child( age < 10 ) and $a : Adult( name == $c.parent ) and $s : String( this == $a.name ),
    // $sum : sum($a.getAge() + $c.getAge() + $s.length()) )
    // 
    // In the case the bindExpression, that will have to be linked to the $s pattern, is originally generated as
    // 
    // bind(var_$sum, var_$a, var_$c, var_$s, (Adult $a, Child $c, String $s) -> $a.getAge() + $c.getAge() + $s.length())
    final Expression bindingId = lastPattern.getArgument(0);
    bindExpression.findFirst(NameExpr.class, e -> e.equals(bindingId)).ifPresent(name -> {
        // since the bind has to be linked to $s, the corresponding variable should be removed from the arguments list so it becomes
        // bind(var_$sum, var_$a, var_$c, (Adult $a, Child $c, String $s) -> $a.getAge() + $c.getAge() + $s.length())
        bindExpression.remove(name);
        // also the first formal parameter in the binding lambda has to be $s so it becomes
        // bind(var_$sum, var_$a, var_$c, (String $s, Adult $a, Child $c) -> $a.getAge() + $c.getAge() + $s.length())
        LambdaExpr lambda = (LambdaExpr) bindExpression.getArgument(bindExpression.getArguments().size() - 1);
        if (lambda.getParameters().size() > 1) {
            String formalArg = context.fromVar(name.getNameAsString());
            for (Parameter param : lambda.getParameters()) {
                if (param.getNameAsString().equals(formalArg)) {
                    lambda.getParameters().remove(param);
                    lambda.getParameters().add(0, param);
                    break;
                }
            }
        }
    });
    return bindExpression;
}
Also used : REACT_ON_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.REACT_ON_CALL) ModelGeneratorVisitor(org.drools.modelcompiler.builder.generator.visitor.ModelGeneratorVisitor) ACCUMULATE_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.ACCUMULATE_CALL) DeclarationSpec(org.drools.modelcompiler.builder.generator.DeclarationSpec) DrlxParseUtil(org.drools.modelcompiler.builder.generator.DrlxParseUtil) PatternDescr(org.drools.drl.ast.descr.PatternDescr) InvalidExpressionErrorResult(org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult) ExpressionTyperContext(org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyperContext) LiteralExpr(com.github.javaparser.ast.expr.LiteralExpr) AccumulateUtil(org.drools.compiler.rule.builder.util.AccumulateUtil) AccumulateFunction(org.kie.api.runtime.rule.AccumulateFunction) Expression(com.github.javaparser.ast.expr.Expression) ConstraintParser(org.drools.modelcompiler.builder.generator.drlxparse.ConstraintParser) PatternExpressionBuilder(org.drools.modelcompiler.builder.generator.expression.PatternExpressionBuilder) BinaryExpr(com.github.javaparser.ast.expr.BinaryExpr) Node(com.github.javaparser.ast.Node) PackageModel(org.drools.modelcompiler.builder.PackageModel) NodeList(com.github.javaparser.ast.NodeList) AND_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.AND_CALL) Collection(java.util.Collection) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) Set(java.util.Set) LambdaUtil(org.drools.modelcompiler.util.LambdaUtil) BaseDescr(org.drools.drl.ast.descr.BaseDescr) VALUE_OF_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.VALUE_OF_CALL) Objects(java.util.Objects) List(java.util.List) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) SingleDrlxParseSuccess(org.drools.modelcompiler.builder.generator.drlxparse.SingleDrlxParseSuccess) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) DrlxParseFail(org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseFail) DrlxParseUtil.validateDuplicateBindings(org.drools.modelcompiler.builder.generator.DrlxParseUtil.validateDuplicateBindings) DrlxParseResult(org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseResult) AbstractExpressionBuilder(org.drools.modelcompiler.builder.generator.expression.AbstractExpressionBuilder) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) DrlxParseSuccess(org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseSuccess) PrintUtil.printNode(org.drools.mvel.parser.printer.PrintUtil.printNode) Parameter(com.github.javaparser.ast.body.Parameter) Pattern(org.drools.core.rule.Pattern) ArrayList(java.util.ArrayList) ACC_FUNCTION_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.ACC_FUNCTION_CALL) HashSet(java.util.HashSet) CollectListAccumulateFunction(org.drools.core.base.accumulators.CollectListAccumulateFunction) AccumulateDescr(org.drools.drl.ast.descr.AccumulateDescr) DrlxParseUtil.getLiteralExpressionType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.getLiteralExpressionType) DslMethodNames.createDslTopLevelMethod(org.drools.modelcompiler.builder.generator.DslMethodNames.createDslTopLevelMethod) AndDescr(org.drools.drl.ast.descr.AndDescr) ReplaceTypeInLambda.replaceTypeInExprLambda(org.drools.modelcompiler.util.lambdareplace.ReplaceTypeInLambda.replaceTypeInExprLambda) BIND_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.BIND_CALL) Optional.ofNullable(java.util.Optional.ofNullable) BIND_AS_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.BIND_AS_CALL) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) MethodReferenceExpr(com.github.javaparser.ast.expr.MethodReferenceExpr) ExpressionTyper(org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyper) RuleContext(org.drools.modelcompiler.builder.generator.RuleContext) Collectors.toList(java.util.stream.Collectors.toList) CollectAccumulator(org.drools.core.base.accumulators.CollectAccumulator) CollectSetAccumulateFunction(org.drools.core.base.accumulators.CollectSetAccumulateFunction) ParseResultVisitor(org.drools.modelcompiler.builder.generator.drlxparse.ParseResultVisitor) Collections(java.util.Collections) Expression(com.github.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) DrlNameExpr(org.drools.mvel.parser.ast.expr.DrlNameExpr) NameExpr(com.github.javaparser.ast.expr.NameExpr) Parameter(com.github.javaparser.ast.body.Parameter)

Example 78 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class LogicTransformerTest method testNotExistsTransformation.

/**
 * Exists inside a not is redundant and should be eliminated
 *
 * (Not (exists (A) ) )
 *
 * <pre>
 *             Not
 *              |
 *            Exists
 *              |
 *             And
 *             / \
 *            a   b
 * </pre>
 *
 * Should become:
 *
 * <pre>
 *             Not
 *              |
 *             And
 *             / \
 *            a   b
 * </pre>
 */
@Test
public void testNotExistsTransformation() throws InvalidPatternException {
    final ObjectType type = new ClassObjectType(String.class);
    final Pattern a = new Pattern(0, type, "a");
    final Pattern b = new Pattern(1, type, "b");
    final GroupElement not = GroupElementFactory.newNotInstance();
    final GroupElement exists = GroupElementFactory.newExistsInstance();
    final GroupElement and = GroupElementFactory.newAndInstance();
    not.addChild(exists);
    exists.addChild(and);
    and.addChild(a);
    and.addChild(b);
    GroupElement[] transformed = LogicTransformer.getInstance().transform(not, Collections.EMPTY_MAP);
    GroupElement wrapper = transformed[0];
    GroupElement notR = (GroupElement) wrapper.getChildren().get(0);
    assertTrue(notR.isNot());
    assertEquals(1, notR.getChildren().size());
    assertTrue(notR.getChildren().get(0) instanceof GroupElement);
    GroupElement andR = (GroupElement) notR.getChildren().get(0);
    assertTrue(andR.isAnd());
    assertEquals(2, andR.getChildren().size());
    assertTrue(andR.getChildren().get(0) instanceof Pattern);
    assertTrue(andR.getChildren().get(1) instanceof Pattern);
    final Pattern a1 = (Pattern) andR.getChildren().get(0);
    final Pattern b1 = (Pattern) andR.getChildren().get(1);
    assertEquals(a, a1);
    assertEquals(b, b1);
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) GroupElement(org.drools.core.rule.GroupElement) Test(org.junit.Test)

Example 79 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class LogicTransformerTest method testSingleOrAndOrTransformation.

/**
 * (a||b)&&c
 *
 * <pre>
 *               and
 *               / \
 *              or  c
 *             /  \
 *            a    b
 * </pre>
 *
 * Should become (a&&c)||(b&&c)
 *
 * <pre>
 *
 *               or
 *              /  \
 *             /    \
 *            /      \
 *             and      and
 *          / \      / \
 *         a   c    b   c
 * </pre>
 */
@Test
public void testSingleOrAndOrTransformation() throws InvalidPatternException {
    final ObjectType type = new ClassObjectType(String.class);
    final Pattern a = new Pattern(0, type, "a");
    final Pattern b = new Pattern(1, type, "b");
    final Pattern c = new Pattern(2, type, "c");
    final GroupElement or = GroupElementFactory.newOrInstance();
    or.addChild(a);
    or.addChild(b);
    final GroupElement parent = GroupElementFactory.newAndInstance();
    parent.addChild(or);
    parent.addChild(c);
    LogicTransformer.getInstance().applyOrTransformation(parent);
    assertLength(2, parent.getChildren());
    assertEquals(GroupElement.class, parent.getChildren().get(0).getClass());
    assertEquals(GroupElement.class, parent.getChildren().get(1).getClass());
    final GroupElement and1 = (GroupElement) parent.getChildren().get(0);
    assertTrue(and1.isAnd());
    // transformation MUST keep the order
    assertEquals(a, and1.getChildren().get(0));
    assertEquals(c, and1.getChildren().get(1));
    final GroupElement and2 = (GroupElement) parent.getChildren().get(1);
    assertEquals(b, and2.getChildren().get(0));
    assertEquals(c, and2.getChildren().get(1));
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) GroupElement(org.drools.core.rule.GroupElement) Test(org.junit.Test)

Example 80 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class LogicTransformerTest method testTransform.

/**
 * /**
 *
 * <pre>
 *                         _/|\_
 *                      __/  |  \__
 *                     /     |     \
 *                  __/      |      \__
 *                 /         |         \
 *                And       or         And
 *               /  \       / \        /  \
 *             a    Or     d   e      Not OR
 *                 / \                |  / |
 *               b    c               f g Not
 *                                         |
 *                                         h
 *
 * </pre>
 *
 * Each And is a Rete sub rule
 *
 * <pre>
 *
 *       And___     And___      And___      And___        And__    And___       And___    And___
 *      ||| |  \   ||| |  \     ||| |  \   ||| |  \     ||| |  \  ||| |  \     ||| |  \  ||| |  \
 *      abd Not g  abd Not Not  abe Not g  abe Not Not  acd Not g acd Not Not  ace Not g ace Not Not
 *           |          |   |        |          |   |        |        |    |       |          |   |
 *           f          f   h        f          f   h        f        f    h       f          f   h
 *
 * </pre>
 *
 * @throws IOException
 * @throws ClassNotFoundException
 *
 * @throws IOException
 * @throws ClassNotFoundException
 */
@Test
public void testTransform() throws IOException, ClassNotFoundException, InvalidPatternException {
    final ObjectType type = new ClassObjectType(String.class);
    final Pattern a = new Pattern(0, type, "a");
    final Pattern b = new Pattern(1, type, "b");
    final Pattern c = new Pattern(2, type, "c");
    final Pattern d = new Pattern(3, type, "d");
    final Pattern e = new Pattern(4, type, "e");
    final Pattern f = new Pattern(5, type, "f");
    final Pattern g = new Pattern(6, type, "g");
    final Pattern h = new Pattern(7, type, "h");
    final GroupElement and = GroupElementFactory.newAndInstance();
    final GroupElement and1 = GroupElementFactory.newAndInstance();
    and1.addChild(a);
    final GroupElement or1 = GroupElementFactory.newOrInstance();
    or1.addChild(b);
    or1.addChild(c);
    and1.addChild(or1);
    and.addChild(and1);
    final GroupElement or2 = GroupElementFactory.newOrInstance();
    or2.addChild(d);
    or2.addChild(e);
    and.addChild(or2);
    final GroupElement and2 = GroupElementFactory.newAndInstance();
    final GroupElement not1 = GroupElementFactory.newNotInstance();
    not1.addChild(f);
    final GroupElement or3 = GroupElementFactory.newOrInstance();
    or3.addChild(g);
    final GroupElement not2 = GroupElementFactory.newNotInstance();
    not2.addChild(h);
    or3.addChild(not2);
    and2.addChild(not1);
    and2.addChild(or3);
    and.addChild(and2);
    final GroupElement[] ands = LogicTransformer.getInstance().transform(and, Collections.EMPTY_MAP);
    // Uncomment this when you need to output a new known correct tree
    // result
    final File testFile = new File("target/test/LogicTransformerTest_correct_transform1.dat");
    testFile.getParentFile().mkdirs();
    DroolsStreamUtils.streamOut(new FileOutputStream(testFile), ands);
    // Now check the main tree
    // Get known correct tree
    // The binary stream was created from a handchecked correct output
    final GroupElement[] correctResultAnds = (GroupElement[]) DroolsStreamUtils.streamIn(new FileInputStream(testFile));
    for (int j = 0; j < ands.length; j++) {
        assertEquals(correctResultAnds[j], ands[j]);
    }
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) GroupElement(org.drools.core.rule.GroupElement) FileOutputStream(java.io.FileOutputStream) File(java.io.File) FileInputStream(java.io.FileInputStream) Test(org.junit.Test)

Aggregations

Pattern (org.drools.core.rule.Pattern)190 ClassObjectType (org.drools.core.base.ClassObjectType)103 Test (org.junit.Test)98 Declaration (org.drools.core.rule.Declaration)79 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)69 GroupElement (org.drools.core.rule.GroupElement)49 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)45 ArrayList (java.util.ArrayList)35 IOException (java.io.IOException)33 ObjectType (org.drools.core.spi.ObjectType)32 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)28 Variable (org.drools.model.Variable)25 LambdaConstraint (org.drools.modelcompiler.constraints.LambdaConstraint)25 List (java.util.List)24 Accumulate (org.drools.core.rule.Accumulate)24 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)23 KieBase (org.kie.api.KieBase)23 Collection (java.util.Collection)21 QueryImpl (org.drools.core.rule.QueryImpl)21 KieSession (org.kie.api.runtime.KieSession)21