Projects >> mvel >>d0704b517b22947b43491b06852ad78378cae0e3

Chunk
Conflicting content
        // raising the error.
  public void testContextObjMethodCall() {
      String str = "getName() == \"bob\"";

<<<<<<< HEAD
      ParserConfiguration pconf = new ParserConfiguration();
      ParserContext pctx = new ParserContext(pconf);
      pctx.setStrongTyping(true);
      pctx.addInput( "this", Bar.class );
      ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
      Bar ctx = new Bar();
      ctx.setName( "bob" );
      Boolean result = (Boolean) MVEL.executeExpression( stmt, ctx );
      assertTrue( result );
  }
=======
        assertNotNull(result);
        assertTrue(result);
        assertEquals(1,
                list.size());
        assertEquals("first",
                list.get(0));
    }

    public void testReturnBoolean() {
        String ex = "list = new java.util.ArrayList(); return list != null";

        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        Serializable s = compileExpression(ex,
                ctx);

        assertEquals(true,
                executeExpression(s,
                        new HashMap()));
    }

    public void testComaProblemStrikesBack() {
        String ex = "a.explanation = \"There is a coma, in here\"";

        ParserContext ctx = new ParserContext();
        ExpressionCompiler compiler = new ExpressionCompiler(ex);
        Serializable s = compiler.compile(ctx);

        Base a = new Base();
        Map variables = new HashMap();
        variables.put("a",
                a);

        executeExpression(s,
                variables);
        assertEquals("There is a coma, in here",
                a.data);
    }


    public static interface Services {
        public final static String A_CONST = "Hello World";

        public void log(String text);
    }

    public void testStringConcatenation() {
        // debugging MVEL code, it seems that MVEL 'thinks' that the result of the expression:
        // "Drop +5%: "+$sb+" avg: $"+$av+" price: $"+$pr
        // is a double, and as so, he looks for a method:
        // Services.log( double );
        // but finds only:
        // Services.log( String );
            }

    }


        String ex = "services.log((String) \"Drop +5%: \"+$sb+\" avg: $\"+$av+\" price: $\"+$pr );";
        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addInput("$sb",
                String.class);
        ctx.addInput("$av",
                double.class);
        ctx.addInput("$pr",
                double.class);
        ctx.addInput("services",
                Services.class);
        try {
            ExpressionCompiler compiler = new ExpressionCompiler(ex);
            compiler.compile(ctx);
        }
        catch (Throwable e) {
            e.printStackTrace();
            fail("Should not raise exception: " + e.getMessage());
        }
    }

    public void testStringConcatenation2() {
        String ex = "services.log( $cheese + \" some string \" );";
        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addInput("$cheese",
                Cheese.class);
        ctx.addInput("services",
                Services.class);
        try {
            ExpressionCompiler compiler = new ExpressionCompiler(ex);
            compiler.compile(ctx);
        }
        catch (Throwable e) {
            e.printStackTrace();
            fail("Should not raise exception: " + e.getMessage());
        }
    }

    public void testStringConcatenation3() {
        // BUG: return type of the string concatenation is inferred as double instead of String
        String ex = "services.log($av + \"Drop +5%: \"+$sb+\" avg: $\"+percent($av)+\" price: $\"+$pr );";
        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.setStrictTypeEnforcement(true);
        ctx.addInput("$sb",
                String.class);
        ctx.addInput("$av",
                double.class);
        ctx.addInput("$pr",
                double.class);
        ctx.addInput("services",
                Services.class);
        ctx.addImport("percent", MVEL.getStaticMethod(String.class, "valueOf", new Class[]{double.class}));
        try {
            Serializable compiledExpression = MVEL.compileExpression(ex, ctx);

            Services services = new Services() {
                public void log(String text) {
                }
            };
            Map vars = new HashMap();
            vars.put("services", services);
            vars.put("$sb", "RHT");
            vars.put("$av", 15.0);
            vars.put("$pr", 10.0);

            MVEL.executeExpression(compiledExpression, vars);
        }
        catch (Throwable e) {
            e.printStackTrace();
            fail("Should not raise exception: " + e.getMessage());
        }
    }

    public void testMapsWithVariableAsKey() {
        String ex = "aMap[aKey] == 'aValue'";
        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(false);

        ExpressionCompiler compiler = new ExpressionCompiler(ex);
        compiler.setVerifyOnly(true);
        compiler.compile(ctx);

        Set requiredInputs = compiler.getParserContextState().getInputs().keySet();
        assertTrue(requiredInputs.contains("aMap"));
        assertTrue(requiredInputs.contains("aKey"));
    }

    public static void testProjectionUsingThis() {
        Set records = new HashSet();
        for (int i = 0; i < 53; i++) {
            Bean2 record = new Bean2(i);
            records.add(record);
        }

        Object result = MVEL.eval("(_prop in this)",
                records);
        System.out.println("result: " + result);
    }

    public static final class Bean2 {
        public final int _prop;

        public Bean2(int prop_) {
            _prop = prop_;
        }

        public int getProp() {
            return _prop;
        }

        public String toString() {
            return Integer.toString(_prop);
        }
    }

    public void testUnaryOpNegation1() {
        assertEquals(false,
                test("!new Boolean(true)"));
    }

    public void testUnaryOpNegation2() {
        assertEquals(true,
                test("!isdef _foozy_"));
    }

    public class Az {
        public void foo(String s) {
        }
    }

    public class Bz extends Az {
    }

    public void testJIRA151() {
        OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE);
        Bz b = new Bz();
        ParserContext context = new ParserContext();
        Object expression = MVEL.compileExpression("a.foo(value)",
                context);
        Map variables = new HashMap();

        variables.put("a",
                b);
        variables.put("value",
                123);
        for (int i = 0; i < 100; i++) {
            System.out.println("i: " + i);
            System.out.flush();
            executeExpression(expression,
                    variables);
        }
    }

    public void testJIRA151b() {
        OptimizerFactory.setDefaultOptimizer("ASM");
        Bz b = new Bz();
        ParserContext context = new ParserContext();
        Object expression = MVEL.compileExpression("a.foo(value)",
                context);
        Map variables = new HashMap();

        variables.put("a",
                b);
        variables.put("value",
                123);
        for (int i = 0; i < 100; i++) {
            System.out.println("i: " + i);
            System.out.flush();
            executeExpression(expression,
                    variables);
        }
    }


    public void testJIRA153() {
        assertEquals(false,
                MVEL.eval("!(true)"));
        assertEquals(false,
                executeExpression(MVEL.compileExpression("!(true)")));
    }

    public void testJIRA154() {
        Map m = createTestMap();
        m.put("returnTrue",
                MVEL.getStaticMethod(CoreConfidenceTests.class,
                        "returnTrue",
                        new Class[0]));

        assertEquals(false,
                MVEL.eval("!returnTrue()",
                        m));
    }

    public void testJIRA154b() {
        ParserContext pctx = new ParserContext();
        pctx.addImport("returnTrue",
                MVEL.getStaticMethod(CoreConfidenceTests.class,
                        "returnTrue",
                        new Class[0]));

        assertEquals(false,
                executeExpression(MVEL.compileExpression("!(returnTrue())",
                        pctx)));
    }

    public void testJIRA155() {
        ParserContext pctx = new ParserContext();
        pctx.addImport("returnTrue",
                MVEL.getStaticMethod(CoreConfidenceTests.class,
                        "returnTrue",
                        new Class[0]));

        assertEquals(true,
                executeExpression(MVEL.compileExpression("!true || returnTrue()",
                        pctx)));
    }

    public void testJIRA155b() {
        ParserContext pctx = new ParserContext();
        pctx.addImport("returnTrue",
                MVEL.getStaticMethod(CoreConfidenceTests.class,
                        "returnTrue",
                        new Class[0]));

        assertEquals(true,
                executeExpression(MVEL.compileExpression("!(!true || !returnTrue())",
                        pctx)));
    }

    public void testJIRA156() throws Throwable {
        ClassProvider provider = new ClassProvider();
        provider.getPrivate().foo();

        PublicClass.class.getMethod("foo").invoke(provider.getPrivate());

        String script = "provider.getPrivate().foo()";
        HashMap vars = new HashMap();
        vars.put("provider",
                provider);
        MVEL.eval(script,
                vars);
    }

    public void testJIRA156b() throws Throwable {
        ClassProvider provider = new ClassProvider();
        provider.getPrivate().foo();

        PublicClass.class.getMethod("foo").invoke(provider.getPrivate());

        String script = "provider.getPrivate().foo()";

        Serializable s = MVEL.compileExpression(script);

        HashMap vars = new HashMap();
        vars.put("provider",
                provider);

        OptimizerFactory.setDefaultOptimizer("reflective");
        executeExpression(s,
                vars);
        OptimizerFactory.setDefaultOptimizer("ASM");
        executeExpression(s,
                vars);
    }

    public void testJIRA156c() throws Throwable {
        ClassProvider provider = new ClassProvider();
        provider.getPublic().foo();

        PublicClass.class.getMethod("foo").invoke(provider.getPublic());

        String script = "provider.getPublic().foo()";

        Serializable s = MVEL.compileExpression(script);

        HashMap vars = new HashMap();
        vars.put("provider",
                provider);

        MVEL.eval(script,
                vars);
        OptimizerFactory.setDefaultOptimizer("reflective");
        executeExpression(s,
                vars);
        OptimizerFactory.setDefaultOptimizer("ASM");
        executeExpression(s,
                vars);
    }

    public static boolean returnTrue() {
        return true;
    }

    public static class TestHelper {
        public static void method(int id,
                                  Object[] arr) {
            System.out.println(id + " -> " + arr.length);
        }

        public static void method(Object obj1, Object obj2) {
            System.out.println(obj1 + "-> " + obj2);
        }

        public static Calendar minDate() {
    }
            return Calendar.getInstance();
        }

        public static Calendar maxDate() {
            return Calendar.getInstance();
        }
    }

    public static class Fooz {
        public Fooz(String id) {
        }
    }

    public void testArray() {
        String ex = " TestHelper.method(1, new String[]{\"a\", \"b\"});\n"
                + " TestHelper.method(2, new String[]{new String(\"a\"), new String(\"b\")});\n"
                + " TestHelper.method(3, new Fooz[]{new Fooz(\"a\"), new Fooz(\"b\")});";
        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addImport(TestHelper.class);
        ctx.addImport(Fooz.class);
        ExpressionCompiler compiler = new ExpressionCompiler(ex);

        OptimizerFactory.setDefaultOptimizer("ASM");
        CompiledExpression expr = compiler.compile(ctx);
        executeExpression(expr);

        OptimizerFactory.setDefaultOptimizer("reflective");
        expr = compiler.compile(ctx);
        executeExpression(expr);
    }

    public void testArray2() {
        String ex = " TestHelper.method(1, {\"a\", \"b\"});\n"
                + " TestHelper.method(2, {new String(\"a\"), new String(\"b\")});\n"
                + " TestHelper.method(3, {new Fooz(\"a\"), new Fooz(\"b\")});";
        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addImport(TestHelper.class);
        ctx.addImport(Fooz.class);
        ExpressionCompiler compiler = new ExpressionCompiler(ex);

        OptimizerFactory.setDefaultOptimizer("ASM");
        CompiledExpression expr = compiler.compile(ctx);
        executeExpression(expr);

        OptimizerFactory.setDefaultOptimizer("reflective");
        expr = compiler.compile(ctx);
        executeExpression(expr);
    }


    public void testJIRA166() {
        Object v = MVEL.eval("import java.util.regex.Matcher; import java.util.regex.Pattern;"
                + " if (Pattern.compile(\"hoge\").matcher(\"hogehogehoge\").find()) { 'foo' } else { 'bar' }",
                new HashMap());
        assertEquals("foo",
                v);
    }

    public static class Beano {
        public String getProperty1() {
            return null;
        }

        public boolean isProperty2() {
            return true;
        }

        public boolean isProperty3() {
            return false;
        }
    }

    public void testJIRA167() {
        Map context = new HashMap();
        context.put("bean",
                new Beano());
        MVEL.eval("bean.property1==null?bean.isProperty2():bean.isProperty3()",
                context);
    }

    public void testJIRA168() {
        boolean before = MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL;
        try {
            Map st = new HashMap();
            st.put("__fact__", new ArrayList());
            st.put("__expected__", 0);

            String expressionNaked = "__fact__.size == __expected__";
            String expressionNonNaked = "__fact__.size() == __expected__";
            MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;

            // the following works fine
            ParserContext ctx = new ParserContext();
            for (Map.Entry entry : st.entrySet()) {
                ctx.addInput(entry.getKey(),
                        entry.getValue().getClass());
            CompiledExpression expr = new ExpressionCompiler(expressionNaked).compile(ctx);

            Boolean result = (Boolean) executeExpression(expr,
                    st);
            assertTrue(result);

            // the following works fine        
            result = (Boolean) MVEL.eval(expressionNonNaked, st);
            assertTrue(result);

            // the following fails
            result = (Boolean) MVEL.eval(expressionNaked, st);
            assertTrue(result);
        }
        finally {
            MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = before;
        }
    }

    public void testJIRA170() {
        OptimizerFactory.setDefaultOptimizer("reflective");

        List staticDispatch = Arrays.asList(2, 1, 0);
        List multimethodDispatch = Arrays.asList(3, 2, 1);

        //      invokeJIRA170("Dynamic", ctxJIRA170(false, false), varsJIRA170(), multimethodDispatch);
        //      invokeJIRA170("Strict", ctxJIRA170(true, false), varsJIRA170(), multimethodDispatch);
        invokeJIRA170("Strong", ctxJIRA170(false, true), varsJIRA170(), staticDispatch);
    }

    public void testJIRA170b() {
        OptimizerFactory.setDefaultOptimizer("ASM");

        List staticDispatch = Arrays.asList(2, 1, 0);
        List multimethodDispatch = Arrays.asList(3, 2, 1);

        //       invokeJIRA170("Dynamic", ctxJIRA170(false, false), varsJIRA170(), multimethodDispatch);
        //       invokeJIRA170("Strict", ctxJIRA170(true, false), varsJIRA170(), multimethodDispatch);
        invokeJIRA170("Strong", ctxJIRA170(false, true), varsJIRA170(), staticDispatch);
    }

    public void invokeJIRA170(String name, ParserContext pctx, Map vars, Collection expected) {
        Serializable expression = MVEL.compileExpression("x.remove((Object) y); x ", pctx);
        Object result = executeExpression(expression, vars);

        assertTrue(String.format("%s Expected %s, Got %s", name, expected, result), expected.equals(result));
        result = executeExpression(expression, vars);

        assertTrue(String.format("%s Expected %s, Got %s", name, expected, result), expected.equals(result));
    }


    private Map varsJIRA170() {
        Map vars = new HashMap();
        vars.put("x", new ArrayList(Arrays.asList(3, 2, 1, 0)));
        vars.put("y", 3);
        return vars;
    }

    private ParserContext ctxJIRA170(boolean strictTypeEnforcement, boolean strongTyping) {
        ParserContext ctx = new ParserContext();
        //    ctx.setStrictTypeEnforcement(strictTypeEnforcement);
        ctx.setStrongTyping(strongTyping);
        ctx.addInput("x", Collection.class, new Class[]{Integer.class});
        ctx.addInput("y", Integer.class);
        return ctx;
    }


    public static class JIRA167Step {
        public String getParent() {
            return null;
        }
    }

    public static class JIRA167Node {
        public boolean isServer() {
            return true;
        }
    }

    public void testJIRA167b() {
        Map context = new HashMap();
        context.put("current", new JIRA167Step());
        context.put("node", new JIRA167Node());
        MVEL.eval("current.parent==null?node.isServer():(node==current.parent.node)", context);
    }

    public void testJIRA167c() {
        MVEL.eval("true?true:(false)");
    }


    public void testJIRA176() {
        Map innerMap = new HashMap();

        innerMap.put("testKey[MyValue=newValue]", "test");

        Map vars = new HashMap();
        vars.put("mappo", innerMap);

        assertEquals("test", MVEL.eval("mappo['testKey[MyValue=newValue]']", vars));
    }

    public void testJIRA176b() {
        Map innerMap = new HashMap();
        innerMap.put("testKey[MyValue=newValue]", "test");

        Map vars = new HashMap();
        vars.put("mappo", innerMap);

        Serializable s = MVEL.compileExpression("mappo['testKey[MyValue=newValue]']");
        OptimizerFactory.setDefaultOptimizer("reflective");

        assertEquals("test", executeExpression(s, vars));

        s = MVEL.compileExpression("mappo['testKey[MyValue=newValue]']");
        OptimizerFactory.setDefaultOptimizer("ASM");

        assertEquals("test", executeExpression(s, vars));
    }

    public void testRandomSomething() {

        Foo foo = new Foo();
        foo.setName("foo1");

        Foo foo2 = new Foo();
        foo2.setName("foo2");

        MVEL.setProperty(foo, "name", 5);

        Serializable s = MVEL.compileExpression("name.toUpperCase()", ParserContext.create().stronglyTyped().withInput("name", String.class));

        Object _return = executeExpression(s, foo);

        System.out.println("returned value: " + String.valueOf(_return));

        _return = executeExpression(s, foo2);

        System.out.println("returned value: " + String.valueOf(_return));

    }

    public static class ProcessManager {
        public void startProcess(String name, Map variables) {
            System.out.println("Process started");
        }
    }

    public static class KnowledgeRuntimeHelper {
        public ProcessManager getProcessManager() {
            return new ProcessManager();
        }
    }

    public void testDeepMethodNameResolution() {
        String expression = "variables = [ \"symbol\" : \"RHT\" ]; \n" +
                "drools.getProcessManager().startProcess(\"id\", variables );";

        // third pass
        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addInput("drools", KnowledgeRuntimeHelper.class);
        Map vars = new HashMap();
        vars.put("drools", new KnowledgeRuntimeHelper());
        Serializable expr = MVEL.compileExpression(expression, ctx);
        executeExpression(expr, vars);
    }

    public void testJIRA183() {
        String exp1 = "int end = 'attribute'.indexOf('@');  if(end == -1)" +
                " { end = 'attribute'.length()} 'attribute'.substring(0, end);";
        Object val1 = MVEL.eval(exp1, new HashMap());

        String exp2 = "int end = 'attribute'.indexOf('@');  if(end == -1)" +
                " { end = 'attribute'.length() } 'attribute'.substring(0, end);";
        Object val2 = MVEL.eval(exp2, new HashMap());
    }


    public void testContextAssignments() {
        Foo foo = new Foo();
        MVEL.eval("this.name = 'bar'", foo);

        assertEquals("bar", foo.getName());
    }

    public void testMVEL187() {
        ParserContext context = new ParserContext();
        context.addPackageImport("test");
        context.addInput("outer", Outer.class);

        Object compiled = MVEL.compileExpression(
                "outer.getInner().getValue()", context);
        Map vars = new HashMap();
        vars.put("outer", new Outer());
        VariableResolverFactory varsResolver = new MapVariableResolverFactory(vars);

        assertEquals(2, executeExpression(compiled, varsResolver));
    }

    public void testMVEL190() {
        ParserContext context = new ParserContext();
        context.addImport(Ship.class);
        context.addImport(MapObject.class);

        context.addInput("obj", MapObject.class);

        Object compiled = MVEL.compileExpression(
                "((Ship) obj).getName()", context);

        Map vars = new HashMap();
        vars.put("obj", new Ship());

        VariableResolverFactory varsResolver
                = new MapVariableResolverFactory(vars);

        System.out.println(
                executeExpression(compiled, varsResolver));
    }

    public void testMethodScoring() {
        OptimizerFactory.setDefaultOptimizer("ASM");
        ParserConfiguration pconf = new ParserConfiguration();
        for (Method m : StaticMethods.class.getMethods()) {
            if (Modifier.isStatic(m.getModifiers())) {
                pconf.addImport(m.getName(), m);

            }
        }
        pconf.addImport("TestCase", TestCase.class);
        ParserContext pctx = new ParserContext(pconf);

        Map vars = new HashMap();

        // this is successful
        TestCase.assertTrue(StaticMethods.is(StaticMethods.getList(java.util.Formatter.class)));

        // this also should be fine
        Serializable expr = MVEL.compileExpression("TestCase.assertTrue( is( getList( java.util.Formatter ) ) )", pctx);
        executeExpression(expr, vars);
    }

    public static class StaticMethods {
        public static  boolean is(List arg) {
            return true;
        }

        public static boolean is(Collection arg) {
            throw new RuntimeException("Wrong method called");
        }

        public static List getList(Class arg) {
            ArrayList result = new ArrayList();
            result.add(arg);
            return result;
        }

        public static String throwException() {
            throw new RuntimeException("this should throw an exception");
        }
    }

    public void testSetterViaDotNotation() {

        TestClass tc = new TestClass();
        tc.getExtra().put("test", "value");

        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        String expression = "extra.test";
        Serializable compiled = MVEL.compileSetExpression(expression, ctx);
        MVEL.executeSetExpression(compiled, tc, "value2");
        assertEquals("value2", tc.getExtra().get("test"));
    }

    public void testSetterViaMapNotation() {

        TestClass tc = new TestClass();
        tc.getExtra().put("test", "value");

        ParserContext ctx = new ParserContext();
        ctx.withInput("this", TestClass.class);
        ctx.setStrongTyping(true);
        String expression = "extra[\"test\"]";
        Serializable compiled = MVEL.compileSetExpression(expression, tc.getClass(), ctx);
        MVEL.executeSetExpression(compiled, tc, "value3");
        assertEquals("value3", tc.getExtra().get("test"));
    }


    public void testGetterViaDotNotation() {

        TestClass tc = new TestClass();
        tc.getExtra().put("test", "value");

        Map vars = new HashMap();
        vars.put("tc", tc);

        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addInput("tc", tc.getClass());
        String expression = "tc.extra.test";
        Serializable compiled = MVEL.compileExpression(expression, ctx);
        String val = (String) executeExpression(compiled, vars);
        assertEquals("value", val);
    }

    public void testGetterViaMapNotation() {
        TestClass tc = new TestClass();
        tc.getExtra().put("test", "value");

        Map vars = new HashMap();
        vars.put("tc", tc);

        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addInput("tc", tc.getClass());
        String expression = "tc.extra[\"test\"]";
        Serializable compiled = MVEL.compileExpression(expression, ctx);
        String val = (String) executeExpression(compiled, vars);
        assertEquals("value", val);
    }

    public void testGetterViaMapGetter() {
        TestClass tc = new TestClass();
        tc.getExtra().put("test", "value");

        Map vars = new HashMap();
        vars.put("tc", tc);

        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addInput("tc", tc.getClass());
        String expression = "tc.extra.get(\"test\")";
        Serializable compiled = MVEL.compileExpression(expression, ctx);
        String val = (String) executeExpression(compiled, vars);
        assertEquals("value", val);
    }


    public void testJIRA209() {
        Map vars = new LinkedHashMap();
        vars.put("bal", new BigDecimal("999.99"));

        String[] testCases = {
                //        "bal < 100 or bal > 200",
                //        "bal < 100 || bal > 200",
                "bal > 200 or bal < 100",
                "bal > 200 || bal < 100",
                "bal < 100 and bal > 200",
                "bal < 100 && bal > 200",
                "bal > 200 and bal < 100",
                "bal > 200 && bal < 100"
        };

        Object val1, val2;
        for (String expr : testCases) {
            System.out.println("Evaluating '" + expr + "': ......");
            val1 = MVEL.eval(expr, vars);
            assertNotNull(val1);
            Serializable compiled = MVEL.compileExpression(expr);
            val2 = executeExpression(compiled, vars);
            assertNotNull(val2);
            assertEquals("expression did not evaluate correctly: " + expr, val1, val2);
        }
    }

    public void testConstructor() {
        String ex = " TestHelper.method(new Person('bob', 30), new Person('mark', 40, 999, 55, 10));\n";
        ParserContext ctx = new ParserContext();
        ctx.setStrongTyping(true);
        ctx.addImport(TestHelper.class);
        ctx.addImport(Person.class);

        // un-comment the following line to see how MVEL is converting the int argument 40 into a
        // string and then executing the wrong constructor on the Person class
        try {
            MVEL.compileExpression(ex, ctx);
            fail("Constructor should not have been found.");
        }
        catch (CompileException e) {
            // yay.
        }
        // fail( "The Person constructor used in the expression does not exist, so an error should have been raised during compilation." );
    }

    public void testAmbiguousGetName() {
        Map vars = createTestMap();
        vars.put("Foo244", Foo.class);

        Serializable s = MVEL.compileExpression("foo.getClass().getName()");

        System.out.println(MVEL.executeExpression(s, vars));

        s = MVEL.compileExpression("Foo244.getName()");

        System.out.println(MVEL.executeExpression(s, vars));
    }

    public void testBindingNullToPrimitiveTypes() {
        Map vars = createTestMap();
        ((Foo) vars.get("foo")).setCountTest(10);

        OptimizerFactory.setDefaultOptimizer("reflective");
        Serializable s = MVEL.compileSetExpression("foo.countTest");
        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).getCountTest(), 0);

        OptimizerFactory.setDefaultOptimizer("ASM");
        s = MVEL.compileSetExpression("foo.countTest");
        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).getCountTest(), 0);

        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).getCountTest(), 0);
    }

    public void testBindingNullToPrimitiveTypes2() {
        Map vars = createTestMap();
        ((Foo) vars.get("foo")).setCountTest(10);

        OptimizerFactory.setDefaultOptimizer("reflective");
        Serializable s = MVEL.compileSetExpression("foo.boolTest");
        MVEL.executeSetExpression(s, vars, null);

        assertFalse(((Foo) vars.get("foo")).isBoolTest());

        OptimizerFactory.setDefaultOptimizer("ASM");
        s = MVEL.compileSetExpression("foo.boolTest");
        MVEL.executeSetExpression(s, vars, null);

        assertFalse(((Foo) vars.get("foo")).isBoolTest());

        MVEL.executeSetExpression(s, vars, null);

        assertFalse(((Foo) vars.get("foo")).isBoolTest());
    }

    public void testBindingNullToPrimitiveTypes3() {
        Map vars = createTestMap();
        ((Foo) vars.get("foo")).setCharTest('a');

        OptimizerFactory.setDefaultOptimizer("reflective");
        Serializable s = MVEL.compileSetExpression("foo.charTest");
        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).getCharTest(), 0);

        OptimizerFactory.setDefaultOptimizer("ASM");
        s = MVEL.compileSetExpression("foo.charTest");
        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).getCharTest(), 0);

        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).getCharTest(), 0);
    }


    public void testBindingNullToPrimitiveTypes4() {
        Map vars = createTestMap();
        ((Foo) vars.get("foo")).charTestFld = 'a';

        OptimizerFactory.setDefaultOptimizer("reflective");
        Serializable s = MVEL.compileSetExpression("foo.charTestFld");

        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).charTestFld, 0);

        OptimizerFactory.setDefaultOptimizer("ASM");
        s = MVEL.compileSetExpression("foo.charTestFld");
        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).charTestFld, 0);

        MVEL.executeSetExpression(s, vars, null);

        assertEquals(((Foo) vars.get("foo")).charTestFld, 0);
    }

    public void testBindListToArray() {
        Map vars = createTestMap();

        ArrayList list = new ArrayList();
        list.add("a");
        list.add("b");
        list.add("c");

        OptimizerFactory.setDefaultOptimizer("reflective");
        Serializable s = MVEL.compileSetExpression("foo.charArray");

        MVEL.executeSetExpression(s, vars, list);

        assertEquals(((Foo) vars.get("foo")).getCharArray().length, 3);
    }

    public void testBindListToMultiArray() {
        Map vars = createTestMap();

        ArrayList> list = new ArrayList>();

        List l1 = new ArrayList();
        l1.add("a");
        l1.add("b");
        l1.add("c");

        List l2 = new ArrayList();
        l2.add("d");
        l2.add("e");
        l2.add("f");

        List l3 = new ArrayList();
        l3.add("g");
        l3.add("h");
        l3.add("i");

        list.add(l1);
        list.add(l2);
        list.add(l3);

        OptimizerFactory.setDefaultOptimizer("reflective");
        Serializable s = MVEL.compileSetExpression("foo.charArrayMulti");

        MVEL.executeSetExpression(s, vars, list);

        Foo foo = (Foo) vars.get("foo");

        assertEquals(foo.getCharArrayMulti().length, 3);
        assertEquals(foo.getCharArrayMulti()[2][2], 'i');
    }

    //This one should compile and pass
    public void testStrObjEqualsEquals() {

        MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
        ParserConfiguration pconf = new ParserConfiguration();
        ParserContext pctx = new ParserContext(pconf);
        pctx.addInput("this", Triangle.class);
        pctx.setStrongTyping(true);
        
        String str = "strLabel == objLabel";
        
        ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
        assertTrue( (Boolean) MVEL.executeExpression(stmt, new Triangle(), new HashMap()));         
    }
    
    //This one should fail to compile? JPW:IMO this one should compile too because equals is at the 
    //object level any object should be able to evaluate equivalence on any other object
    public void testStrTriangleEqualsEquals() {

        MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
        ParserConfiguration pconf = new ParserConfiguration();
        ParserContext pctx = new ParserContext(pconf);
        pctx.addInput("this", Triangle.class);
        pctx.setStrongTyping(true);
        
        String str = "strLabel == this";
        
        ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
        assertFalse( (Boolean) MVEL.executeExpression(stmt, new Triangle(), new HashMap()));         
    }
    
    //Should compile and fail
    public void testStrDoubleEqualsEquals() {
        MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
        ParserConfiguration pconf = new ParserConfiguration();
        ParserContext pctx = new ParserContext(pconf);
        pctx.addInput("this", Triangle.class);
        pctx.setStrongTyping(true);
        
        String str = "strLabel == doubleVal";
        
        ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
        assertFalse( (Boolean) MVEL.executeExpression(stmt, new Triangle(), new HashMap()));         
    }
    public void testMVEL224() {
        ParserContext ctx = new ParserContext();
        MVEL.compileExpression("(pin == 1)", ctx);
    public static class A221 {

        public B221 b;
    }

    public static class B221 {

        public String c = "something";
    }

    public void testMVEL221() {
        A221 a1 = new A221();
        a1.b = new B221();

        A221 a2 = new A221();

        OptimizerFactory.setDefaultOptimizer("ASM");

        String expression = "this.?b.c";
        Serializable compiledExpression = MVEL.compileExpression(expression);

        assertEquals(null, MVEL.executeExpression(compiledExpression, a2, String.class));
        assertEquals("something", MVEL.executeExpression(compiledExpression, a1, String.class));

        OptimizerFactory.setDefaultOptimizer("reflective");

        compiledExpression = MVEL.compileExpression(expression);

        assertEquals(null, MVEL.executeExpression(compiledExpression, a2, String.class));
        assertEquals("something", MVEL.executeExpression(compiledExpression, a1, String.class));
    }

    public void testMVEL222() throws IOException {
        String script = "for (int i= 0; i < 10; i++ ){ values[i] = 1.0; }";
        Map scriptVars = new HashMap();
        double[] values = new double[10];
        scriptVars.put("values", values);
        Serializable expression = MVEL.compileExpression(script);
        for (int i = 0; i < 6; i++) {
            scriptVars.put("values", values);
            MVEL.executeExpression(expression, scriptVars);
        }
    }

    public void testMVEL238() throws IOException {
        String expr = new String(loadFromFile(new File("src/test/java/org/mvel2/tests/MVEL238.mvel")));

        Serializable s = MVEL.compileExpression(expr);

        System.out.println(MVEL.executeExpression(s, new HashMap()));
        System.out.println(MVEL.executeExpression(s, new HashMap()));
    }

    public void testParsingRegression() {
        String expr = "if (false) {System.out.println(\" foo\")} else {System.out.println(\" bar\")}";
        MVEL.eval(expr);
    }


    public static class StaticClassWithStaticMethod {
        public static String getString() {
            return "hello";
        }
    }

//    public void testStaticImportWithWildcard() {
//        // this isn't supported yet
//        assertEquals("hello",
//                test("import_static " + getClass().getName() + ".StaticClassWithStaticMethod.*; getString()"));
//    }

    public void testArrayLength() {
        ParserContext context = new ParserContext();
        context.setStrongTyping(true);
        context.addInput("x",
                String[].class);
        ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression("x.length", context);
    }

    public void testEmptyConstructorWithSpace() throws Exception {
        ParserConfiguration pconf = new ParserConfiguration();
    public void testStrictModeAddAll() {
        pconf.addImport("getString", StaticClassWithStaticMethod.class.getMethod("getString", null));

        String text = "getString( )";

        ParserContext pctx = new ParserContext(pconf);
        pctx.setStrongTyping(true);
        pctx.setStrictTypeEnforcement(true);


        MVEL.compileExpression(text, pctx);
    }

    public void testJavaLangImport() throws Exception {
        String s = "Exception e = null;";
        ParserConfiguration pconf = new ParserConfiguration();
        ParserContext pctx = new ParserContext(pconf);
        MVEL.compileExpression(s, pctx);
    public void testContextFieldNotFound() {
        String str = "'stilton'.equals( type );";

        ParserConfiguration pconf = new ParserConfiguration();

        ParserContext pctx = new ParserContext(pconf);
        pctx.addInput("this", Cheese.class);
        pctx.setStrictTypeEnforcement(true);
        pctx.setStrongTyping(true);

        ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
        MVEL.executeExpression(stmt, new Cheese(), new HashMap());
    }

    public void testVarArgs() throws Exception {
        ParserContext parserContext = new ParserContext();
        parserContext.setStrictTypeEnforcement(true);
        parserContext.setStrongTyping(true);

        MVEL.analyze("String.format(\"\");", parserContext);
    }


    public void testOperatorPrecedence() throws IOException {
        String script = "list = [1, 2, 3]; x = 10; list contains x || x == 20";
        Serializable expression = MVEL.compileExpression(script);
        Object result = MVEL.executeExpression(expression, new HashMap());

        assertEquals(Boolean.FALSE, result);
    }


    public void testNestedEnum() throws Exception {
//        assertEquals(Triangle.Foo.class, MVEL.analyze("import " + Triangle.class.getCanonicalName() +"; Triangle.Foo.OBTUSE" , ParserContext.create()));

        //       Serializable o = MVEL.compileExpression( "import " + Triangle.class.getCanonicalName() +"; Triangle.Foo.OBTUSE" );

        //     assertEquals( Triangle.Foo.OBTUSE, MVEL.executeExpression(o, new HashMap()) );

        MVEL.eval("import " + Triangle.class.getCanonicalName() + "; Triangle.Foo.OBTUSE", new HashMap());
    }

    public static class Triangle {
        public static enum Foo {
            INCOMPLETE, UNCLASSIFIED,
            EQUILATERAL, ISOSCELES, RECTANGLED, ISOSCELES_RECTANGLED, ACUTE, OBTUSE;
        }

        private Object objLabel = "Triangle";
        private String strLabel = "Triangle";
        private Double doubleVal = 29.0;
        
		public Object getObjLabel() {
			return objLabel;
		}
		public void setObjLabel(Object objLabel) {
			this.objLabel = objLabel;
		}
		public String getStrLabel() {
			return strLabel;
		}
		public void setStrLabel(String strLabel) {
			this.strLabel = strLabel;
		}
		public Double getDoubleVal() {
			return doubleVal;
		}
		public void setDoubleVal(Double doubleVal) {
			this.doubleVal = doubleVal;
		}
        
        
//        private Foo foo;
//
//        public Foo getFoo() {
//            return foo;
//        }
//
//        public void setFoo(Foo foo) {
//            this.foo = foo;
//        }
    }

        String str = "list.addAll( o );";

        ParserConfiguration pconf = new ParserConfiguration();
        ParserContext pctx = new ParserContext(pconf);
        pctx.setStrongTyping(true);
        pctx.addInput("o", Object.class);
        pctx.addInput("list", ArrayList.class);
        try {
            ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
            fail("This should not compileShared, as o is not of a type Collection");
        }
        catch (Exception e) {

        }
    }

    public void testNestedEnumFromJar() throws ClassNotFoundException,
            SecurityException,
            NoSuchFieldException {
        String expr = "EventRequest.Status.ACTIVE";

        // creating a classloader for the jar
        URL resource = getClass().getResource("/eventing-example.jar");
        assertNotNull(resource);
        URLClassLoader loader = new URLClassLoader(new URL[]{resource},
                getClass().getClassLoader());

        // loading the class to prove it works
        Class er = loader.loadClass("org.drools.examples.eventing.EventRequest");
        assertNotNull(er);
        assertEquals("org.drools.examples.eventing.EventRequest",
                er.getCanonicalName());

        // getting the value of the enum to prove it works:
        Class st = er.getDeclaredClasses()[0];
        assertNotNull(st);
        Field active = st.getField("ACTIVE");
        assertNotNull(active);

        // now, trying with MVEL
        ParserConfiguration pconf = new ParserConfiguration();
        pconf.setClassLoader(loader);
        pconf.addImport(er);
        ParserContext pctx = new ParserContext(pconf);
        pctx.setStrongTyping(true);

        Serializable compiled = MVEL.compileExpression(expr, pctx);
        Object result = MVEL.executeExpression(compiled);

        assertNotNull(result);
    }
>>>>>>> 6fe36ed82a15ceefa97641f9dca4eb835da35e2a

}
Solution content
  public void testContextObjMethodCall() {
    String str = "name == \"bob\"";

    ParserConfiguration pconf = new ParserConfiguration();
    ParserContext pctx = new ParserContext(pconf);
    pctx.setStrongTyping(true);
    pctx.addInput("this", Bar.class);
    ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
    Bar ctx = new Bar();
    ctx.setName("bob");
    Boolean result = (Boolean) MVEL.executeExpression(stmt, ctx);
    assertTrue(result);
  }

  public void testStrTriangleEqualsEquals() {

    MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;

    try {
      ParserConfiguration pconf = new ParserConfiguration();
      ParserContext pctx = new ParserContext(pconf);
      pctx.addInput("this", Triangle.class);
      pctx.setStrongTyping(true);

      String str = "this.strLabel == this";

      try {
        ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
        fail("should have failed");
      }
      catch (CompileException e) {
        return;
      }
    }
    finally {
      MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false;
    }
  }

  public void testStrDoubleEqualsEquals() {

    MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
    try {
      ParserConfiguration pconf = new ParserConfiguration();
      ParserContext pctx = new ParserContext(pconf);
      pctx.addInput("this", Triangle.class);
      pctx.setStrongTyping(true);

      String str = "strLabel == doubleVal";

      try {
        ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
        fail("should have failed");
      }
      catch (CompileException e) {
        return;
      }
    }
    finally {
      MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false;
    }
  }
}
File
CoreConfidenceTests.java
Developer's decision
Manual
Kind of conflict
Cast expression
Class declaration
Comment
Interface declaration
Method declaration
Method invocation
Variable