Search in sources :

Example 66 with VariableResolverFactory

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

the class MacroProcessorTest method testMacroSupport.

public void testMacroSupport() {
    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";
        }
    });
    ExpressionCompiler compiler = new ExpressionCompiler(parseMacros("modify (foo) { aValue = 'poo = poo', bValue = 'poo, poo' }; mod", macros));
    ParserContext ctx = new ParserContext(null, interceptors, null);
    ctx.setSourceFile("test.mv");
    ctx.setDebugSymbols(true);
    assertEquals("FOOBAR!", executeExpression(compiler.compile(ctx), null, vars));
}
Also used : HashMap(java.util.HashMap) Foo(org.mvel2.tests.core.res.Foo) WithNode(org.mvel2.ast.WithNode) VariableResolverFactory(org.mvel2.integration.VariableResolverFactory) MapVariableResolverFactory(org.mvel2.integration.impl.MapVariableResolverFactory) ASTNode(org.mvel2.ast.ASTNode) ExpressionCompiler(org.mvel2.compiler.ExpressionCompiler) Interceptor(org.mvel2.integration.Interceptor)

Example 67 with VariableResolverFactory

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

the class PropertyHandlerTests method testNullPropertyHandler2.

public void testNullPropertyHandler2() {
    MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
    OptimizerFactory.setDefaultOptimizer("reflective");
    PropertyHandlerFactory.setNullPropertyHandler(new PropertyHandler() {

        public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) {
            return "NULL";
        }

        public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) {
            return "NULL";
        }
    });
    Foo foo = new Foo();
    Bar bar = foo.getBar();
    foo.setBar(null);
    Map map = new HashMap();
    map.put("foo", foo);
    Serializable s = MVEL.compileExpression("foo.bar");
    assertEquals("NULL", MVEL.executeExpression(s, map));
    assertEquals("NULL", MVEL.executeExpression(s, map));
    foo.setBar(bar);
    assertEquals(bar, MVEL.executeExpression(s, map));
}
Also used : Bar(org.mvel2.tests.core.res.Bar) Serializable(java.io.Serializable) HashMap(java.util.HashMap) Foo(org.mvel2.tests.core.res.Foo) HashMap(java.util.HashMap) Map(java.util.Map)

Example 68 with VariableResolverFactory

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

the class ASMAccessorOptimizer method optimizeCollection.

public Accessor optimizeCollection(ParserContext pCtx, Object o, Class type, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory) {
    this.expr = property;
    this.cursor = this.start = start;
    this.end = start + offset;
    this.length = offset;
    this.returnType = type;
    this.compiledInputs = new ArrayList<ExecutableStatement>();
    this.ctx = ctx;
    this.thisRef = thisRef;
    this.variableFactory = factory;
    _initJIT();
    literal = true;
    _getAccessor(o, type);
    _finishJIT();
    try {
        Accessor compiledAccessor = _initializeAccessor();
        if (property != null && length > start) {
            return new Union(compiledAccessor, property, start, length);
        } else {
            return compiledAccessor;
        }
    } catch (Exception e) {
        throw new OptimizationFailure("could not optimize collection", e);
    }
}
Also used : PropertyTools.getFieldOrWriteAccessor(org.mvel2.util.PropertyTools.getFieldOrWriteAccessor) PropertyTools.getFieldOrAccessor(org.mvel2.util.PropertyTools.getFieldOrAccessor) Union(org.mvel2.optimizers.impl.refl.nodes.Union) IOException(java.io.IOException)

Example 69 with VariableResolverFactory

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

the class ASMAccessorOptimizer method _initJIT2.

