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);
}
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;
}
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;
}
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);
}
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());
}
Aggregations