Search in sources :

Example 71 with MapVariableResolverFactory

use of org.mvel2.integration.impl.MapVariableResolverFactory in project mvel by mvel.

the class DebuggerTests method testBreakpoints4.

public void testBreakpoints4() {
    String expression = "System.out.println('foo');\n" + "a = new Foo244();\n" + "update (a) { name = 'bar' };\n" + "System.out.println('name:' + a.name);\n" + "return a.name;";
    Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
    Map<String, Macro> macros = new HashMap<String, Macro>();
    class TestResult {

        boolean firedBefore;

        boolean firedAfter;
    }
    final TestResult result = new TestResult();
    interceptors.put("Update", new Interceptor() {

        public int doBefore(ASTNode node, VariableResolverFactory factory) {
            ((WithNode) node).getNestedStatement().getValue(null, factory);
            System.out.println("fired update interceptor -- before");
            result.firedBefore = true;
            return 0;
        }

        public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) {
            System.out.println("fired update interceptor -- after");
            result.firedAfter = true;
            return 0;
        }
    });
    macros.put("update", new Macro() {

        public String doMacro() {
            return "@Update with";
        }
    });
    expression = parseMacros(expression, macros);
    ParserContext ctx = new ParserContext();
    ctx.setDebugSymbols(true);
    ctx.setSourceFile("test2.mv");
    ctx.addImport("Foo244", Foo.class);
    ctx.setInterceptors(interceptors);
    ExpressionCompiler compiler = new ExpressionCompiler(expression, ctx);
    CompiledExpression compiled = compiler.compile();
    System.out.println("\nExpression:------------");
    System.out.println(expression);
    System.out.println("------------");
    MVELRuntime.registerBreakpoint("test2.mv", 3);
    MVELRuntime.registerBreakpoint("test2.mv", 4);
    MVELRuntime.registerBreakpoint("test2.mv", 5);
    final Set<Integer> breaked = new HashSet<Integer>();
    Debugger testDebugger = new Debugger() {

        public int onBreak(Frame frame) {
            System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]");
            breaked.add(frame.getLineNumber());
            return 0;
        }
    };
    MVELRuntime.setThreadDebugger(testDebugger);
    assertEquals("bar", MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap())));
    assertTrue("did not fire before", result.firedBefore);
    assertTrue("did not fire after", result.firedAfter);
    assertEquals("did not break at expected points", Make.Set.<Integer>$()._(3)._(4)._(5)._finish(), breaked);
}
Also used : Debugger(org.mvel2.debug.Debugger) Frame(org.mvel2.debug.Frame) HashMap(java.util.HashMap) Macro(org.mvel2.Macro) WithNode(org.mvel2.ast.WithNode) CompiledExpression(org.mvel2.compiler.CompiledExpression) DefaultLocalVariableResolverFactory(org.mvel2.integration.impl.DefaultLocalVariableResolverFactory) 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) HashSet(java.util.HashSet)

Example 72 with MapVariableResolverFactory

use of org.mvel2.integration.impl.MapVariableResolverFactory in project mvel by mvel.

the class MvelArrayTest method testDynamicOptimizerWorksFine.

public void testDynamicOptimizerWorksFine() {
    OptimizerFactory.setDefaultOptimizer("dynamic");
    Serializable compileExpression = MVEL.compileExpression(biglistTestScript);
    VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap());
    int actual = (Integer) executeExpression(compileExpression, factory);
    assertEquals(actual, 25);
}
Also used : Serializable(java.io.Serializable) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory) HashMap(java.util.HashMap) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory)

Example 73 with MapVariableResolverFactory

use of org.mvel2.integration.impl.MapVariableResolverFactory in project mvel by mvel.

the class AbstractTest method _test.

