Search in sources :

Example 6 with SelfReferenceClassFieldReader

use of org.drools.core.base.extractors.SelfReferenceClassFieldReader in project drools by kiegroup.

the class JavaAccumulateBuilder method buildExternalFunctionCall.

private Accumulate buildExternalFunctionCall(RuleBuildContext context, AccumulateDescr accumDescr, RuleConditionElement source, Map<String, Declaration> declsInScope, Map<String, Class<?>> declCls, boolean readLocalsFromTuple) {
    // list of functions to build
    final List<AccumulateFunctionCallDescr> funcCalls = accumDescr.getFunctions();
    // list of available source declarations
    final Declaration[] sourceDeclArr = source.getOuterDeclarations().values().toArray(new Declaration[source.getOuterDeclarations().size()]);
    Arrays.sort(sourceDeclArr, RuleTerminalNode.SortDeclarations.instance);
    // set of required previous declarations
    Set<Declaration> requiredDecl = new HashSet<Declaration>();
    Pattern pattern = (Pattern) context.getDeclarationResolver().peekBuildStack();
    if (accumDescr.isMultiFunction()) {
        // the accumulator array
        Accumulator[] accumulators = new Accumulator[funcCalls.size()];
        // creating the custom array reader
        InternalReadAccessor reader = new SelfReferenceClassFieldReader(Object[].class);
        int index = 0;
        for (AccumulateFunctionCallDescr fc : funcCalls) {
            AccumulateFunction function = getAccumulateFunction(context, accumDescr, fc, source, declCls);
            if (function == null) {
                return null;
            }
            bindReaderToDeclaration(context, accumDescr, pattern, fc, new ArrayElementReader(reader, index, function.getResultType()), function.getResultType(), index);
            accumulators[index++] = buildAccumulator(context, accumDescr, declsInScope, declCls, readLocalsFromTuple, sourceDeclArr, requiredDecl, fc, function);
        }
        return new MultiAccumulate(source, requiredDecl.toArray(new Declaration[requiredDecl.size()]), accumulators);
    } else {
        AccumulateFunctionCallDescr fc = accumDescr.getFunctions().get(0);
        AccumulateFunction function = getAccumulateFunction(context, accumDescr, fc, source, declCls);
        if (function == null) {
            return null;
        }
        Class<?> returnType = function.getResultType();
        if (!pattern.isCompatibleWithAccumulateReturnType(returnType)) {
            context.addError(new DescrBuildError(accumDescr, context.getRuleDescr(), null, "Pattern of type: '" + pattern.getObjectType() + "' on rule '" + context.getRuleDescr().getName() + "' is not compatible with type " + returnType.getCanonicalName() + " returned by accumulate function."));
            return null;
        }
        bindReaderToDeclaration(context, accumDescr, pattern, fc, new SelfReferenceClassFieldReader(function.getResultType()), function.getResultType(), -1);
        Accumulator accumulator = buildAccumulator(context, accumDescr, declsInScope, declCls, readLocalsFromTuple, sourceDeclArr, requiredDecl, fc, function);
        return new SingleAccumulate(source, requiredDecl.toArray(new Declaration[requiredDecl.size()]), accumulator);
    }
}
Also used : Accumulator(org.drools.core.spi.Accumulator) Pattern(org.drools.core.rule.Pattern) MultiAccumulate(org.drools.core.rule.MultiAccumulate) SingleAccumulate(org.drools.core.rule.SingleAccumulate) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Constraint(org.drools.core.spi.Constraint) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) AccumulateFunctionCallDescr(org.drools.compiler.lang.descr.AccumulateDescr.AccumulateFunctionCallDescr) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) Declaration(org.drools.core.rule.Declaration) AccumulateFunction(org.kie.api.runtime.rule.AccumulateFunction) HashSet(java.util.HashSet)

Example 7 with SelfReferenceClassFieldReader

use of org.drools.core.base.extractors.SelfReferenceClassFieldReader in project drools by kiegroup.

the class BuildUtilsTest method testCalculateTemporalDistance.

/**
 * Test method for {@link org.drools.core.reteoo.builder.BuildUtils#calculateTemporalDistance(org.drools.core.rule.GroupElement)}.
 */
