Search in sources :

Example 1 with ExprViewItem

use of org.drools.model.view.ExprViewItem in project drools by kiegroup.

the class ViewFlowBuilder method viewItems2Condition.

private static CompositePatterns viewItems2Condition(BuildContext ctx, Condition.Type type, boolean topLevel) {
    List<Condition> conditions = new ArrayList<>();
    Map<Variable<?>, Condition> conditionMap = new HashMap<>();
    Map<String, Consequence> consequences = topLevel ? new LinkedHashMap<>() : null;
    Iterator<RuleItem> ruleItemIterator = ctx.ruleItems.iterator();
    while (ruleItemIterator.hasNext()) {
        Map<Variable<?>, InputViewItemImpl<?>> scopedInputs = type.createsScope() ? new LinkedHashMap<>(ctx.inputs) : ctx.inputs;
        RuleItem ruleItem = ruleItemIterator.next();
        if (ruleItem instanceof FixedValueItem) {
            conditions.add(new EvalImpl(((FixedValueItem) ruleItem).isValue()));
            continue;
        }
        if (ruleItem instanceof Consequence) {
            if (!topLevel) {
                throw new IllegalStateException("A consequence can be only a top level item");
            }
            Consequence consequence = (Consequence) ruleItem;
            String name = ruleItemIterator.hasNext() ? generateName("consequence") : RuleImpl.DEFAULT_CONSEQUENCE_NAME;
            consequences.put(name, consequence);
            conditions.add(new NamedConsequenceImpl(name, consequence.isBreaking()));
            continue;
        }
        if (ruleItem instanceof ConditionalConsequence) {
            if (!topLevel) {
                throw new IllegalStateException("A consequence can be only a top level item");
            }
            conditions.add(createConditionalNamedConsequence(consequences, (ConditionalConsequence) ruleItem));
            continue;
        }
        ViewItem viewItem = (ViewItem) ruleItem;
        if (viewItem instanceof CombinedExprViewItem) {
            CombinedExprViewItem combined = (CombinedExprViewItem) viewItem;
            conditions.add(viewItems2Condition(new BuildContext(ctx, combined.getExpressions(), scopedInputs), combined.getType(), false));
            continue;
        }
        if (viewItem instanceof QueryCallViewItem) {
            QueryCallViewItem query = ((QueryCallViewItem) viewItem);
            for (Argument arg : query.getArguments()) {
                if (arg instanceof Variable) {
                    ctx.usedVars.add(((Variable) arg));
                }
            }
            conditions.add(new QueryCallPattern(query));
            continue;
        }
        if (viewItem instanceof Binding) {
            Binding bindViewItem = (Binding) viewItem;
            PatternImpl pattern = (PatternImpl) conditionMap.get(bindViewItem.getInputVariable());
            if (pattern == null) {
                // This should probably be the bindViewItem.getBoundVariable() instead of the input
                // as the input variables can be many
                pattern = new PatternImpl(bindViewItem.getInputVariable());
                pattern.addWatchedProps(bindViewItem.getWatchedProps());
                ctx.usedVars.add(bindViewItem.getInputVariable());
                conditions.add(pattern);
                conditionMap.put(bindViewItem.getInputVariable(), pattern);
            }
            pattern.addBinding(bindViewItem);
            ctx.usedVars.add(viewItem.getFirstVariable());
            ctx.addBinding(bindViewItem);
            scopedInputs.putIfAbsent(viewItem.getFirstVariable(), (InputViewItemImpl) input(viewItem.getFirstVariable()));
            continue;
        }
        Variable<?> patterVariable = findPatterVariable(viewItem, scopedInputs.keySet());
        if (viewItem instanceof InputViewItemImpl) {
            scopedInputs.put(patterVariable, (InputViewItemImpl) viewItem);
            PatternImpl condition = new PatternImpl(patterVariable);
            condition.addWatchedProps(((InputViewItemImpl) viewItem).getWatchedProps());
            conditions.add(condition);
            conditionMap.put(patterVariable, condition);
            ctx.usedVars.add(patterVariable);
            continue;
        }
        if (viewItem instanceof ExistentialExprViewItem) {
            ExistentialExprViewItem existential = ((ExistentialExprViewItem) viewItem);
            if (patterVariable != null && !existential.isQueryExpression()) {
                registerInputsFromViewItem(existential.getExpression(), conditionMap, scopedInputs, patterVariable);
            }
            Condition condition = new PatternImpl(patterVariable, SingleConstraint.TRUE, ctx.bindings.get(patterVariable));
            conditions.add(new ExistentialPatternImpl(viewItem2Condition(existential.getExpression(), condition, new BuildContext(ctx, new LinkedHashMap<>())), existential.getType()));
            continue;
        }
        if (ruleItem instanceof ExprViewItem && ctx.boundVars.contains(patterVariable)) {
            conditions.add(new EvalImpl(createConstraint((ExprViewItem) ruleItem)));
            continue;
        }
        ctx.usedVars.add(patterVariable);
        Condition condition;
        if (type == Type.AND) {
            condition = conditionMap.get(patterVariable);
            if (condition == null) {
                condition = new PatternImpl(patterVariable, SingleConstraint.TRUE, ctx.bindings.get(patterVariable));
                conditions.add(condition);
                if (!(viewItem instanceof AccumulateExprViewItem)) {
                    conditionMap.put(patterVariable, condition);
                }
                scopedInputs.putIfAbsent(patterVariable, (InputViewItemImpl) input(patterVariable));
            }
        } else {
            condition = new PatternImpl(patterVariable);
            conditions.add(condition);
        }
        addInputFromVariableSource(scopedInputs, patterVariable);
        registerInputsFromViewItem(viewItem, conditionMap, scopedInputs, null);
        Condition modifiedPattern = viewItem2Condition(viewItem, condition, new BuildContext(ctx, scopedInputs));
        conditions.set(conditions.indexOf(condition), modifiedPattern);
        if (type == Type.AND && !(viewItem instanceof AccumulateExprViewItem)) {
            conditionMap.put(patterVariable, modifiedPattern);
        }
    }
    return new CompositePatterns(type, conditions, ctx.usedVars, consequences);
}
Also used : AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) TemporalExprViewItem(org.drools.model.view.TemporalExprViewItem) AbstractExprViewItem(org.drools.model.view.AbstractExprViewItem) ExprViewItem(org.drools.model.view.ExprViewItem) Variable(org.drools.model.Variable) InputViewItemImpl(org.drools.model.view.InputViewItemImpl) Argument(org.drools.model.Argument) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) CompositePatterns(org.drools.model.patterns.CompositePatterns) NamedConsequenceImpl(org.drools.model.consequences.NamedConsequenceImpl) ConditionalNamedConsequenceImpl(org.drools.model.consequences.ConditionalNamedConsequenceImpl) PatternImpl(org.drools.model.patterns.PatternImpl) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl) AccumulatePatternImpl(org.drools.model.patterns.AccumulatePatternImpl) EvalImpl(org.drools.model.patterns.EvalImpl) QueryCallViewItem(org.drools.model.view.QueryCallViewItem) QueryCallPattern(org.drools.model.patterns.QueryCallPattern) RuleItem(org.drools.model.RuleItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) Condition(org.drools.model.Condition) Binding(org.drools.model.Binding) ConditionalConsequence(org.drools.model.ConditionalConsequence) ExprNViewItem(org.drools.model.view.ExprNViewItem) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) InputViewItem(org.drools.model.view.InputViewItem) QueryCallViewItem(org.drools.model.view.QueryCallViewItem) ViewItem(org.drools.model.view.ViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) TemporalExprViewItem(org.drools.model.view.TemporalExprViewItem) AbstractExprViewItem(org.drools.model.view.AbstractExprViewItem) ExprViewItem(org.drools.model.view.ExprViewItem) Consequence(org.drools.model.Consequence) ConditionalConsequence(org.drools.model.ConditionalConsequence) FixedValueItem(org.drools.model.view.FixedValueItem) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem)

