Search in sources :

Example 76 with Declaration

use of org.drools.core.rule.Declaration in project drools by kiegroup.

the class LambdaConsequence method evaluate.

@Override
public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
    Tuple tuple = knowledgeHelper.getTuple();
    Declaration[] declarations = ((RuleTerminalNode) knowledgeHelper.getMatch().getTuple().getTupleSink()).getRequiredDeclarations();
    Variable[] vars = consequence.getVariables();
    Object[] facts;
    int factsOffset = 0;
    if (consequence.isUsingDrools()) {
        factsOffset++;
        facts = new Object[vars.length + 1];
        facts[0] = new DroolsImpl(knowledgeHelper, workingMemory);
    } else {
        facts = new Object[vars.length];
    }
    int declrCounter = 0;
    for (Variable var : vars) {
        if (var.isFact()) {
            Declaration declaration = declarations[declrCounter++];
            InternalFactHandle fh = tuple.get(declaration);
            if (consequence.isUsingDrools()) {
                ((DroolsImpl) facts[0]).registerFactHandle(fh);
            }
            facts[factsOffset++] = declaration.getValue((InternalWorkingMemory) workingMemory, fh.getObject());
        } else {
            facts[factsOffset++] = workingMemory.getGlobal(var.getName());
        }
    }
    consequence.getBlock().execute(facts);
    Object[] objs = knowledgeHelper.getTuple().toObjects();
    for (org.drools.model.Consequence.Update update : consequence.getUpdates()) {
        Object updatedFact = context.getBoundFact(update.getUpdatedVariable(), objs);
        // TODO the Update specs has the changed fields so use update(FactHandle newObject, long mask, Class<?> modifiedClass) instead
        knowledgeHelper.update(updatedFact);
    }
    for (FunctionN insert : consequence.getInserts()) {
        Object insertedFact = insert.apply(facts);
        knowledgeHelper.insert(insertedFact);
    }
    for (Variable delete : consequence.getDeletes()) {
        Object deletedFact = context.getBoundFact(delete, objs);
        knowledgeHelper.delete(deletedFact);
    }
}
Also used : Variable(org.drools.model.Variable) FunctionN(org.drools.model.functions.FunctionN) Consequence(org.drools.core.spi.Consequence) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) Declaration(org.drools.core.rule.Declaration) InternalFactHandle(org.drools.core.common.InternalFactHandle) Tuple(org.drools.core.spi.Tuple) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode)

Example 77 with Declaration

use of org.drools.core.rule.Declaration in project drools by kiegroup.

the class MVELConsequence method evaluate.