@Test
public void testCalculateTemporalDistance() {
    // input is here just for "documentation" purposes
    Interval[][] input = new Interval[][] { { new Interval(0, 0), new Interval(-2, 2), new Interval(-3, 4), new Interval(MIN, MAX), new Interval(MIN, MAX) }, { new Interval(-2, 2), new Interval(0, 0), new Interval(MIN, MAX), new Interval(1, 2), new Interval(MIN, MAX) }, { new Interval(-4, 3), new Interval(MIN, MAX), new Interval(0, 0), new Interval(2, 3), new Interval(MIN, MAX) }, { new Interval(MIN, MAX), new Interval(-2, -1), new Interval(-3, -2), new Interval(0, 0), new Interval(1, 10) }, { new Interval(MIN, MAX), new Interval(MIN, MAX), new Interval(MIN, MAX), new Interval(-10, -1), new Interval(0, 0) } };
    Interval[][] expected = new Interval[][] { { new Interval(0, 0), new Interval(-2, 2), new Interval(-3, 2), new Interval(-1, 4), new Interval(0, 14) }, { new Interval(-2, 2), new Interval(0, 0), new Interval(-2, 0), new Interval(1, 2), new Interval(2, 12) }, { new Interval(-2, 3), new Interval(0, 2), new Interval(0, 0), new Interval(2, 3), new Interval(3, 13) }, { new Interval(-4, 1), new Interval(-2, -1), new Interval(-3, -2), new Interval(0, 0), new Interval(1, 10) }, { new Interval(-14, 0), new Interval(-12, -2), new Interval(-13, -3), new Interval(-10, -1), new Interval(0, 0) } };
    AfterEvaluatorDefinition evals = new AfterEvaluatorDefinition();
    ClassObjectType ot = new ClassObjectType(StockTick.class, true);
    Pattern a = new Pattern(0, ot, "$a");
    Pattern b = new Pattern(1, ot, "$b");
    b.addConstraint(new EvaluatorConstraint(new Declaration[] { a.getDeclaration() }, evals.getEvaluator(ValueType.OBJECT_TYPE, AfterEvaluatorDefinition.AFTER, "-2,2"), new SelfReferenceClassFieldReader(StockTick.class)));
    Pattern c = new Pattern(2, ot, "$c");
    c.addConstraint(new EvaluatorConstraint(new Declaration[] { a.getDeclaration() }, evals.getEvaluator(ValueType.OBJECT_TYPE, AfterEvaluatorDefinition.AFTER, "-3,4"), new SelfReferenceClassFieldReader(StockTick.class)));
    Pattern d = new Pattern(3, ot, "$d");
    d.addConstraint(new EvaluatorConstraint(new Declaration[] { b.getDeclaration() }, evals.getEvaluator(ValueType.OBJECT_TYPE, AfterEvaluatorDefinition.AFTER, "1,2"), new SelfReferenceClassFieldReader(StockTick.class)));
    d.addConstraint(new EvaluatorConstraint(new Declaration[] { c.getDeclaration() }, evals.getEvaluator(ValueType.OBJECT_TYPE, AfterEvaluatorDefinition.AFTER, "2,3"), new SelfReferenceClassFieldReader(StockTick.class)));
    Pattern e = new Pattern(4, ot, "$e");
    e.addConstraint(new EvaluatorConstraint(new Declaration[] { d.getDeclaration() }, evals.getEvaluator(ValueType.OBJECT_TYPE, AfterEvaluatorDefinition.AFTER, "1,10"), new SelfReferenceClassFieldReader(StockTick.class)));
    GroupElement not = new GroupElement(Type.NOT);
    not.addChild(e);
    GroupElement and = new GroupElement(Type.AND);
    and.addChild(a);
    and.addChild(b);
    and.addChild(c);
    and.addChild(d);
    and.addChild(not);
    TemporalDependencyMatrix matrix = utils.calculateTemporalDistance(and);
    // printMatrix( matrix.getMatrix() );
    assertEqualsMatrix(expected, matrix.getMatrix());
    assertEquals(15, matrix.getExpirationOffset(a));
    assertEquals(11, matrix.getExpirationOffset(d));
    assertEquals(1, matrix.getExpirationOffset(e));
}
Also used : Pattern(org.drools.core.rule.Pattern) AfterEvaluatorDefinition(org.drools.core.base.evaluators.AfterEvaluatorDefinition) ClassObjectType(org.drools.core.base.ClassObjectType) EvaluatorConstraint(org.drools.core.rule.constraint.EvaluatorConstraint) TemporalDependencyMatrix(org.drools.core.time.TemporalDependencyMatrix) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) GroupElement(org.drools.core.rule.GroupElement) Declaration(org.drools.core.rule.Declaration) Interval(org.drools.core.time.Interval) Test(org.junit.Test)

Example 8 with SelfReferenceClassFieldReader

use of org.drools.core.base.extractors.SelfReferenceClassFieldReader in project drools by kiegroup.

the class LogicTransformer method processElement.

/**
 * recurse through the rule condition elements updating the declaration objecs
 */