Example 2 with ExprViewItem

use of org.drools.model.view.ExprViewItem in project drools by kiegroup.

the class GroupByTest method testWithNull.

@Test
public void testWithNull() {
    Variable<MyType> var = D.declarationOf(MyType.class);
    Variable<MyType> groupKey = D.declarationOf(MyType.class);
    Variable<Long> count = D.declarationOf(Long.class);
    AtomicInteger mappingFunctionCallCounter = new AtomicInteger(0);
    Function1<MyType, MyType> mappingFunction = (a) -> {
        mappingFunctionCallCounter.incrementAndGet();
        return a.getNested();
    };
    D.PatternDef<MyType> onlyOnesWithNested = D.pattern(var).expr(myType -> myType.getNested() != null);
    ExprViewItem groupBy = D.groupBy(onlyOnesWithNested, var, groupKey, mappingFunction, D.accFunction(CountAccumulateFunction::new).as(count));
    List<MyType> result = new ArrayList<>();
    Rule rule = D.rule("R").build(groupBy, D.on(groupKey, count).execute((drools, key, acc) -> result.add(key)));
    Model model = new ModelImpl().addRule(rule);
    KieBase kieBase = KieBaseBuilder.createKieBaseFromModel(model);
    MyType objectWithoutNestedObject = new MyType(null);
    MyType objectWithNestedObject = new MyType(objectWithoutNestedObject);
    KieSession ksession = kieBase.newKieSession();
    ksession.insert(objectWithNestedObject);
    ksession.insert(objectWithoutNestedObject);
    ksession.fireAllRules();
    // Side issue: this number is unusually high. Perhaps we should try to implement some cache for this?
    System.out.println("GroupKey mapping function was called " + mappingFunctionCallCounter.get() + " times.");
    Assertions.assertThat(result).containsOnly(objectWithoutNestedObject);
}
Also used : Arrays(java.util.Arrays) InternalFactHandle(org.drools.core.common.InternalFactHandle) Accumulator(org.drools.core.spi.Accumulator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Global(org.drools.model.Global) RuleEventListener(org.kie.internal.event.rule.RuleEventListener) DSL(org.drools.model.DSL) Child(org.drools.modelcompiler.domain.Child) Match(org.kie.api.runtime.rule.Match) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Declaration(org.drools.core.rule.Declaration) Assertions(org.assertj.core.api.Assertions) KieSession(org.kie.api.runtime.KieSession) Parent(org.drools.modelcompiler.domain.Parent) Set(java.util.Set) Index(org.drools.model.Index) ConsequenceBuilder(org.drools.model.consequences.ConsequenceBuilder) EvaluationUtil(org.drools.modelcompiler.util.EvaluationUtil) Objects(java.util.Objects) List(java.util.List) Tuple(org.drools.core.spi.Tuple) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) Person(org.drools.modelcompiler.domain.Person) DSL.from(org.drools.model.DSL.from) ModelImpl(org.drools.model.impl.ModelImpl) HashMap(java.util.HashMap) PatternDSL(org.drools.model.PatternDSL) ArrayList(java.util.ArrayList) Function1(org.drools.model.functions.Function1) CollectListAccumulateFunction(org.drools.core.base.accumulators.CollectListAccumulateFunction) RuleEventManager(org.kie.internal.event.rule.RuleEventManager) KieBase(org.kie.api.KieBase) LinkedHashSet(java.util.LinkedHashSet) Model(org.drools.model.Model) IntegerMaxAccumulateFunction(org.drools.core.base.accumulators.IntegerMaxAccumulateFunction) ReteEvaluator(org.drools.core.common.ReteEvaluator) ViewItem(org.drools.model.view.ViewItem) Pair(org.apache.commons.math3.util.Pair) Variable(org.drools.model.Variable) D(org.drools.modelcompiler.dsl.pattern.D) IntegerSumAccumulateFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction) ToIntFunction(java.util.function.ToIntFunction) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) GroupKey(org.drools.model.functions.accumulate.GroupKey) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBaseBuilder(org.drools.modelcompiler.builder.KieBaseBuilder) Assert.assertNull(org.junit.Assert.assertNull) Ignore(org.junit.Ignore) Rule(org.drools.model.Rule) ExprViewItem(org.drools.model.view.ExprViewItem) RuleTerminalNodeLeftTuple(org.drools.core.reteoo.RuleTerminalNodeLeftTuple) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ExprViewItem(org.drools.model.view.ExprViewItem) D(org.drools.modelcompiler.dsl.pattern.D) ArrayList(java.util.ArrayList) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) KieBase(org.kie.api.KieBase) Model(org.drools.model.Model) KieSession(org.kie.api.runtime.KieSession) Rule(org.drools.model.Rule) ModelImpl(org.drools.model.impl.ModelImpl) Test(org.junit.Test)

