Search in sources :

Example 6 with MVELConstraint

use of org.drools.mvel.MVELConstraint in project drools by kiegroup.

the class JavaAccumulateBuilder method bindReaderToDeclaration.

private void bindReaderToDeclaration(RuleBuildContext context, AccumulateDescr accumDescr, Pattern pattern, AccumulateFunctionCallDescr fc, InternalReadAccessor readAccessor, Class<?> resultType, int index) {
    if (fc.getBind() != null) {
        if (context.getDeclarationResolver().isDuplicated(context.getRule(), fc.getBind(), resultType.getName())) {
            if (!fc.isUnification()) {
                context.addError(new DescrBuildError(context.getParentDescr(), accumDescr, null, "Duplicate declaration for variable '" + fc.getBind() + "' in the rule '" + context.getRule().getName() + "'"));
            } else {
                Declaration inner = context.getDeclarationResolver().getDeclaration(fc.getBind());
                Constraint c = new MVELConstraint(Collections.singletonList(context.getPkg().getName()), index >= 0 ? "this[ " + index + " ] == " + fc.getBind() : "this == " + fc.getBind(), new Declaration[] { inner }, null, null, IndexUtil.ConstraintType.EQUAL, context.getDeclarationResolver().getDeclaration(fc.getBind()), index >= 0 ? new ArrayElementReader(readAccessor, index, resultType) : readAccessor, true);
                ((MutableTypeConstraint) c).setType(Constraint.ConstraintType.BETA);
                pattern.addConstraint(c);
            }
        } else {
            Declaration declr = pattern.addDeclaration(fc.getBind());
            declr.setReadAccessor(readAccessor);
        }
    }
}
Also used : DescrBuildError(org.drools.compiler.compiler.DescrBuildError) MVELConstraint(org.drools.mvel.MVELConstraint) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MVELConstraint(org.drools.mvel.MVELConstraint) Constraint(org.drools.core.spi.Constraint) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) Declaration(org.drools.core.rule.Declaration)

Example 7 with MVELConstraint

use of org.drools.mvel.MVELConstraint in project drools by kiegroup.

the class ConstraintEvaluationExceptionTest method addRuleToConstraintTestField.

private void addRuleToConstraintTestField(String ruleName, String ruleFileName) {
    if (testRunType.isExecutableModel()) {
        predicateInformation.addRuleNames(ruleName, ruleFileName);
    } else {
        // in non-exec-model, node sharing triggers merging
        MVELConstraint otherMvelConstraint = new MVELConstraint("com.example", mvelConstraint.getExpression(), null, null, null, null, null);
        InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
        BuildContext buildContext = new BuildContext(kBase, Collections.emptyList());
        RuleImpl ruleImpl = new RuleImpl(ruleName);
        Resource resource = new ByteArrayResource();
        resource.setSourcePath(ruleFileName);
        ruleImpl.setResource(resource);
        buildContext.setRule(ruleImpl);
        otherMvelConstraint.registerEvaluationContext(buildContext);
        mvelConstraint.mergeEvaluationContext(otherMvelConstraint);
    }
}
Also used : MVELConstraint(org.drools.mvel.MVELConstraint) BuildContext(org.drools.core.reteoo.builder.BuildContext) Resource(org.kie.api.io.Resource) ByteArrayResource(org.drools.core.io.impl.ByteArrayResource) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) ByteArrayResource(org.drools.core.io.impl.ByteArrayResource) InternalKnowledgeBase(org.drools.kiesession.rulebase.InternalKnowledgeBase)

Example 8 with MVELConstraint

use of org.drools.mvel.MVELConstraint in project drools by kiegroup.

the class MVELTest method testArrayAccessorWithStaticFieldAccess.

