Search in sources :

Example 41 with VariableResolverFactory

use of org.mule.mvel2.integration.VariableResolverFactory in project mvel by mvel.

the class MacroProcessorTest method testMacroSupportWithDebugging.

public void testMacroSupportWithDebugging() {
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("foo", new Foo());
    Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
    Map<String, Macro> macros = new HashMap<String, Macro>();
    interceptors.put("Modify", new Interceptor() {

        public int doBefore(ASTNode node, VariableResolverFactory factory) {
            ((WithNode) node).getNestedStatement().getValue(null, factory);
            factory.createVariable("mod", "FOOBAR!");
            return 0;
        }

        public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) {
            return 0;
        }
    });
    macros.put("modify", new Macro() {

        public String doMacro() {
            return "@Modify with";
        }
    });
    ParserContext ctx = new ParserContext(null, interceptors, null);
    ctx.setSourceFile("test.mv");
    ctx.setDebugSymbols(true);
    ExpressionCompiler compiler = new ExpressionCompiler(parseMacros("System.out.println('hello');\n" + "System.out.println('bye');\n" + "modify (foo) { aValue = 'poo', \n" + " aValue = 'poo' };\n mod", macros), ctx);
    // compiler.setDebugSymbols(true);
    CompiledExpression compiled = compiler.compile();
    MVELRuntime.setThreadDebugger(new Debugger() {

        public int onBreak(Frame frame) {
            System.out.println(frame.getSourceName() + ":" + frame.getLineNumber());
            return Debugger.STEP;
        }
    });
    MVELRuntime.registerBreakpoint("test.mv", 3);
    System.out.println(DebugTools.decompile(compiled));
    Assert.assertEquals("FOOBAR!", MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(vars)));
}
Also used : Debugger(org.mvel2.debug.Debugger) Frame(org.mvel2.debug.Frame) HashMap(java.util.HashMap) Macro(org.mvel2.Macro) Foo(org.mvel2.tests.core.res.Foo) WithNode(org.mvel2.ast.WithNode) CompiledExpression(org.mvel2.compiler.CompiledExpression) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory) ASTNode(org.mvel2.ast.ASTNode) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory) ExpressionCompiler(org.mvel2.compiler.ExpressionCompiler) ParserContext(org.mvel2.ParserContext) Interceptor(org.mvel2.integration.Interceptor)

Example 42 with VariableResolverFactory

use of org.mule.mvel2.integration.VariableResolverFactory in project mvel by mvel.

the class StackDelimiterResolverFactory method createVariable.

public VariableResolver createVariable(String name, Object value) {
    VariableResolverFactory delegate = getDelegate();
    VariableResolverFactory nextFactory = delegate.getNextFactory();
    delegate.setNextFactory(null);
    VariableResolver resolver = delegate.createVariable(name, value);
    delegate.setNextFactory(nextFactory);
    return resolver;
}
Also used : VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) VariableResolver(org.mvel2.integration.VariableResolver)

Example 43 with VariableResolverFactory

use of org.mule.mvel2.integration.VariableResolverFactory in project drools by kiegroup.

the class DefaultGenerator method generate.

/*
     * (non-Javadoc)
     * 
     * @see org.kie.decisiontable.parser.Generator#generate(java.lang.String,
     *      org.kie.decisiontable.parser.Row)
     */
public void generate(String templateName, Row row) {
    try {
        CompiledTemplate template = getTemplate(templateName);
        VariableResolverFactory factory = new MapVariableResolverFactory();
        Map<String, Object> vars = new HashMap<String, Object>();
        initializePriorCommaConstraints(vars);
        initializeHasPriorJunctionConstraint(vars);
        vars.put("row", row);
        for (Cell cell : row.getCells()) {
            cell.addValue(vars);
        }
        String drl = String.valueOf(TemplateRuntime.execute(template, vars, factory, registry));
        rules.add(drl);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory) HashMap(java.util.HashMap) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory) IOException(java.io.IOException) CompiledTemplate(org.mvel2.templates.CompiledTemplate)

Example 44 with VariableResolverFactory

use of org.mule.mvel2.integration.VariableResolverFactory 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 45 with VariableResolverFactory

use of org.mule.mvel2.integration.VariableResolverFactory in project drools by kiegroup.

the class MvelConditionEvaluator method evaluate.

private boolean evaluate(ExecutableStatement statement, InternalFactHandle handle, InternalWorkingMemory workingMemory, Tuple tuple) {
    if (compilationUnit == null) {
        Map<String, Object> vars = valuesAsMap(handle.getObject(), workingMemory, tuple, declarations);
        if (operators.length > 0) {
            if (vars == null) {
                vars = new HashMap<String, Object>();
            }
            InternalFactHandle[] handles = tuple != null ? tuple.toFactHandles() : new InternalFactHandle[0];
            for (EvaluatorWrapper operator : operators) {
                vars.put(operator.getBindingName(), operator);
                operator.loadHandles(workingMemory, handles, handle);
            }
        }
        return evaluate(statement, handle.getObject(), vars);
    }
    VariableResolverFactory factory = compilationUnit.createFactory();
    compilationUnit.updateFactory(handle, tuple, null, workingMemory, workingMemory.getGlobalResolver(), factory);
    return (Boolean) MVELSafeHelper.getEvaluator().executeExpression(statement, handle.getObject(), factory);
}
Also used : EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) InternalFactHandle(org.drools.core.common.InternalFactHandle)

Aggregations

VariableResolverFactory (org.mvel2.integration.VariableResolverFactory)54 MapVariableResolverFactory (org.mvel2.integration.impl.MapVariableResolverFactory)28 DefaultLocalVariableResolverFactory (org.mvel2.integration.impl.DefaultLocalVariableResolverFactory)19 HashMap (java.util.HashMap)18 ParserContext (org.mvel2.ParserContext)10 ExpressionCompiler (org.mvel2.compiler.ExpressionCompiler)10 MVELDialectRuntimeData (org.drools.core.rule.MVELDialectRuntimeData)9 CompiledExpression (org.mvel2.compiler.CompiledExpression)9 ASTNode (org.mvel2.ast.ASTNode)8 Debugger (org.mvel2.debug.Debugger)8 Frame (org.mvel2.debug.Frame)8 Interceptor (org.mvel2.integration.Interceptor)8 LinkedHashMap (java.util.LinkedHashMap)7 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)7 WithNode (org.mvel2.ast.WithNode)6 IndexedVariableResolverFactory (org.mvel2.integration.impl.IndexedVariableResolverFactory)6 MapObject (org.mvel2.tests.core.res.MapObject)6 Macro (org.mvel2.Macro)4 Foo (org.mvel2.tests.core.res.Foo)4 DroolsVarFactory (org.drools.core.base.mvel.MVELCompilationUnit.DroolsVarFactory)3