protected static Object _test(String ex) {
    ExpressionCompiler compiler = new ExpressionCompiler(ex);
    StringAppender failErrors = new StringAppender();
    CompiledExpression compiled = compiler.compile();
    Object first = null, second = null, third = null, fourth = null, fifth = null, sixth = null, seventh = null, eighth = null;
    System.out.println(DebugTools.decompile((Serializable) compiled));
    if (!Boolean.getBoolean("mvel2.disable.jit")) {
        setDefaultOptimizer("ASM");
        try {
            first = executeExpression(compiled, new Base(), createTestMap());
        } catch (Exception e) {
            failErrors.append("\nFIRST TEST: { " + ex + " }: EXCEPTION REPORT: \n\n");
            CharArrayWriter writer = new CharArrayWriter();
            e.printStackTrace(new PrintWriter(writer));
            failErrors.append(writer.toCharArray());
        }
        try {
            second = executeExpression(compiled, new Base(), createTestMap());
        } catch (Exception e) {
            failErrors.append("\nSECOND TEST: { " + ex + " }: EXCEPTION REPORT: \n\n");
            CharArrayWriter writer = new CharArrayWriter();
            e.printStackTrace(new PrintWriter(writer));
            failErrors.append(writer.toCharArray());
        }
    }
    try {
        third = MVEL.eval(ex, new Base(), createTestMap());
    } catch (Exception e) {
        failErrors.append("\nTHIRD TEST: { " + ex + " }: EXCEPTION REPORT: \n\n");
        CharArrayWriter writer = new CharArrayWriter();
        e.printStackTrace(new PrintWriter(writer));
        failErrors.append(writer.toCharArray());
    }
    if (first != null && !first.getClass().isArray()) {
        if (!first.equals(second)) {
            System.out.println(failErrors.toString());
            throw new AssertionError("Different result from test 1 and 2 (Compiled Re-Run / JIT) [first: " + valueOf(first) + "; second: " + valueOf(second) + "]");
        }
        if (!first.equals(third)) {
            if (failErrors != null)
                System.out.println(failErrors.toString());
            throw new AssertionError("Different result from test 1 and 3 (Compiled to Interpreted) [first: " + valueOf(first) + " (" + (first != null ? first.getClass().getName() : null) + "); third: " + valueOf(third) + " (" + (third != null ? third.getClass().getName() : "null") + ")]");
        }
    }
    setDefaultOptimizer("reflective");
    Serializable compiled2 = compileExpression(ex);
    try {
        fourth = executeExpression(compiled2, new Base(), createTestMap());
    } catch (Exception e) {
        if (failErrors == null)
            failErrors = new StringAppender();
        failErrors.append("\nFOURTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n");
        CharArrayWriter writer = new CharArrayWriter();
        e.printStackTrace(new PrintWriter(writer));
        failErrors.append(writer.toCharArray());
    }
    try {
        fifth = executeExpression(compiled2, new Base(), createTestMap());
    } catch (Exception e) {
        e.printStackTrace();
        if (failErrors == null)
            failErrors = new StringAppender();
        failErrors.append("\nFIFTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n");
        CharArrayWriter writer = new CharArrayWriter();
        e.printStackTrace(new PrintWriter(writer));
        failErrors.append(writer.toCharArray());
    }
    if (fourth != null && !fourth.getClass().isArray()) {
        if (!fourth.equals(fifth)) {
            throw new AssertionError("Different result from test 4 and 5 (Compiled Re-Run X2) [fourth: " + valueOf(fourth) + "; fifth: " + valueOf(fifth) + "]");
        }
    }
    ParserContext ctx = new ParserContext();
    ctx.setSourceFile("unittest");
    ctx.setDebugSymbols(true);
    ExpressionCompiler debuggingCompiler = new ExpressionCompiler(ex, ctx);
    // debuggingCompiler.setDebugSymbols(true);
    CompiledExpression compiledD = debuggingCompiler.compile();
    try {
        sixth = executeExpression(compiledD, new Base(), createTestMap());
    } catch (Exception e) {
        if (failErrors == null)
            failErrors = new StringAppender();
        failErrors.append("\nSIXTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n");
        CharArrayWriter writer = new CharArrayWriter();
        e.printStackTrace(new PrintWriter(writer));
        failErrors.append(writer.toCharArray());
    }
    if (sixth != null && !sixth.getClass().isArray()) {
        if (!fifth.equals(sixth)) {
            System.out.println("Payload 1 -- No Symbols: ");
            System.out.println(decompile(compiled));
            System.out.println();
            System.out.println("Payload 2 -- With Symbols: ");
            System.out.println(decompile(compiledD));
            System.out.println();
            throw new AssertionError("Different result from test 5 and 6 (Compiled to Compiled+DebuggingSymbols) [first: " + valueOf(fifth) + "; second: " + valueOf(sixth) + "]");
        }
    }
    try {
        seventh = executeExpression(compiledD, new Base(), createTestMap());
    } catch (Exception e) {
        if (failErrors == null)
            failErrors = new StringAppender();
        failErrors.append("\nSEVENTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n");
        CharArrayWriter writer = new CharArrayWriter();
        e.printStackTrace(new PrintWriter(writer));
        failErrors.append(writer.toCharArray());
    }
    if (seventh != null && !seventh.getClass().isArray()) {
        if (!seventh.equals(sixth)) {
            throw new AssertionError("Different result from test 4 and 5 (Compiled Re-Run / Reflective) [first: " + valueOf(first) + "; second: " + valueOf(second) + "]");
        }
    }
    try {
        Serializable xx = serializationTest(compiledD);
        eighth = executeExpression(xx, new Base(), new MapVariableResolverFactory(createTestMap()));
    } catch (Exception e) {
        if (failErrors == null)
            failErrors = new StringAppender();
        failErrors.append("\nEIGHTH TEST (Serializability): { " + ex + " }: EXCEPTION REPORT: \n\n");
        CharArrayWriter writer = new CharArrayWriter();
        e.printStackTrace(new PrintWriter(writer));
        failErrors.append(writer.toCharArray());
    }
    if (eighth != null && !eighth.getClass().isArray()) {
        if (!eighth.equals(seventh)) {
            throw new AssertionError("Different result from test 7 and 8 (Compiled Re-Run / Reflective) [first: " + valueOf(first) + "; second: " + valueOf(second) + "]");
        }
    }
    if (failErrors.length() > 0) {
        System.out.println(decompile(compiledD));
        throw new AssertionError("Detailed Failure Report:\n" + failErrors.toString());
    }
    return fourth;
}
Also used : Serializable(java.io.Serializable) StringAppender(org.mvel2.util.StringAppender) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory) ExpressionCompiler(org.mvel2.compiler.ExpressionCompiler) ParserContext(org.mvel2.ParserContext) CompiledExpression(org.mvel2.compiler.CompiledExpression) Base(org.mvel2.tests.core.res.Base) CharArrayWriter(java.io.CharArrayWriter) PrintWriter(java.io.PrintWriter)