@Test
public void testArrayAccessorWithStaticFieldAccess() {
    final String str = "" + "package org.drools.mvel.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + "import " + Address.class.getCanonicalName() + "\n" + "import " + Triangle.class.getCanonicalName() + "\n" + "global java.util.List list \n" + "rule \"show\" \n" + "when  \n" + "    $m : Person( addresses[Triangle.ZERO] == new Address('s1'), addresses[Triangle.ZERO].street == new Address('s1').street ) \n" + "then \n" + "    list.add('r1'); \n" + "end \n";
    KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("test", kieBaseTestConfiguration, str);
    KieSession ksession = kbase.newKieSession();
    final List list = new ArrayList();
    ksession.setGlobal("list", list);
    final Person p = new Person("yoda");
    p.addAddress(new Address("s1"));
    ksession.insert(p);
    ksession.fireAllRules();
    assertEquals("r1", list.get(0));
    // Check it was built with MVELReturnValueExpression constraint
    final List<ObjectTypeNode> nodes = ((InternalKnowledgeBase) kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (final ObjectTypeNode n : nodes) {
        if (((ClassObjectType) n.getObjectType()).getClassType() == Person.class) {
            node = n;
            break;
        }
    }
    AlphaNode alphanode = (AlphaNode) node.getObjectSinkPropagator().getSinks()[0];
    AlphaNodeFieldConstraint constraint = alphanode.getConstraint();
    if (constraint instanceof MVELConstraint) {
        assertTrue(((MVELConstraint) alphanode.getConstraint()).getFieldExtractor() instanceof MVELObjectClassFieldReader);
    }
    alphanode = (AlphaNode) alphanode.getObjectSinkPropagator().getSinks()[0];
    constraint = alphanode.getConstraint();
    if (constraint instanceof MVELConstraint) {
        assertTrue(((MVELConstraint) alphanode.getConstraint()).getFieldExtractor() instanceof MVELObjectClassFieldReader);
    }
}
Also used : Address(org.drools.mvel.compiler.Address) ArrayList(java.util.ArrayList) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) MVELObjectClassFieldReader(org.drools.mvel.extractors.MVELObjectClassFieldReader) AlphaNode(org.drools.core.reteoo.AlphaNode) AlphaNodeFieldConstraint(org.drools.core.spi.AlphaNodeFieldConstraint) MVELConstraint(org.drools.mvel.MVELConstraint) KieBase(org.kie.api.KieBase) StatelessKieSession(org.kie.api.runtime.StatelessKieSession) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) Person(org.drools.mvel.compiler.Person) Test(org.junit.Test)

Example 9 with MVELConstraint

use of org.drools.mvel.MVELConstraint in project drools by kiegroup.

the class MVELAccumulateBuilder method buildExternalFunctions.

private Accumulator[] buildExternalFunctions(final RuleBuildContext context, final AccumulateDescr accumDescr, MVELDialect dialect, Map<String, Declaration> decls, Map<String, Declaration> sourceOuterDeclr, BoundIdentifiers boundIds, boolean readLocalsFromTuple, RuleConditionElement source, Map<String, Class<?>> declarationClasses) {
    Accumulator[] accumulators;
    List<AccumulateFunctionCallDescr> functions = accumDescr.getFunctions();
    accumulators = new Accumulator[functions.size()];
    // creating the custom array reader
    InternalReadAccessor arrayReader = new SelfReferenceClassFieldReader(Object[].class);
    int index = 0;
    Pattern pattern = (Pattern) context.getDeclarationResolver().peekBuildStack();
    for (AccumulateFunctionCallDescr func : functions) {
        // build an external function executor
        Supplier<Class<?>> classSupplier = () -> MVELExprAnalyzer.getExpressionType(context, declarationClasses, source, func.getParams()[0]);
        String functionName = AccumulateUtil.getFunctionName(classSupplier, func.getFunction());
        AccumulateFunction function = context.getConfiguration().getAccumulateFunction(functionName);
        if (function == null) {
            // might have been imported in the package
            function = context.getPkg().getAccumulateFunctions().get(func.getFunction());
        }
        if (function == null) {
            context.addError(new DescrBuildError(accumDescr, context.getRuleDescr(), null, "Unknown accumulate function: '" + func.getFunction() + "' on rule '" + context.getRuleDescr().getName() + "'. All accumulate functions must be registered before building a resource."));
            return null;
        }
        final AnalysisResult analysis = dialect.analyzeExpression(context, accumDescr, func.getParams().length > 0 ? func.getParams()[0] : "\"\"", boundIds);
        MVELCompilationUnit unit = dialect.getMVELCompilationUnit(func.getParams().length > 0 ? func.getParams()[0] : "\"\"", analysis, getUsedDeclarations(decls, analysis), getUsedDeclarations(sourceOuterDeclr, analysis), null, context, "drools", KnowledgeHelper.class, readLocalsFromTuple, MVELCompilationUnit.Scope.CONSTRAINT);
        accumulators[index] = new MVELAccumulatorFunctionExecutor(unit, function);
        // if there is a binding, create the binding
        if (func.getBind() != null) {
            if (context.getDeclarationResolver().isDuplicated(context.getRule(), func.getBind(), function.getResultType().getName())) {
                if (!func.isUnification()) {
                    context.addError(new DescrBuildError(context.getParentDescr(), accumDescr, null, "Duplicate declaration for variable '" + func.getBind() + "' in the rule '" + context.getRule().getName() + "'"));
                } else {
                    Declaration inner = context.getDeclarationResolver().getDeclaration(func.getBind());
                    Constraint c = new MVELConstraint(Collections.singletonList(context.getPkg().getName()), accumDescr.isMultiFunction() ? "this[ " + index + " ] == " + func.getBind() : "this == " + func.getBind(), new Declaration[] { inner }, null, null, IndexUtil.ConstraintType.EQUAL, context.getDeclarationResolver().getDeclaration(func.getBind()), accumDescr.isMultiFunction() ? new ArrayElementReader(arrayReader, index, function.getResultType()) : new SelfReferenceClassFieldReader(function.getResultType()), true);
                    ((MutableTypeConstraint) c).setType(Constraint.ConstraintType.BETA);
                    pattern.addConstraint(c);
                    index++;
                }
            } else {
                Declaration declr = pattern.addDeclaration(func.getBind());
                if (accumDescr.isMultiFunction()) {
                    declr.setReadAccessor(new ArrayElementReader(arrayReader, index, function.getResultType()));
                } else {
                    declr.setReadAccessor(new SelfReferenceClassFieldReader(function.getResultType()));
                }
            }
        }
        index++;
    }
    return accumulators;
}
Also used : Accumulator(org.drools.core.spi.Accumulator) MVELAccumulator(org.drools.mvel.expr.MVELAccumulator) MvelAccumulator(org.drools.core.spi.MvelAccumulator) Pattern(org.drools.core.rule.Pattern) MVELAccumulatorFunctionExecutor(org.drools.mvel.expr.MVELAccumulatorFunctionExecutor) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MVELConstraint(org.drools.mvel.MVELConstraint) Constraint(org.drools.core.spi.Constraint) MVELCompilationUnit(org.drools.mvel.expr.MVELCompilationUnit) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MVELConstraint(org.drools.mvel.MVELConstraint) Constraint(org.drools.core.spi.Constraint) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) MVELConstraint(org.drools.mvel.MVELConstraint) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) AccumulateFunctionCallDescr(org.drools.drl.ast.descr.AccumulateDescr.AccumulateFunctionCallDescr) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) Declaration(org.drools.core.rule.Declaration) AccumulateFunction(org.kie.api.runtime.rule.AccumulateFunction)