private void processElement(final DeclarationScopeResolver resolver, final Stack<RuleConditionElement> contextStack, final RuleConditionElement element) {
    if (element instanceof Pattern) {
        Pattern pattern = (Pattern) element;
        for (RuleConditionElement ruleConditionElement : pattern.getNestedElements()) {
            processElement(resolver, contextStack, ruleConditionElement);
        }
        for (Constraint constraint : pattern.getConstraints()) {
            if (constraint instanceof Declaration) {
                continue;
            }
            replaceDeclarations(resolver, pattern, constraint);
        }
    } else if (element instanceof EvalCondition) {
        processEvalCondition(resolver, (EvalCondition) element);
    } else if (element instanceof Accumulate) {
        for (RuleConditionElement rce : element.getNestedElements()) {
            processElement(resolver, contextStack, rce);
        }
        Accumulate accumulate = (Accumulate) element;
        replaceDeclarations(resolver, accumulate);
    } else if (element instanceof From) {
        DataProvider provider = ((From) element).getDataProvider();
        Declaration[] decl = provider.getRequiredDeclarations();
        for (Declaration aDecl : decl) {
            Declaration resolved = resolver.getDeclaration(aDecl.getIdentifier());
            if (resolved != null && resolved != aDecl) {
                provider.replaceDeclaration(aDecl, resolved);
            } else if (resolved == null) {
                // it is probably an implicit declaration, so find the corresponding pattern
                Pattern old = aDecl.getPattern();
                Pattern current = resolver.findPatternByIndex(old.getIndex());
                if (current != null && old != current) {
                    resolved = new Declaration(aDecl.getIdentifier(), aDecl.getExtractor(), current);
                    provider.replaceDeclaration(aDecl, resolved);
                }
            }
        }
    } else if (element instanceof QueryElement) {
        QueryElement qe = (QueryElement) element;
        Pattern pattern = qe.getResultPattern();
        for (Entry<String, Declaration> entry : pattern.getInnerDeclarations().entrySet()) {
            Declaration resolved = resolver.getDeclaration(entry.getValue().getIdentifier());
            if (resolved != null && resolved != entry.getValue() && resolved.getPattern() != pattern) {
                entry.setValue(resolved);
            }
        }
        List<Integer> varIndexes = asList(qe.getVariableIndexes());
        for (int i = 0; i < qe.getArguments().length; i++) {
            if (!(qe.getArguments()[i] instanceof QueryArgument.Declr)) {
                continue;
            }
            Declaration declr = ((QueryArgument.Declr) qe.getArguments()[i]).getDeclaration();
            Declaration resolved = resolver.getDeclaration(declr.getIdentifier());
            if (resolved != declr && resolved.getPattern() != pattern) {
                qe.getArguments()[i] = new QueryArgument.Declr(resolved);
            }
            if (ClassObjectType.DroolsQuery_ObjectType.isAssignableFrom(resolved.getPattern().getObjectType())) {
                // if the resolved still points to DroolsQuery, we know this is the first unification pattern, so redeclare it as the visible Declaration
                declr = pattern.addDeclaration(declr.getIdentifier());
                // this bit is different, notice its the ArrayElementReader that we wire up to, not the declaration.
                ArrayElementReader reader = new ArrayElementReader(new SelfReferenceClassFieldReader(Object[].class), i, resolved.getDeclarationClass());
                declr.setReadAccessor(reader);
                varIndexes.add(i);
            }
        }
        qe.setVariableIndexes(toIntArray(varIndexes));
    } else if (element instanceof ConditionalBranch) {
        processBranch(resolver, (ConditionalBranch) element);
    } else {
        contextStack.push(element);
        for (RuleConditionElement ruleConditionElement : element.getNestedElements()) {
            processElement(resolver, contextStack, ruleConditionElement);
        }
        contextStack.pop();
    }
}
Also used : Constraint(org.drools.core.spi.Constraint) Constraint(org.drools.core.spi.Constraint) DataProvider(org.drools.core.spi.DataProvider) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader)

Aggregations

SelfReferenceClassFieldReader (org.drools.core.base.extractors.SelfReferenceClassFieldReader)8 Declaration (org.drools.core.rule.Declaration)6 ArrayElementReader (org.drools.core.base.extractors.ArrayElementReader)5 Pattern (org.drools.core.rule.Pattern)5 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)5 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)3 Accumulator (org.drools.core.spi.Accumulator)3 Constraint (org.drools.core.spi.Constraint)3 ArrayList (java.util.ArrayList)2 AccumulateFunctionCallDescr (org.drools.compiler.lang.descr.AccumulateDescr.AccumulateFunctionCallDescr)2 ClassObjectType (org.drools.core.base.ClassObjectType)2 MultiAccumulate (org.drools.core.rule.MultiAccumulate)2 MutableTypeConstraint (org.drools.core.rule.MutableTypeConstraint)2 QueryArgument (org.drools.core.rule.QueryArgument)2 QueryElement (org.drools.core.rule.QueryElement)2 SingleAccumulate (org.drools.core.rule.SingleAccumulate)2 TypeDeclaration (org.drools.core.rule.TypeDeclaration)2 WindowDeclaration (org.drools.core.rule.WindowDeclaration)2 MvelConstraint (org.drools.core.rule.constraint.MvelConstraint)2 QueryNameConstraint (org.drools.core.rule.constraint.QueryNameConstraint)2