@Override
public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
    // same as lambda consequence...
    Tuple tuple = knowledgeHelper.getTuple();
    Declaration[] declarations = ((RuleTerminalNode) knowledgeHelper.getMatch().getTuple().getTupleSink()).getRequiredDeclarations();
    Variable[] vars = consequence.getVariables();
    // ...but the facts are association of Variable and its value, preserving order.
    Map<Variable, Object> facts = new LinkedHashMap<>();
    int declrCounter = 0;
    for (Variable var : vars) {
        if (var.isFact()) {
            Declaration declaration = declarations[declrCounter++];
            InternalFactHandle fh = tuple.get(declaration);
            facts.put(var, declaration.getValue((InternalWorkingMemory) workingMemory, fh.getObject()));
        } else {
            facts.put(var, workingMemory.getGlobal(var.getName()));
        }
    }
    ScriptBlock scriptBlock = null;
    try {
        scriptBlock = (ScriptBlock) consequence.getBlock();
    } catch (ClassCastException e) {
        throw new RuntimeException("I tried to access a ScriptBlock but it was not. So something is thinking is a MVEL consequence but did not set the MVEL script textual representation", e);
    }
    String originalRHS = scriptBlock.getScript();
    String name = context.getRule().getPackageName() + "." + context.getRule().getName();
    String expression = MVELConsequenceBuilder.processMacros(originalRHS);
    String[] globalIdentifiers = new String[] {};
    String[] default_inputIdentifiers = new String[] { "this", "drools", "kcontext", "rule" };
    String[] inputIdentifiers = Stream.concat(Arrays.asList(default_inputIdentifiers).stream(), facts.entrySet().stream().map(kv -> kv.getKey().getName())).collect(Collectors.toList()).toArray(new String[] {});
    String[] default_inputTypes = new String[] { "org.drools.core.spi.KnowledgeHelper", "org.drools.core.spi.KnowledgeHelper", "org.drools.core.spi.KnowledgeHelper", "org.kie.api.definition.rule.Rule" };
    String[] inputTypes = Stream.concat(Arrays.asList(default_inputTypes).stream(), facts.entrySet().stream().map(kv -> kv.getKey().getType().getName())).collect(Collectors.toList()).toArray(new String[] {});
    // ^^ please notice about inputTypes, it is to use the Class.getName(), because is later used by the Classloader internally in MVEL to load the class,
    // do NOT replace with getCanonicalName() otherwise inner classes will not be loaded correctly.
    int languageLevel = 4;
    boolean strictMode = true;
    boolean readLocalsFromTuple = false;
    EvaluatorWrapper[] operators = new EvaluatorWrapper[] {};
    Declaration[] previousDeclarations = new Declaration[] {};
    Declaration[] localDeclarations = new Declaration[] {};
    String[] otherIdentifiers = new String[] {};
    MVELCompilationUnit cu = new MVELCompilationUnit(name, expression, globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, strictMode, readLocalsFromTuple);
    // TODO unfortunately the MVELDialectRuntimeData would be the one of compile time
    // the one from runtime is not helpful, in fact the dialect registry for runtime is empty:
    // MVELDialectRuntimeData runtimeData = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
    MVELDialectRuntimeData runtimeData = new MVELDialectRuntimeData();
    // this classloader will be used by the CompilationUnit to load the imports.
    runtimeData.onAdd(null, Thread.currentThread().getContextClassLoader());
    runtimeData.addPackageImport(context.getPkg().getName());
    runtimeData.addPackageImport("java.lang");
    // therefore we assume for the ScriptBlock all available KBPackages are the default available and imported for the scope of the Script itself.
    for (KiePackage kp : context.getKnowledgePackages()) {
        if (!kp.getName().equals(context.getPkg().getName())) {
            runtimeData.addPackageImport(kp.getName());
        }
    }
    // sometimes here it was passed as a 2nd argument a String?? similar to `rule R in file file.drl`
    Serializable cuResult = cu.getCompiledExpression(runtimeData);
    ExecutableStatement compiledExpression = (ExecutableStatement) cuResult;
    // TODO the part above up to the ExecutableStatement compiledExpression should be cached.
    Map<String, Object> mvelContext = new HashMap<>();
    mvelContext.put("this", knowledgeHelper);
    mvelContext.put("drools", knowledgeHelper);
    mvelContext.put("kcontext", knowledgeHelper);
    mvelContext.put("rule", knowledgeHelper.getRule());
    for (Entry<Variable, Object> kv : facts.entrySet()) {
        mvelContext.put(kv.getKey().getName(), kv.getValue());
    }
    CachingMapVariableResolverFactory cachingFactory = new CachingMapVariableResolverFactory(mvelContext);
    VariableResolverFactory factory = cu.getFactory(knowledgeHelper, ((AgendaItem) knowledgeHelper.getMatch()).getTerminalNode().getRequiredDeclarations(), knowledgeHelper.getRule(), knowledgeHelper.getTuple(), null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver());
    cachingFactory.setNextFactory(factory);
    MVEL.executeExpression(compiledExpression, knowledgeHelper, cachingFactory);
}
Also used : ScriptBlock(org.drools.model.functions.ScriptBlock) AgendaItem(org.drools.core.common.AgendaItem) ExecutableStatement(org.mvel2.compiler.ExecutableStatement) Arrays(java.util.Arrays) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) InternalFactHandle(org.drools.core.common.InternalFactHandle) HashMap(java.util.HashMap) RuleContext(org.drools.modelcompiler.RuleContext) LinkedHashMap(java.util.LinkedHashMap) MVELConsequenceBuilder(org.drools.compiler.rule.builder.dialect.mvel.MVELConsequenceBuilder) Map(java.util.Map) Declaration(org.drools.core.rule.Declaration) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) KiePackage(org.kie.api.definition.KiePackage) WorkingMemory(org.drools.core.WorkingMemory) Variable(org.drools.model.Variable) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) Consequence(org.drools.core.spi.Consequence) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) CachingMapVariableResolverFactory(org.mvel2.integration.impl.CachingMapVariableResolverFactory) Stream(java.util.stream.Stream) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) Tuple(org.drools.core.spi.Tuple) ScriptBlock(org.drools.model.functions.ScriptBlock) Entry(java.util.Map.Entry) MVEL(org.mvel2.MVEL) EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) Serializable(java.io.Serializable) Variable(org.drools.model.Variable) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) AgendaItem(org.drools.core.common.AgendaItem) LinkedHashMap(java.util.LinkedHashMap) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) MVELDialectRuntimeData(org.drools.core.rule.MVELDialectRuntimeData) KiePackage(org.kie.api.definition.KiePackage) CachingMapVariableResolverFactory(org.mvel2.integration.impl.CachingMapVariableResolverFactory) Declaration(org.drools.core.rule.Declaration) InternalFactHandle(org.drools.core.common.InternalFactHandle) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) ExecutableStatement(org.mvel2.compiler.ExecutableStatement) EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) CachingMapVariableResolverFactory(org.mvel2.integration.impl.CachingMapVariableResolverFactory) Tuple(org.drools.core.spi.Tuple)