Example 10 with MVELConstraint

use of org.drools.mvel.MVELConstraint in project drools by kiegroup.

the class SharingTest method assertNonHashableConstraint.

private void assertNonHashableConstraint(ObjectTypeNode otn, String expected) {
    CompositeObjectSinkAdapter sinkAdapter = (CompositeObjectSinkAdapter) otn.getObjectSinkPropagator();
    AlphaNode alpha = (AlphaNode) sinkAdapter.getOtherSinks().get(0);
    AlphaNodeFieldConstraint constraint = alpha.getConstraint();
    if (constraint instanceof MVELConstraint) {
        assertEquals(expected, ((MVELConstraint) constraint).getExpression());
    } else if (constraint instanceof LambdaConstraint) {
        assertEquals(expected, ((LambdaConstraint) constraint).getPredicateInformation().getStringConstraint());
    }
}
Also used : AlphaNodeFieldConstraint(org.drools.core.spi.AlphaNodeFieldConstraint) MVELConstraint(org.drools.mvel.MVELConstraint) LambdaConstraint(org.drools.modelcompiler.constraints.LambdaConstraint) CompositeObjectSinkAdapter(org.drools.core.reteoo.CompositeObjectSinkAdapter) AlphaNode(org.drools.core.reteoo.AlphaNode)

Aggregations

MVELConstraint (org.drools.mvel.MVELConstraint)11 Test (org.junit.Test)6 AlphaNode (org.drools.core.reteoo.AlphaNode)5 AlphaNodeFieldConstraint (org.drools.core.spi.AlphaNodeFieldConstraint)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)4 ObjectTypeNode (org.drools.core.reteoo.ObjectTypeNode)4 Address (org.drools.mvel.compiler.Address)4 Person (org.drools.mvel.compiler.Person)4 MVELObjectClassFieldReader (org.drools.mvel.extractors.MVELObjectClassFieldReader)4 KieBase (org.kie.api.KieBase)4 Pattern (org.drools.core.rule.Pattern)3 KieSession (org.kie.api.runtime.KieSession)3 StatelessKieSession (org.kie.api.runtime.StatelessKieSession)3 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)2 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)2 ArrayElementReader (org.drools.core.base.extractors.ArrayElementReader)2 ByteArrayResource (org.drools.core.io.impl.ByteArrayResource)2 BuildContext (org.drools.core.reteoo.builder.BuildContext)2