Example 3 with ExprViewItem

use of org.drools.model.view.ExprViewItem in project drools by kiegroup.

the class GroupByTest method testUnexpectedRuleMatch.

@Test
public void testUnexpectedRuleMatch() {
    final Global<List> var_results = D.globalOf(List.class, "defaultpkg", "results");
    // $a: Parent()
    Variable<Parent> patternVar = D.declarationOf(Parent.class);
    PatternDSL.PatternDef<Parent> pattern = D.pattern(patternVar);
    // exists Child($a.getChild() == this)
    Variable<Child> existsPatternVar = D.declarationOf(Child.class);
    PatternDSL.PatternDef<Child> existsPattern = D.pattern(existsPatternVar).expr(patternVar, (child, parent) -> Objects.equals(parent.getChild(), child));
    // count(Parent::getChild)
    Variable<Child> groupKeyVar = D.declarationOf(Child.class);
    Variable<Long> accumulateResult = D.declarationOf(Long.class);
    ExprViewItem groupBy = PatternDSL.groupBy(D.and(pattern, D.exists(existsPattern)), patternVar, groupKeyVar, Parent::getChild, DSL.accFunction(CountAccumulateFunction::new).as(accumulateResult));
    Rule rule1 = D.rule("R1").build(groupBy, D.on(var_results, groupKeyVar, accumulateResult).execute((results, $child, $count) -> results.add(Arrays.asList($child, $count))));
    Model model = new ModelImpl().addRule(rule1).addGlobal(var_results);
    KieSession ksession = KieBaseBuilder.createKieBaseFromModel(model).newKieSession();
    List results = new ArrayList();
    ksession.setGlobal("results", results);
    Child child1 = new Child("Child1", 1);
    Parent parent1 = new Parent("Parent1", child1);
    Child child2 = new Child("Child2", 2);
    Parent parent2 = new Parent("Parent2", child2);
    ksession.insert(parent1);
    ksession.insert(parent2);
    FactHandle toRemove = ksession.insert(child1);
    ksession.insert(child2);
    // Remove child1, therefore it does not exist, therefore there should be no groupBy matches for the child.
    ksession.delete(toRemove);
    // Yet, we still get (Child1, 0).
    ksession.fireAllRules();
    Assertions.assertThat(results).containsOnly(Arrays.asList(child2, 1L));
}
Also used : Arrays(java.util.Arrays) InternalFactHandle(org.drools.core.common.InternalFactHandle) Accumulator(org.drools.core.spi.Accumulator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Global(org.drools.model.Global) RuleEventListener(org.kie.internal.event.rule.RuleEventListener) DSL(org.drools.model.DSL) Child(org.drools.modelcompiler.domain.Child) Match(org.kie.api.runtime.rule.Match) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Declaration(org.drools.core.rule.Declaration) Assertions(org.assertj.core.api.Assertions) KieSession(org.kie.api.runtime.KieSession) Parent(org.drools.modelcompiler.domain.Parent) Set(java.util.Set) Index(org.drools.model.Index) ConsequenceBuilder(org.drools.model.consequences.ConsequenceBuilder) EvaluationUtil(org.drools.modelcompiler.util.EvaluationUtil) Objects(java.util.Objects) List(java.util.List) Tuple(org.drools.core.spi.Tuple) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) Person(org.drools.modelcompiler.domain.Person) DSL.from(org.drools.model.DSL.from) ModelImpl(org.drools.model.impl.ModelImpl) HashMap(java.util.HashMap) PatternDSL(org.drools.model.PatternDSL) ArrayList(java.util.ArrayList) Function1(org.drools.model.functions.Function1) CollectListAccumulateFunction(org.drools.core.base.accumulators.CollectListAccumulateFunction) RuleEventManager(org.kie.internal.event.rule.RuleEventManager) KieBase(org.kie.api.KieBase) LinkedHashSet(java.util.LinkedHashSet) Model(org.drools.model.Model) IntegerMaxAccumulateFunction(org.drools.core.base.accumulators.IntegerMaxAccumulateFunction) ReteEvaluator(org.drools.core.common.ReteEvaluator) ViewItem(org.drools.model.view.ViewItem) Pair(org.apache.commons.math3.util.Pair) Variable(org.drools.model.Variable) D(org.drools.modelcompiler.dsl.pattern.D) IntegerSumAccumulateFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction) ToIntFunction(java.util.function.ToIntFunction) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) GroupKey(org.drools.model.functions.accumulate.GroupKey) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBaseBuilder(org.drools.modelcompiler.builder.KieBaseBuilder) Assert.assertNull(org.junit.Assert.assertNull) Ignore(org.junit.Ignore) Rule(org.drools.model.Rule) ExprViewItem(org.drools.model.view.ExprViewItem) RuleTerminalNodeLeftTuple(org.drools.core.reteoo.RuleTerminalNodeLeftTuple) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ExprViewItem(org.drools.model.view.ExprViewItem) PatternDSL(org.drools.model.PatternDSL) Parent(org.drools.modelcompiler.domain.Parent) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) ArrayList(java.util.ArrayList) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) Model(org.drools.model.Model) List(java.util.List) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) Rule(org.drools.model.Rule) ModelImpl(org.drools.model.impl.ModelImpl) Child(org.drools.modelcompiler.domain.Child) Test(org.junit.Test)