Example 78 with Declaration

use of org.drools.core.rule.Declaration in project drools by kiegroup.

the class LeftLeftTupleIndexHashTableIteratorTest method getConstraint.

protected BetaNodeFieldConstraint getConstraint(String identifier, Operator operator, String fieldName, Class clazz) {
    ClassFieldAccessorStore store = new ClassFieldAccessorStore();
    store.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);
    InternalReadAccessor extractor = store.getReader(clazz, fieldName);
    Declaration declaration = new Declaration(identifier, extractor, new Pattern(0, new ClassObjectType(clazz)));
    String expression = fieldName + " " + operator.getOperatorString() + " " + declaration.getIdentifier();
    return new MvelConstraintTestUtil(expression, declaration, extractor);
}
Also used : ClassFieldAccessorCache(org.drools.core.base.ClassFieldAccessorCache) Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) ClassFieldAccessorStore(org.drools.core.base.ClassFieldAccessorStore) Declaration(org.drools.core.rule.Declaration) MvelConstraintTestUtil(org.drools.core.rule.MvelConstraintTestUtil)

Example 79 with Declaration

use of org.drools.core.rule.Declaration in project drools by kiegroup.

the class JavaAccumulateBuilder method collectRequiredDeclarations.

private Declaration[] collectRequiredDeclarations(Map<String, Declaration> declsInScope, Set<Declaration> requiredDecl, final BoundIdentifiers usedIdentifiers) {
    final Declaration[] previousDeclarations = new Declaration[usedIdentifiers.getDeclrClasses().size()];
    int i = 0;
    for (String key : usedIdentifiers.getDeclrClasses().keySet()) {
        Declaration d = declsInScope.get(key);
        previousDeclarations[i++] = d;
        requiredDecl.add(d);
    }
    return previousDeclarations;
}
Also used : Declaration(org.drools.core.rule.Declaration) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Constraint(org.drools.core.spi.Constraint)

Example 80 with Declaration

use of org.drools.core.rule.Declaration 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) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Constraint(org.drools.core.spi.Constraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) Declaration(org.drools.core.rule.Declaration)

Aggregations

Declaration (org.drools.core.rule.Declaration)115 Pattern (org.drools.core.rule.Pattern)42 ClassObjectType (org.drools.core.base.ClassObjectType)29 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)27 TypeDeclaration (org.drools.core.rule.TypeDeclaration)24 InternalFactHandle (org.drools.core.common.InternalFactHandle)22 ArrayList (java.util.ArrayList)19 HashMap (java.util.HashMap)17 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)17 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)16 Test (org.junit.Test)16 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)14 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)12 WorkingMemory (org.drools.core.WorkingMemory)11 MVELCompilationUnit (org.drools.core.base.mvel.MVELCompilationUnit)11 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)11 MvelConstraint (org.drools.core.rule.constraint.MvelConstraint)10 Consequence (org.drools.core.spi.Consequence)10 Constraint (org.drools.core.spi.Constraint)10 AnalysisResult (org.drools.compiler.compiler.AnalysisResult)9