Example 74 with MapVariableResolverFactory

use of org.mvel2.integration.impl.MapVariableResolverFactory in project drools by kiegroup.

the class JavaFunctionBuilder method build.

/* (non-Javadoc)
     * @see org.kie.rule.builder.dialect.java.JavaFunctionBuilder#build(org.kie.rule.Package, org.kie.lang.descr.FunctionDescr, org.codehaus.jfdi.interpreter.TypeResolver, java.util.Map)
     */
public String build(final InternalKnowledgePackage pkg, final FunctionDescr functionDescr, final TypeResolver typeResolver, final Map<String, LineMappings> lineMappings, final List<KnowledgeBuilderResult> errors) {
    final Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("package", pkg.getName());
    vars.put("imports", pkg.getImports().keySet());
    final List<String> staticImports = new LinkedList<String>();
    for (String staticImport : pkg.getStaticImports()) {
        if (!staticImport.endsWith(functionDescr.getName())) {
            staticImports.add(staticImport);
        }
    }
    vars.put("staticImports", staticImports);
    vars.put("className", StringUtils.ucFirst(functionDescr.getName()));
    vars.put("methodName", functionDescr.getName());
    vars.put("returnType", functionDescr.getReturnType());
    vars.put("parameterTypes", functionDescr.getParameterTypes());
    vars.put("parameterNames", functionDescr.getParameterNames());
    vars.put("hashCode", functionDescr.getText().hashCode());
    // Check that all the parameters are resolvable
    final List<String> names = functionDescr.getParameterNames();
    final List<String> types = functionDescr.getParameterTypes();
    for (int i = 0, size = names.size(); i < size; i++) {
        try {
            typeResolver.resolveType(types.get(i));
        } catch (final ClassNotFoundException e) {
            errors.add(new FunctionError(functionDescr, e, "Unable to resolve type " + types.get(i) + " while building function."));
            break;
        }
    }
    vars.put("text", functionDescr.getText());
    final String text = String.valueOf(TemplateRuntime.eval(template, null, new MapVariableResolverFactory(vars)));
    final BufferedReader reader = new BufferedReader(new StringReader(text));
    final String lineStartsWith = "    public static " + functionDescr.getReturnType() + " " + functionDescr.getName();
    try {
        String line;
        int offset = 0;
        while ((line = reader.readLine()) != null) {
            offset++;
            if (line.startsWith(lineStartsWith)) {
                break;
            }
        }
        functionDescr.setOffset(offset);
    } catch (final IOException e) {
        // won't ever happen, it's just reading over a string.
        throw new RuntimeException("Error determining start offset with function");
    }
    final String name = pkg.getName() + "." + StringUtils.ucFirst(functionDescr.getName());
    final LineMappings mapping = new LineMappings(name);
    mapping.setStartLine(functionDescr.getLine());
    mapping.setOffset(functionDescr.getOffset());
    lineMappings.put(name, mapping);
    return text;
}
Also used : HashMap(java.util.HashMap) FunctionError(org.drools.compiler.compiler.FunctionError) IOException(java.io.IOException) LinkedList(java.util.LinkedList) LineMappings(org.drools.core.rule.LineMappings) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory)