private void _initJIT2() {
    if (isAdvancedDebugging()) {
        buildLog = new StringAppender();
    }
    cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
    synchronized (Runtime.getRuntime()) {
        cw.visit(OPCODES_VERSION, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, className = "ASMAccessorImpl_" + valueOf(cw.hashCode()).replaceAll("\\-", "_") + (System.currentTimeMillis() / 10) + ((int) Math.random() * 100), null, "java/lang/Object", new String[] { NAMESPACE + "compiler/Accessor" });
    }
    MethodVisitor m = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    m.visitCode();
    m.visitVarInsn(Opcodes.ALOAD, 0);
    m.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    m.visitInsn(RETURN);
    m.visitMaxs(1, 1);
    m.visitEnd();
    (mv = cw.visitMethod(ACC_PUBLIC, "setValue", "(Ljava/lang/Object;Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;Ljava/lang/Object;)Ljava/lang/Object;", null, null)).visitCode();
}
Also used : ClassWriter(org.mvel2.asm.ClassWriter) MethodVisitor(org.mvel2.asm.MethodVisitor)

Example 70 with VariableResolverFactory

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

the class ASMAccessorOptimizer method optimizeObjectCreation.

public Accessor optimizeObjectCreation(ParserContext pCtx, char[] property, int start, int offset, Object ctx, Object thisRef, VariableResolverFactory factory) {
    _initJIT();
    compiledInputs = new ArrayList<ExecutableStatement>();
    this.start = cursor = start;
    this.end = start + offset;
    this.length = this.end - this.start;
    this.ctx = ctx;
    this.thisRef = thisRef;
    this.variableFactory = factory;
    this.pCtx = pCtx;
    String[] cnsRes = captureContructorAndResidual(property, start, offset);
    List<char[]> constructorParms = parseMethodOrConstructor(cnsRes[0].toCharArray());
    try {
        if (constructorParms != null) {
            for (char[] constructorParm : constructorParms) {
                compiledInputs.add((ExecutableStatement) subCompileExpression(constructorParm, pCtx));
            }
            Class cls = findClass(factory, new String(subset(property, 0, findFirst('(', start, length, property))), pCtx);
            assert debug("NEW " + getInternalName(cls));
            mv.visitTypeInsn(NEW, getInternalName(cls));
            assert debug("DUP");
            mv.visitInsn(DUP);
            Object[] parms = new Object[constructorParms.size()];
            int i = 0;
            for (ExecutableStatement es : compiledInputs) {
                parms[i++] = es.getValue(ctx, factory);
            }
            Constructor cns = getBestConstructorCandidate(parms, cls, pCtx.isStrongTyping());
            if (cns == null) {
                StringBuilder error = new StringBuilder();
                for (int x = 0; x < parms.length; x++) {
                    error.append(parms[x].getClass().getName());
                    if (x + 1 < parms.length)
                        error.append(", ");
                }
                throw new CompileException("unable to find constructor: " + cls.getName() + "(" + error.toString() + ")", expr, st);
            }
            this.returnType = cns.getDeclaringClass();
            Class tg;
            for (i = 0; i < constructorParms.size(); i++) {
                assert debug("ALOAD 0");
                mv.visitVarInsn(ALOAD, 0);
                assert debug("GETFIELD p" + i);
                mv.visitFieldInsn(GETFIELD, className, "p" + i, "L" + NAMESPACE + "compiler/ExecutableStatement;");
                assert debug("ALOAD 2");
                mv.visitVarInsn(ALOAD, 2);
                assert debug("ALOAD 3");
                mv.visitVarInsn(ALOAD, 3);
                assert debug("INVOKEINTERFACE " + NAMESPACE + "compiler/ExecutableStatement.getValue");
                mv.visitMethodInsn(INVOKEINTERFACE, "" + NAMESPACE + "compiler/ExecutableStatement", "getValue", "(Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;)Ljava/lang/Object;");
                tg = cns.getParameterTypes()[i].isPrimitive() ? getWrapperClass(cns.getParameterTypes()[i]) : cns.getParameterTypes()[i];
                if (parms[i] != null && !parms[i].getClass().isAssignableFrom(cns.getParameterTypes()[i])) {
                    ldcClassConstant(tg);
                    assert debug("INVOKESTATIC " + NAMESPACE + "DataConversion.convert");
                    mv.visitMethodInsn(INVOKESTATIC, "" + NAMESPACE + "DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;");
                    if (cns.getParameterTypes()[i].isPrimitive()) {
                        unwrapPrimitive(cns.getParameterTypes()[i]);
                    } else {
                        assert debug("CHECKCAST " + getInternalName(tg));
                        mv.visitTypeInsn(CHECKCAST, getInternalName(tg));
                    }
                } else {
                    assert debug("CHECKCAST " + getInternalName(cns.getParameterTypes()[i]));
                    mv.visitTypeInsn(CHECKCAST, getInternalName(cns.getParameterTypes()[i]));
                }
            }
            assert debug("INVOKESPECIAL " + getInternalName(cls) + ".<init> : " + getConstructorDescriptor(cns));
            mv.visitMethodInsn(INVOKESPECIAL, getInternalName(cls), "<init>", getConstructorDescriptor(cns));
            _finishJIT();
            Accessor acc = _initializeAccessor();
            if (cnsRes.length > 1 && cnsRes[1] != null && !cnsRes[1].trim().equals("")) {
                return new Union(acc, cnsRes[1].toCharArray(), 0, cnsRes[1].length());
            }
            return acc;
        } else {
            Class cls = findClass(factory, new String(property), pCtx);
            assert debug("NEW " + getInternalName(cls));
            mv.visitTypeInsn(NEW, getInternalName(cls));
            assert debug("DUP");
            mv.visitInsn(DUP);
            Constructor cns = cls.getConstructor(EMPTYCLS);
            assert debug("INVOKESPECIAL <init>");
            mv.visitMethodInsn(INVOKESPECIAL, getInternalName(cls), "<init>", getConstructorDescriptor(cns));
            _finishJIT();
            Accessor acc = _initializeAccessor();
            if (cnsRes.length > 1 && cnsRes[1] != null && !cnsRes[1].trim().equals("")) {
                return new Union(acc, cnsRes[1].toCharArray(), 0, cnsRes[1].length());
            }
            return acc;
        }
    } catch (ClassNotFoundException e) {
        throw new CompileException("class or class reference not found: " + new String(property), property, st);
    } catch (Exception e) {
        throw new OptimizationFailure("could not optimize construtor: " + new String(property), e);
    }
}
Also used : PropertyTools.getFieldOrWriteAccessor(org.mvel2.util.PropertyTools.getFieldOrWriteAccessor) PropertyTools.getFieldOrAccessor(org.mvel2.util.PropertyTools.getFieldOrAccessor) Union(org.mvel2.optimizers.impl.refl.nodes.Union) IOException(java.io.IOException)

Aggregations

VariableResolverFactory (org.mvel2.integration.VariableResolverFactory)79 MapVariableResolverFactory (org.mvel2.integration.impl.MapVariableResolverFactory)41 HashMap (java.util.HashMap)33 DefaultLocalVariableResolverFactory (org.mvel2.integration.impl.DefaultLocalVariableResolverFactory)33 VariableResolver (org.mvel2.integration.VariableResolver)32 ParserContext (org.mvel2.ParserContext)24 Serializable (java.io.Serializable)23 CompileException (org.mvel2.CompileException)23 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)14 AccessorOptimizer (org.mvel2.optimizers.AccessorOptimizer)14 Map (java.util.Map)13 ExpressionCompiler (org.mvel2.compiler.ExpressionCompiler)12 IndexedVariableResolverFactory (org.mvel2.integration.impl.IndexedVariableResolverFactory)12 List (java.util.List)11 CompiledExpression (org.mvel2.compiler.CompiledExpression)11 ASTNode (org.mvel2.ast.ASTNode)10 Foo (org.mvel2.tests.core.res.Foo)10 MapObject (org.mvel2.tests.core.res.MapObject)10 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)9