Search in sources :

Example 1 with Constraint

use of org.drools.core.spi.Constraint in project drools by kiegroup.

the class PatternBuilder method combineConstraints.

private void combineConstraints(RuleBuildContext context, Pattern pattern, MVELDumper.MVELDumperContext mvelCtx) {
    List<MvelConstraint> combinableConstraints = pattern.getCombinableConstraints();
    if (combinableConstraints == null || combinableConstraints.size() < 2) {
        return;
    }
    List<Declaration> declarations = new ArrayList<Declaration>();
    List<EvaluatorWrapper> operators = new ArrayList<EvaluatorWrapper>();
    Set<String> declarationNames = new HashSet<String>();
    boolean isFirst = true;
    Collection<String> packageNames = null;
    StringBuilder expressionBuilder = new StringBuilder(combinableConstraints.size() * 25);
    for (MvelConstraint constraint : combinableConstraints) {
        pattern.removeConstraint(constraint);
        if (isFirst) {
            packageNames = constraint.getPackageNames();
            isFirst = false;
        } else {
            expressionBuilder.append(" && ");
        }
        String constraintExpression = constraint.getExpression();
        boolean isComplex = constraintExpression.contains("&&") || constraintExpression.contains("||");
        if (isComplex) {
            expressionBuilder.append("( ");
        }
        expressionBuilder.append(constraintExpression);
        if (isComplex) {
            expressionBuilder.append(" )");
        }
        for (Declaration declaration : constraint.getRequiredDeclarations()) {
            if (declarationNames.add(declaration.getBindingName())) {
                declarations.add(declaration);
            }
        }
        Collections.addAll(operators, constraint.getOperators());
    }
    String expression = expressionBuilder.toString();
    MVELCompilationUnit compilationUnit = getConstraintBuilder(context).buildCompilationUnit(context, pattern, expression, mvelCtx.getAliases());
    Constraint combinedConstraint = getConstraintBuilder(context).buildMvelConstraint(packageNames, expression, declarations.toArray(new Declaration[declarations.size()]), operators.toArray(new EvaluatorWrapper[operators.size()]), compilationUnit, IndexUtil.ConstraintType.UNKNOWN, null, null, false);
    pattern.addConstraint(combinedConstraint);
}
Also used : EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) NegConstraint(org.drools.core.rule.constraint.NegConstraint) Constraint(org.drools.core.spi.Constraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) EvaluatorConstraint(org.drools.core.rule.constraint.EvaluatorConstraint) PredicateConstraint(org.drools.core.rule.PredicateConstraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) ArrayList(java.util.ArrayList) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) Declaration(org.drools.core.rule.Declaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration) HashSet(java.util.HashSet)

Example 2 with Constraint

use of org.drools.core.spi.Constraint 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) {
    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
        AccumulateFunction function = context.getConfiguration().getAccumulateFunction(func.getFunction());
        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 : MVELAccumulator(org.drools.core.base.mvel.MVELAccumulator) Accumulator(org.drools.core.spi.Accumulator) MvelAccumulator(org.drools.core.spi.MvelAccumulator) Pattern(org.drools.core.rule.Pattern) MVELAccumulatorFunctionExecutor(org.drools.core.base.accumulators.MVELAccumulatorFunctionExecutor) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Constraint(org.drools.core.spi.Constraint) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Constraint(org.drools.core.spi.Constraint) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) 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)

Example 3 with Constraint

use of org.drools.core.spi.Constraint in project drools by kiegroup.

the class Pattern method clone.