Example 4 with ExprViewItem

use of org.drools.model.view.ExprViewItem 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);
}
Also used : PatternDSL.rule(org.drools.model.PatternDSL.rule) Variable(org.drools.model.Variable) AverageAccumulateFunction(org.drools.core.base.accumulators.AverageAccumulateFunction) PatternDSL(org.drools.model.PatternDSL) Test(org.junit.Test) DSL.on(org.drools.model.DSL.on) Index(org.drools.model.Index) Predicate1(org.drools.model.functions.Predicate1) Supplier(java.util.function.Supplier) PatternDSL.pattern(org.drools.model.PatternDSL.pattern) Predicate2(org.drools.model.functions.Predicate2) DSL.accumulate(org.drools.model.DSL.accumulate) Function1(org.drools.model.functions.Function1) DSL.accFunction(org.drools.model.DSL.accFunction) PatternDSL.alphaIndexedBy(org.drools.model.PatternDSL.alphaIndexedBy) AccumulateFunction(org.kie.api.runtime.rule.AccumulateFunction) Rule(org.drools.model.Rule) Assertions(org.assertj.core.api.Assertions) ExprViewItem(org.drools.model.view.ExprViewItem) Person(org.drools.modelcompiler.domain.Person) PatternDSL.betaIndexedBy(org.drools.model.PatternDSL.betaIndexedBy) DSL.declarationOf(org.drools.model.DSL.declarationOf) DSL.accumulate(org.drools.model.DSL.accumulate) AverageAccumulateFunction(org.drools.core.base.accumulators.AverageAccumulateFunction) PatternDSL(org.drools.model.PatternDSL) Rule(org.drools.model.Rule) AverageAccumulateFunction(org.drools.core.base.accumulators.AverageAccumulateFunction) AccumulateFunction(org.kie.api.runtime.rule.AccumulateFunction) Person(org.drools.modelcompiler.domain.Person) Test(org.junit.Test)