Example 75 with MapVariableResolverFactory

use of org.mvel2.integration.impl.MapVariableResolverFactory in project drools by kiegroup.

the class JavaRuleBuilderHelper method generateMethodTemplate.

public static void generateMethodTemplate(final String ruleTemplate, final RuleBuildContext context, final Map vars) {
    TemplateRegistry registry = getRuleTemplateRegistry(context.getKnowledgeBuilder().getRootClassLoader());
    context.addMethod((String) TemplateRuntime.execute(registry.getNamedTemplate(ruleTemplate), null, new MapVariableResolverFactory(vars), registry));
}
Also used : TemplateRegistry(org.mvel2.templates.TemplateRegistry) SimpleTemplateRegistry(org.mvel2.templates.SimpleTemplateRegistry) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory)

Aggregations

MapVariableResolverFactory (org.mvel2.integration.impl.MapVariableResolverFactory)79 HashMap (java.util.HashMap)43 VariableResolverFactory (org.mvel2.integration.VariableResolverFactory)29 ParserContext (org.mvel2.ParserContext)24 Serializable (java.io.Serializable)18 DefaultLocalVariableResolverFactory (org.mvel2.integration.impl.DefaultLocalVariableResolverFactory)17 CompiledExpression (org.mvel2.compiler.CompiledExpression)16 ExpressionCompiler (org.mvel2.compiler.ExpressionCompiler)16 SimpleTemplateRegistry (org.mvel2.templates.SimpleTemplateRegistry)14 TemplateRegistry (org.mvel2.templates.TemplateRegistry)13 Debugger (org.mvel2.debug.Debugger)12 Frame (org.mvel2.debug.Frame)12 HashSet (java.util.HashSet)10 MapObject (org.mvel2.tests.core.res.MapObject)10 IndexedVariableResolverFactory (org.mvel2.integration.impl.IndexedVariableResolverFactory)9 LinkedHashMap (java.util.LinkedHashMap)7 Map (java.util.Map)7 Test (org.junit.Test)7 TemplateRuntimeError (org.mvel2.templates.TemplateRuntimeError)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6