public Pattern clone() {
    final String identifier = (this.declaration != null) ? this.declaration.getIdentifier() : null;
    final Pattern clone = new Pattern(this.index, this.offset, this.objectType, identifier, this.declaration != null && this.declaration.isInternalFact());
    clone.setListenedProperties(getListenedProperties());
    if (this.getSource() != null) {
        clone.setSource((PatternSource) this.getSource().clone());
        if (source instanceof From) {
            ((From) clone.getSource()).setResultPattern(clone);
        }
    }
    for (Declaration decl : this.declarations.values()) {
        Declaration addedDeclaration = clone.addDeclaration(decl.getIdentifier());
        addedDeclaration.setReadAccessor(decl.getExtractor());
        addedDeclaration.setBindingName(decl.getBindingName());
    }
    for (Constraint oldConstr : this.constraints) {
        Constraint clonedConstr = oldConstr.clone();
        // we must update pattern references in cloned declarations
        Declaration[] oldDecl = oldConstr.getRequiredDeclarations();
        Declaration[] newDecl = clonedConstr.getRequiredDeclarations();
        for (int i = 0; i < newDecl.length; i++) {
            if (newDecl[i].getPattern() == this) {
                newDecl[i].setPattern(clone);
                // we still need to call replace because there might be nested declarations to replace
                clonedConstr.replaceDeclaration(oldDecl[i], newDecl[i]);
            }
        }
        clone.addConstraint(clonedConstr);
    }
    if (behaviors != null) {
        for (Behavior behavior : this.behaviors) {
            clone.addBehavior(behavior);
        }
    }
    return clone;
}
Also used : MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) Constraint(org.drools.core.spi.Constraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) Constraint(org.drools.core.spi.Constraint)

Example 4 with Constraint

use of org.drools.core.spi.Constraint in project drools by kiegroup.

the class Pattern method setConstraintType.

private void setConstraintType(final MutableTypeConstraint constraint) {
    final Declaration[] declarations = constraint.getRequiredDeclarations();
    boolean isAlphaConstraint = true;
    for (int i = 0; isAlphaConstraint && i < declarations.length; i++) {
        if (!declarations[i].isGlobal() && declarations[i].getPattern() != this) {
            isAlphaConstraint = false;
        }
    }
    ConstraintType type = isAlphaConstraint ? ConstraintType.ALPHA : ConstraintType.BETA;
    constraint.setType(type);
}
Also used : ConstraintType(org.drools.core.spi.Constraint.ConstraintType) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) Constraint(org.drools.core.spi.Constraint)

Example 5 with Constraint

use of org.drools.core.spi.Constraint in project drools by kiegroup.

the class DefaultTemplateRuleBaseTest method testSimpleTemplate.