Example 5 with ExprViewItem

use of org.drools.model.view.ExprViewItem in project drools by kiegroup.

the class ViewPatternBuilder method ruleItem2Condition.

public static Condition ruleItem2Condition(RuleItem ruleItem) {
    if (ruleItem instanceof PatternDefImpl) {
        PatternDefImpl<?> patternDef = (PatternDefImpl) ruleItem;
        Variable<?> patternVariable = patternDef.getFirstVariable();
        PatternImpl pattern = new PatternImpl(patternVariable, patternVariable instanceof Exchange ? Condition.Type.RECEIVER : Condition.Type.PATTERN);
        for (PatternItem patternItem : patternDef.getItems()) {
            if (patternItem instanceof PatternExprImpl) {
                pattern.addConstraint(((PatternExprImpl) patternItem).asConstraint(patternDef));
            } else if (patternItem instanceof PatternBindingImpl) {
                pattern.addBinding(((PatternBindingImpl) patternItem).asBinding(patternDef));
            } else {
                throw new UnsupportedOperationException("Unknown pattern item type: " + patternItem);
            }
        }
        pattern.addWatchedProps(patternDef.getWatch());
        pattern.setPassive(patternDef.isPassive());
        return pattern;
    }
    if (ruleItem instanceof FixedValueItem) {
        return new EvalImpl(((FixedValueItem) ruleItem).isValue());
    }
    if (ruleItem instanceof QueryCallViewItem) {
        return new QueryCallPattern((QueryCallViewItem) ruleItem);
    }
    if (ruleItem instanceof CombinedExprViewItem) {
        CombinedExprViewItem combined = (CombinedExprViewItem) ruleItem;
        List<Condition> conditions = new ArrayList<>();
        for (ViewItem expr : combined.getExpressions()) {
            conditions.add(ruleItem2Condition(expr));
        }
        return new CompositePatterns(combined.getType(), conditions);
    }
    if (ruleItem instanceof ExistentialExprViewItem) {
        ExistentialExprViewItem existential = (ExistentialExprViewItem) ruleItem;
        return new ExistentialPatternImpl(ruleItem2Condition(existential.getExpression()), existential.getType());
    }
    if (ruleItem instanceof GroupByExprViewItem) {
        GroupByExprViewItem groupBy = (GroupByExprViewItem) ruleItem;
        return new GroupByPatternImpl(ruleItem2Condition(groupBy.getExpr()), groupBy.getVars(), groupBy.getVarKey(), groupBy.getGroupingFunction(), groupBy.getAccumulateFunctions());
    }
    if (ruleItem instanceof AccumulateExprViewItem) {
        AccumulateExprViewItem acc = (AccumulateExprViewItem) ruleItem;
        return new AccumulatePatternImpl(ruleItem2Condition(acc.getExpr()), null, acc.getAccumulateFunctions());
    }
    if (ruleItem instanceof ExprViewItem) {
        return new EvalImpl(createConstraint((ExprViewItem) ruleItem));
    }
    if (ruleItem instanceof ExchangeDefImpl) {
        ExchangeDefImpl<?> exchangeDef = (ExchangeDefImpl) ruleItem;
        return new PatternImpl(exchangeDef.getFirstVariable(), Condition.Type.SENDER);
    }
    throw new UnsupportedOperationException("Unknown " + ruleItem);
}
Also used : AccumulatePatternImpl(org.drools.model.patterns.AccumulatePatternImpl) GroupByExprViewItem(org.drools.model.view.GroupByExprViewItem) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) ExprViewItem(org.drools.model.view.ExprViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl) ExchangeDefImpl(org.drools.model.PatternDSL.ExchangeDefImpl) PatternItem(org.drools.model.PatternDSL.PatternItem) ArrayList(java.util.ArrayList) CompositePatterns(org.drools.model.patterns.CompositePatterns) GroupByExprViewItem(org.drools.model.view.GroupByExprViewItem) GroupByPatternImpl(org.drools.model.patterns.GroupByPatternImpl) PatternImpl(org.drools.model.patterns.PatternImpl) ExistentialPatternImpl(org.drools.model.patterns.ExistentialPatternImpl) AccumulatePatternImpl(org.drools.model.patterns.AccumulatePatternImpl) EvalImpl(org.drools.model.patterns.EvalImpl) QueryCallViewItem(org.drools.model.view.QueryCallViewItem) QueryCallPattern(org.drools.model.patterns.QueryCallPattern) GroupByPatternImpl(org.drools.model.patterns.GroupByPatternImpl) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) Condition(org.drools.model.Condition) GroupByExprViewItem(org.drools.model.view.GroupByExprViewItem) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) ExistentialExprViewItem(org.drools.model.view.ExistentialExprViewItem) QueryCallViewItem(org.drools.model.view.QueryCallViewItem) ViewItem(org.drools.model.view.ViewItem) CombinedExprViewItem(org.drools.model.view.CombinedExprViewItem) ExprViewItem(org.drools.model.view.ExprViewItem) FixedValueItem(org.drools.model.view.FixedValueItem) PatternExprImpl(org.drools.model.PatternDSL.PatternExprImpl) AccumulateExprViewItem(org.drools.model.view.AccumulateExprViewItem) PatternBindingImpl(org.drools.model.PatternDSL.PatternBindingImpl) PatternDefImpl(org.drools.model.PatternDSL.PatternDefImpl)

Aggregations

ExprViewItem (org.drools.model.view.ExprViewItem)5 ArrayList (java.util.ArrayList)4 Variable (org.drools.model.Variable)4 ViewItem (org.drools.model.view.ViewItem)4 HashMap (java.util.HashMap)3 Assertions (org.assertj.core.api.Assertions)3 Index (org.drools.model.Index)3 PatternDSL (org.drools.model.PatternDSL)3 Rule (org.drools.model.Rule)3 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 LinkedHashSet (java.util.LinkedHashSet)2 List (java.util.List)2 Map (java.util.Map)2 Objects (java.util.Objects)2 Set (java.util.Set)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 ToIntFunction (java.util.function.ToIntFunction)2 Pair (org.apache.commons.math3.util.Pair)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2