@SuppressWarnings("unchecked")
@Test
public void testSimpleTemplate() throws Exception {
    TemplateContainer tc = new TemplateContainer() {

        private Column[] columns = new Column[] { new LongColumn("column1"), new LongColumn("column2"), new StringColumn("column3") };

        public Column[] getColumns() {
            return columns;
        }

        public String getHeader() {
            return null;
        }

        public Map<String, RuleTemplate> getTemplates() {
            Map<String, RuleTemplate> templates = new HashMap<String, RuleTemplate>();
            RuleTemplate ruleTemplate = new RuleTemplate("template1", this);
            ruleTemplate.addColumn("column1 == 10");
            ruleTemplate.addColumn("column2 < 5 || > 20");
            ruleTemplate.addColumn("column3 == \"xyz\"");
            templates.put("template1", ruleTemplate);
            return templates;
        }

        public Column getColumn(String name) {
            return columns[Integer.parseInt(name.substring(6)) - 1];
        }
    };
    DefaultTemplateRuleBase ruleBase = new DefaultTemplateRuleBase(tc);
    InternalKnowledgePackage[] packages = ((KnowledgeBaseImpl) ruleBase.newStatefulSession().getKieBase()).getPackages();
    assertEquals(1, packages.length);
    Map<String, String> globals = packages[0].getGlobals();
    assertEquals(DefaultGenerator.class.getName(), globals.get("generator"));
    Collection<org.kie.api.definition.rule.Rule> rules = packages[0].getRules();
    assertEquals(1, rules.size());
    assertEquals("template1", rules.iterator().next().getName());
    GroupElement lhs = ((RuleImpl) rules.iterator().next()).getLhs();
    // when
    // r : Row()
    // column1 : Column(name == "column1")
    // exists LongCell(row == r, column == column1, value == 10)
    // column2 : Column(name == "column2")
    // exists LongCell(row == r, column == column2, value < 5 | > 20)
    // column3 : Column(name == "column3")
    // exists StringCell(row == r, column == column3, value == "xyz")
    assertEquals(7, lhs.getChildren().size());
    org.drools.core.rule.Pattern pattern = (org.drools.core.rule.Pattern) lhs.getChildren().get(1);
    assertEquals(1, pattern.getConstraints().size());
    Constraint constraint = pattern.getConstraints().get(0);
    GroupElement exists = (GroupElement) lhs.getChildren().get(2);
    pattern = (org.drools.core.rule.Pattern) exists.getChildren().get(0);
    assertEquals(3, pattern.getConstraints().size());
    IndexableConstraint vconstraint = (IndexableConstraint) pattern.getConstraints().get(1);
    assertEquals(Column.class, vconstraint.getFieldIndex().getExtractor().getExtractToClass());
    assertEquals("column1", vconstraint.getRequiredDeclarations()[0].getIdentifier());
    pattern = (org.drools.core.rule.Pattern) lhs.getChildren().get(3);
    assertEquals(1, pattern.getConstraints().size());
    constraint = pattern.getConstraints().get(0);
    exists = (GroupElement) lhs.getChildren().get(4);
    pattern = (org.drools.core.rule.Pattern) exists.getChildren().get(0);
    assertEquals(3, pattern.getConstraints().size());
    vconstraint = (IndexableConstraint) pattern.getConstraints().get(1);
    assertEquals(Column.class, vconstraint.getFieldIndex().getExtractor().getExtractToClass());
    assertEquals("column2", vconstraint.getRequiredDeclarations()[0].getIdentifier());
    pattern = (org.drools.core.rule.Pattern) lhs.getChildren().get(5);
    assertEquals(1, pattern.getConstraints().size());
    constraint = pattern.getConstraints().get(0);
    exists = (GroupElement) lhs.getChildren().get(6);
    pattern = (org.drools.core.rule.Pattern) exists.getChildren().get(0);
    assertEquals(3, pattern.getConstraints().size());
    vconstraint = (IndexableConstraint) pattern.getConstraints().get(1);
    assertEquals(Column.class, vconstraint.getFieldIndex().getExtractor().getExtractToClass());
    assertEquals("column3", vconstraint.getRequiredDeclarations()[0].getIdentifier());
}
Also used : HashMap(java.util.HashMap) Constraint(org.drools.core.spi.Constraint) IndexableConstraint(org.drools.core.rule.IndexableConstraint) GroupElement(org.drools.core.rule.GroupElement) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) IndexableConstraint(org.drools.core.rule.IndexableConstraint) KnowledgeBaseImpl(org.drools.core.impl.KnowledgeBaseImpl) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Test(org.junit.Test)

Aggregations

Constraint (org.drools.core.spi.Constraint)21 MvelConstraint (org.drools.core.rule.constraint.MvelConstraint)16 XpathConstraint (org.drools.core.rule.constraint.XpathConstraint)14 PredicateConstraint (org.drools.core.rule.PredicateConstraint)13 EvaluatorConstraint (org.drools.core.rule.constraint.EvaluatorConstraint)11 NegConstraint (org.drools.core.rule.constraint.NegConstraint)11 Declaration (org.drools.core.rule.Declaration)6 TypeDeclaration (org.drools.core.rule.TypeDeclaration)6 Pattern (org.drools.core.rule.Pattern)5 ArrayList (java.util.ArrayList)4 BindingDescr (org.drools.compiler.lang.descr.BindingDescr)3 ConstraintConnectiveDescr (org.drools.compiler.lang.descr.ConstraintConnectiveDescr)3 ArrayElementReader (org.drools.core.base.extractors.ArrayElementReader)3 Test (org.junit.Test)3 AnalysisResult (org.drools.compiler.compiler.AnalysisResult)2 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)2 MVELDumper (org.drools.compiler.lang.MVELDumper)2 BaseDescr (org.drools.compiler.lang.descr.BaseDescr)2 ExprConstraintDescr (org.drools.compiler.lang.descr.ExprConstraintDescr)2 JavaDialect (org.drools.compiler.rule.builder.dialect.java.JavaDialect)2