0001: package org.mvel.tests.main;
0002:
0003: import org.mvel.*;
0004: import static org.mvel.MVEL.*;
0005: import org.mvel.ast.ASTNode;
0006: import org.mvel.ast.WithNode;
0007: import org.mvel.ast.Function;
0008: import org.mvel.compiler.CompiledExpression;
0009: import org.mvel.compiler.ExecutableStatement;
0010: import org.mvel.compiler.ExpressionCompiler;
0011: import org.mvel.debug.DebugTools;
0012: import org.mvel.debug.Debugger;
0013: import org.mvel.debug.Frame;
0014: import org.mvel.integration.Interceptor;
0015: import org.mvel.integration.ResolverTools;
0016: import org.mvel.integration.VariableResolverFactory;
0017: import org.mvel.integration.impl.ClassImportResolverFactory;
0018: import org.mvel.integration.impl.DefaultLocalVariableResolverFactory;
0019: import org.mvel.integration.impl.MapVariableResolverFactory;
0020: import org.mvel.integration.impl.StaticMethodImportResolverFactory;
0021: import org.mvel.optimizers.OptimizerFactory;
0022: import org.mvel.tests.main.res.*;
0023: import org.mvel.util.MethodStub;
0024: import org.mvel.util.CompilerTools;
0025: import static org.mvel.util.ParseTools.loadFromFile;
0026:
0027: import java.awt.*;
0028: import java.io.BufferedReader;
0029: import java.io.File;
0030: import java.io.IOException;
0031: import java.io.Serializable;
0032: import java.util.*;
0033: import java.util.List;
0034:
0035: @SuppressWarnings({"AssertEqualsBetweenInconvertibleTypes","UnnecessaryBoxing","unchecked","PointlessArithmeticExpression"})
0036: public class CoreConfidenceTests extends AbstractTest {
0037: public void testSingleProperty() {
0038: assertEquals(false, test("fun"));
0039: }
0040:
0041: public void testMethodOnValue() {
0042: assertEquals("DOG", test("foo.bar.name.toUpperCase()"));
0043: }
0044:
0045: public void testSimpleProperty() {
0046: assertEquals("dog", test("foo.bar.name"));
0047: }
0048:
0049: public void testSimpleProperty2() {
0050: assertEquals("cat", test("DATA"));
0051: }
0052:
0053: public void testPropertyViaDerivedClass() {
0054: assertEquals("cat", test("derived.data"));
0055: }
0056:
0057: public void testDeepAssignment() {
0058: Map map = createTestMap();
0059: assertEquals("crap", testCompiledSimple(
0060: "foo.bar.assignTest = 'crap'", map));
0061: assertEquals("crap", testCompiledSimple("foo.bar.assignTest",
0062: map));
0063: }
0064:
0065: public void testThroughInterface() {
0066: assertEquals("FOOBAR!", test("testImpl.name"));
0067: }
0068:
0069: public void testThroughInterface2() {
0070: assertEquals(true, test("testImpl.foo"));
0071: }
0072:
0073: public void testMapAccessWithMethodCall() {
0074: assertEquals("happyBar", test("funMap['foo'].happy()"));
0075: }
0076:
0077: public void testSimpleIfStatement() {
0078: test("if (true) { System.out.println(\"test!\") } \n");
0079: }
0080:
0081: public void testBooleanOperator() {
0082: assertEquals(true, test("foo.bar.woof == true"));
0083: }
0084:
0085: public void testBooleanOperator2() {
0086: assertEquals(false, test("foo.bar.woof == false"));
0087: }
0088:
0089: public void testBooleanOperator3() {
0090: assertEquals(true, test("foo.bar.woof== true"));
0091: }
0092:
0093: public void testBooleanOperator4() {
0094: assertEquals(false, test("foo.bar.woof ==false"));
0095: }
0096:
0097: public void testBooleanOperator5() {
0098: assertEquals(true, test("foo.bar.woof == true"));
0099: }
0100:
0101: public void testBooleanOperator6() {
0102: assertEquals(false, test("foo.bar.woof==false"));
0103: }
0104:
0105: public void testTextComparison() {
0106: assertEquals(true, test("foo.bar.name == 'dog'"));
0107: }
0108:
0109: public void testNETextComparison() {
0110: assertEquals(true, test("foo.bar.name != 'foo'"));
0111: }
0112:
0113: public void testChor() {
0114: assertEquals("cat", test("a or b or c"));
0115: }
0116:
0117: public void testChorWithLiteral() {
0118: assertEquals("fubar", test("a or 'fubar'"));
0119: }
0120:
0121: public void testNullCompare() {
0122: assertEquals(true, test("c != null"));
0123: }
0124:
0125: public void testUninitializedInt() {
0126: assertEquals(0, test("sarahl"));
0127: }
0128:
0129: public void testAnd() {
0130: assertEquals(
0131: true,
0132: test("c != null && foo.bar.name == 'dog' && foo.bar.woof"));
0133: }
0134:
0135: public void testAnd2() {
0136: assertEquals(true,
0137: test("c!=null&&foo.bar.name=='dog'&&foo.bar.woof"));
0138: }
0139:
0140: public void testMath() {
0141: assertEquals(188.4f, test("pi * hour"));
0142: }
0143:
0144: public void testMath2() {
0145: assertEquals(3, test("foo.number-1"));
0146: }
0147:
0148: public void testMath3() {
0149: assertEquals((10d * 5d) * 2d / 3d, test("(10 * 5) * 2 / 3"));
0150: }
0151:
0152: public void testMath4() {
0153: int val = (int) ((100d % 3d) * 2d - 1d / 1d + 8d + (5d * 2d));
0154: assertEquals(val, test("(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)"));
0155: }
0156:
0157: public void testMath5() {
0158: assertEquals(300.5 / 5.3 / 2.1 / 1.5,
0159: test("300.5 / 5.3 / 2.1 / 1.5"));
0160: }
0161:
0162: public void testMath6() {
0163: int val = (300 * 5 + 1) + 100 / 2 * 2;
0164: assertEquals(val, test("(300 * five + 1) + (100 / 2 * 2)"));
0165: }
0166:
0167: public void testMath7() {
0168: int val = (int) ((100d % 3d) * 2d - 1d / 1d + 8d + (5d * 2d));
0169: assertEquals(val, test("(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)"));
0170: }
0171:
0172: public void testMath8() {
0173: float val = 5f * (100.56f * 30.1f);
0174: assertEquals(val, test("5 * (100.56 * 30.1)"));
0175: }
0176:
0177: public void testPowerOf() {
0178: assertEquals(25, test("5 ** 2"));
0179: }
0180:
0181: public void testWhileUsingImports() {
0182: Map<String, Object> imports = new HashMap<String, Object>();
0183: imports.put("ArrayList", java.util.ArrayList.class);
0184: imports.put("List", java.util.List.class);
0185:
0186: ParserContext context = new ParserContext(imports, null,
0187: "testfile");
0188: ExpressionCompiler compiler = new ExpressionCompiler(
0189: "List list = new ArrayList(); return (list == empty)");
0190: assertTrue((Boolean) MVEL.executeExpression(compiler
0191: .compile(context),
0192: new DefaultLocalVariableResolverFactory()));
0193: }
0194:
0195: public void testComplexExpression() {
0196: assertEquals(
0197: "bar",
0198: test("a = 'foo'; b = 'bar'; c = 'jim'; list = {a,b,c}; list[1]"));
0199: }
0200:
0201: public void testComplexAnd() {
0202: assertEquals(true,
0203: test("(pi * hour) > 0 && foo.happy() == 'happyBar'"));
0204: }
0205:
0206: public void testShortPathExpression() {
0207: assertEquals(null,
0208: test("3 > 4 && foo.toUC('test'); foo.register"));
0209: }
0210:
0211: public void testShortPathExpression2() {
0212: assertEquals(true, test("4 > 3 || foo.toUC('test')"));
0213: }
0214:
0215: public void testShortPathExpression4() {
0216: assertEquals(true, test("4>3||foo.toUC('test')"));
0217: }
0218:
0219: public void testOrOperator() {
0220: assertEquals(true, test("true||true"));
0221: }
0222:
0223: public void testOrOperator2() {
0224: assertEquals(true, test("2 > 3 || 3 > 2"));
0225: }
0226:
0227: public void testOrOperator3() {
0228: assertEquals(true, test("pi > 5 || pi > 6 || pi > 3"));
0229: }
0230:
0231: public void testShortPathExpression3() {
0232: assertEquals(false,
0233: test("defnull != null && defnull.length() > 0"));
0234: }
0235:
0236: public void testModulus() {
0237: assertEquals(38392 % 2, test("38392 % 2"));
0238: }
0239:
0240: public void testLessThan() {
0241: assertEquals(true, test("pi < 3.15"));
0242: assertEquals(true, test("pi <= 3.14"));
0243: assertEquals(false, test("pi > 3.14"));
0244: assertEquals(true, test("pi >= 3.14"));
0245: }
0246:
0247: public void testMethodAccess() {
0248: assertEquals("happyBar", test("foo.happy()"));
0249: }
0250:
0251: public void testMethodAccess2() {
0252: assertEquals("FUBAR", test("foo.toUC( 'fubar' )"));
0253: }
0254:
0255: public void testMethodAccess3() {
0256: assertEquals(true, test("equalityCheck(c, 'cat')"));
0257: }
0258:
0259: public void testMethodAccess4() {
0260: assertEquals(null, test("readBack(null)"));
0261: }
0262:
0263: public void testMethodAccess5() {
0264: assertEquals("nulltest", test("appendTwoStrings(null, 'test')"));
0265: }
0266:
0267: public void testMethodAccess6() {
0268: assertEquals(
0269: true,
0270: test(" equalityCheck( c \n , \n 'cat' ) "));
0271: }
0272:
0273: public void testNegation() {
0274: assertEquals(true, test("!fun && !fun"));
0275: }
0276:
0277: public void testNegation2() {
0278: assertEquals(false, test("fun && !fun"));
0279: }
0280:
0281: public void testNegation3() {
0282: assertEquals(true, test("!(fun && fun)"));
0283: }
0284:
0285: public void testNegation4() {
0286: assertEquals(false, test("(fun && fun)"));
0287: }
0288:
0289: public void testMultiStatement() {
0290: assertEquals(true, test("populate(); barfoo == 'sarah'"));
0291: }
0292:
0293: public void testAssignment() {
0294: assertEquals(
0295: true,
0296: test("populate(); blahfoo = 'sarah'; blahfoo == 'sarah'"));
0297: }
0298:
0299: public void testAssignment2() {
0300: assertEquals("sarah", test("populate(); blahfoo = barfoo"));
0301: }
0302:
0303: public void testAssignment3() {
0304: assertEquals(java.lang.Integer.class, test("blah = 5")
0305: .getClass());
0306: }
0307:
0308: public void testAssignment4() {
0309: assertEquals(102, test("a = 100 + 1 + 1"));
0310: }
0311:
0312: public void testOr() {
0313: assertEquals(true, test("fun || true"));
0314: }
0315:
0316: public void testLiteralPassThrough() {
0317: assertEquals(true, test("true"));
0318: }
0319:
0320: public void testLiteralPassThrough2() {
0321: assertEquals(false, test("false"));
0322: }
0323:
0324: public void testLiteralPassThrough3() {
0325: assertEquals(null, test("null"));
0326: }
0327:
0328: public void testLiteralReduction1() {
0329: assertEquals("foo", test("null or 'foo'"));
0330: }
0331:
0332: public void testRegEx() {
0333: assertEquals(true, test("foo.bar.name ~= '[a-z].+'"));
0334: }
0335:
0336: public void testRegExNegate() {
0337: assertEquals(false, test("!(foo.bar.name ~= '[a-z].+')"));
0338: }
0339:
0340: public void testRegEx2() {
0341: assertEquals(
0342: true,
0343: test("foo.bar.name ~= '[a-z].+' && foo.bar.name != null"));
0344: }
0345:
0346: public void testRegEx3() {
0347: assertEquals(true,
0348: test("foo.bar.name~='[a-z].+'&&foo.bar.name!=null"));
0349: }
0350:
0351: public void testBlank() {
0352: assertEquals(true, test("'' == empty"));
0353: }
0354:
0355: public void testBlank2() {
0356: assertEquals(true, test("BWAH == empty"));
0357: }
0358:
0359: public void testBooleanModeOnly2() {
0360: assertEquals(false, (Object) DataConversion.convert(
0361: test("BWAH"), Boolean.class));
0362: }
0363:
0364: public void testBooleanModeOnly4() {
0365: assertEquals(true, test("hour == (hour + 0)"));
0366: }
0367:
0368: public void testTernary() {
0369: assertEquals("foobie", test("zero==0?'foobie':zero"));
0370: }
0371:
0372: public void testTernary2() {
0373: assertEquals("blimpie", test("zero==1?'foobie':'blimpie'"));
0374: }
0375:
0376: public void testTernary3() {
0377: assertEquals("foobiebarbie",
0378: test("zero==1?'foobie':'foobie'+'barbie'"));
0379: }
0380:
0381: public void testStrAppend() {
0382: assertEquals("foobarcar", test("'foo' + 'bar' + 'car'"));
0383: }
0384:
0385: public void testStrAppend2() {
0386: assertEquals("foobarcar1", test("'foobar' + 'car' + 1"));
0387: }
0388:
0389: public void testInstanceCheck1() {
0390: assertEquals(true, test("c is java.lang.String"));
0391: }
0392:
0393: public void testInstanceCheck2() {
0394: assertEquals(false, test("pi is java.lang.Integer"));
0395: }
0396:
0397: public void testInstanceCheck3() {
0398: assertEquals(true, test("foo is org.mvel.tests.main.res.Foo"));
0399: }
0400:
0401: public void testBitwiseOr1() {
0402: assertEquals(6, test("2|4"));
0403: }
0404:
0405: public void testBitwiseOr2() {
0406: assertEquals(true, test("(2 | 1) > 0"));
0407: }
0408:
0409: public void testBitwiseOr3() {
0410: assertEquals(true, test("(2|1) == 3"));
0411: }
0412:
0413: public void testBitwiseOr4() {
0414: assertEquals(2 | 5, test("2|five"));
0415: }
0416:
0417: public void testBitwiseAnd1() {
0418: assertEquals(2, test("2 & 3"));
0419: }
0420:
0421: public void testBitwiseAnd2() {
0422: assertEquals(5 & 3, test("five & 3"));
0423: }
0424:
0425: public void testShiftLeft() {
0426: assertEquals(4, test("2 << 1"));
0427: }
0428:
0429: public void testShiftLeft2() {
0430: assertEquals(5 << 1, test("five << 1"));
0431: }
0432:
0433: public void testUnsignedShiftLeft() {
0434: assertEquals(2, test("-2 <<< 0"));
0435: }
0436:
0437: public void testUnsignedShiftLeft2() {
0438: assertEquals(5, test("(five - 10) <<< 0"));
0439: }
0440:
0441: public void testShiftRight() {
0442: assertEquals(128, test("256 >> 1"));
0443: }
0444:
0445: public void testShiftRight2() {
0446: assertEquals(5 >> 1, test("five >> 1"));
0447: }
0448:
0449: public void testUnsignedShiftRight() {
0450: assertEquals(-5 >>> 1, test("-5 >>> 1"));
0451: }
0452:
0453: public void testUnsignedShiftRight2() {
0454: assertEquals(-5 >>> 1, test("(five - 10) >>> 1"));
0455: }
0456:
0457: public void testXOR() {
0458: assertEquals(3, test("1 ^ 2"));
0459: }
0460:
0461: public void testXOR2() {
0462: assertEquals(5 ^ 2, test("five ^ 2"));
0463: }
0464:
0465: public void testContains1() {
0466: assertEquals(true, test("list contains 'Happy!'"));
0467: }
0468:
0469: public void testContains2() {
0470: assertEquals(false, test("list contains 'Foobie'"));
0471: }
0472:
0473: public void testContains3() {
0474: assertEquals(true, test("sentence contains 'fox'"));
0475: }
0476:
0477: public void testContains4() {
0478: assertEquals(false, test("sentence contains 'mike'"));
0479: }
0480:
0481: public void testContains5() {
0482: assertEquals(true, test("!(sentence contains 'mike')"));
0483: }
0484:
0485: public void testContains6() {
0486: assertEquals(
0487: true,
0488: test("bwahbwah = 'mikebrock'; testVar10 = 'mike'; bwahbwah contains testVar10"));
0489: }
0490:
0491: public void testInvert() {
0492: assertEquals(~10, test("~10"));
0493: }
0494:
0495: public void testInvert2() {
0496: assertEquals(~(10 + 1), test("~(10 + 1)"));
0497: }
0498:
0499: public void testInvert3() {
0500: assertEquals(~10 + (1 + ~50), test("~10 + (1 + ~50)"));
0501: }
0502:
0503: public void testListCreation2() {
0504: assertTrue(test("[\"test\"]") instanceof List);
0505: }
0506:
0507: public void testListCreation3() {
0508: assertTrue(test("[66]") instanceof List);
0509: }
0510:
0511: public void testListCreation4() {
0512: List ar = (List) test("[ 66 , \"test\" ]");
0513: assertEquals(2, ar.size());
0514: assertEquals(66, ar.get(0));
0515: assertEquals("test", ar.get(1));
0516: }
0517:
0518: public void testListCreationWithCall() {
0519: assertEquals(1, test("[\"apple\"].size()"));
0520: }
0521:
0522: public void testArrayCreationWithLength() {
0523: assertEquals(2, test("Array.getLength({'foo', 'bar'})"));
0524: }
0525:
0526: public void testEmptyList() {
0527: assertTrue(test("[]") instanceof List);
0528: }
0529:
0530: public void testEmptyArray() {
0531: assertTrue(((Object[]) test("{}")).length == 0);
0532: }
0533:
0534: public void testEmptyArray2() {
0535: assertTrue(((Object[]) test("{ }")).length == 0);
0536: }
0537:
0538: public void testArrayCreation() {
0539: assertEquals(
0540: 0,
0541: test("arrayTest = {{1, 2, 3}, {2, 1, 0}}; arrayTest[1][2]"));
0542: }
0543:
0544: public void testMapCreation() {
0545: assertEquals(
0546: "sarah",
0547: test("map = ['mike':'sarah','tom':'jacquelin']; map['mike']"));
0548: }
0549:
0550: public void testMapCreation2() {
0551: assertEquals(
0552: "sarah",
0553: test("map = ['mike' :'sarah' ,'tom' :'jacquelin' ]; map['mike']"));
0554: }
0555:
0556: public void testMapCreation3() {
0557: assertEquals("foo", test("map = [1 : 'foo']; map[1]"));
0558: }
0559:
0560: public void testProjectionSupport() {
0561: assertEquals(true, test("(name in things)contains'Bob'"));
0562: }
0563:
0564: public void testProjectionSupport1() {
0565: assertEquals(true, test("(name in things) contains 'Bob'"));
0566: }
0567:
0568: public void testProjectionSupport2() {
0569: assertEquals(3, test("(name in things).size()"));
0570: }
0571:
0572: public void testSizeOnInlineArray() {
0573: assertEquals(3, test("{1,2,3}.size()"));
0574: }
0575:
0576: public void testSimpleListCreation() {
0577: test("['foo', 'bar', 'foobar', 'FOOBAR']");
0578: }
0579:
0580: public void testStaticMethodFromLiteral() {
0581: assertEquals(
0582: String.class.getName(),
0583: test("String.valueOf(Class.forName('java.lang.String').getName())"));
0584: }
0585:
0586: // public void testMethodCallsEtc() {
0587: // test("title = 1; " +
0588: // "frame = new javax.swing.JFrame; " +
0589: // "label = new javax.swing.JLabel; " +
0590: // "title = title + 1;" +
0591: // "frame.setTitle(title);" +
0592: // "label.setText('MVEL UNIT TEST PACKAGE -- IF YOU SEE THIS, THAT IS GOOD');" +
0593: // "frame.getContentPane().add(label);" +
0594: // "frame.pack();" +
0595: // "frame.setVisible(true);");
0596: // }
0597:
0598: public void testObjectInstantiation() {
0599: test("new java.lang.String('foobie')");
0600: }
0601:
0602: public void testObjectInstantiationWithMethodCall() {
0603: assertEquals("FOOBIE",
0604: test("new String('foobie') . toUpperCase()"));
0605: }
0606:
0607: public void testObjectInstantiation2() {
0608: test("new String() is String");
0609: }
0610:
0611: public void testObjectInstantiation3() {
0612: test("new java.text.SimpleDateFormat('yyyy').format(new java.util.Date(System.currentTimeMillis()))");
0613: }
0614:
0615: public void testArrayCoercion() {
0616: assertEquals("gonk", test("funMethod( {'gonk', 'foo'} )"));
0617: }
0618:
0619: public void testArrayCoercion2() {
0620: assertEquals(10, test("sum({2,2,2,2,2})"));
0621: }
0622:
0623: public void testMapAccess() {
0624: assertEquals("dog", test("funMap['foo'].bar.name"));
0625: }
0626:
0627: public void testMapAccess2() {
0628: assertEquals("dog", test("funMap.foo.bar.name"));
0629: }
0630:
0631: public void testSoundex() {
0632: assertTrue((Boolean) test("'foobar' soundslike 'fubar'"));
0633: }
0634:
0635: public void testSoundex2() {
0636: assertFalse((Boolean) test("'flexbar' soundslike 'fubar'"));
0637: }
0638:
0639: public void testSoundex3() {
0640: assertEquals(true, test("c soundslike 'kat'"));
0641: }
0642:
0643: public void testSimilarity1() {
0644: assertEquals(0.6666667f, test("c strsim 'kat'"));
0645: }
0646:
0647: public void testThisReference() {
0648: assertEquals(true, test("this") instanceof Base);
0649: }
0650:
0651: public void testThisReference2() {
0652: assertEquals(true, test("this.funMap") instanceof Map);
0653: }
0654:
0655: public void testThisReference3() {
0656: assertEquals(true, test("this is org.mvel.tests.main.res.Base"));
0657: }
0658:
0659: public void testThisReference4() {
0660: assertEquals(true, test("this.funMap instanceof java.util.Map"));
0661: }
0662:
0663: public void testThisReference5() {
0664: assertEquals(true, test("this.data == 'cat'"));
0665: }
0666:
0667: public void testThisReferenceInMethodCall() {
0668: assertEquals(101, test("Integer.parseInt(this.number)"));
0669: }
0670:
0671: public void testThisReferenceInConstructor() {
0672: assertEquals("101", test("new String(this.number)"));
0673: }
0674:
0675: // interpreted
0676: public void testThisReferenceMapVirtualObjects() {
0677: Map<String, String> map = new HashMap<String, String>();
0678: map.put("foo", "bar");
0679:
0680: VariableResolverFactory factory = new MapVariableResolverFactory(
0681: new HashMap<String, Object>());
0682: factory.createVariable("this", map);
0683:
0684: assertEquals(true, eval("this.foo == 'bar'", map, factory));
0685: }
0686:
0687: // compiled - reflective
0688: public void testThisReferenceMapVirtualObjects1() {
0689: // Create our root Map object
0690: Map<String, String> map = new HashMap<String, String>();
0691: map.put("foo", "bar");
0692:
0693: VariableResolverFactory factory = new MapVariableResolverFactory(
0694: new HashMap<String, Object>());
0695: factory.createVariable("this", map);
0696:
0697: Serializable compiled = MVEL
0698: .compileExpression("this.foo == 'bar'");
0699:
0700: OptimizerFactory.setDefaultOptimizer("reflective");
0701:
0702: // Run test
0703: assertEquals(true, MVEL.executeExpression(compiled, map,
0704: factory));
0705: }
0706:
0707: // compiled - asm
0708: public void testThisReferenceMapVirtualObjects2() {
0709: // Create our root Map object
0710: Map<String, String> map = new HashMap<String, String>();
0711: map.put("foo", "bar");
0712:
0713: VariableResolverFactory factory = new MapVariableResolverFactory(
0714: new HashMap<String, Object>());
0715: factory.createVariable("this", map);
0716:
0717: // I think we can all figure this one out.
0718: Serializable compiled = MVEL
0719: .compileExpression("this.foo == 'bar'");
0720:
0721: if (!Boolean.getBoolean("mvel.disable.jit"))
0722: OptimizerFactory.setDefaultOptimizer("ASM");
0723:
0724: // Run test
0725: assertEquals(true, MVEL.executeExpression(compiled, map,
0726: factory));
0727: }
0728:
0729: public void testStringEscaping() {
0730: assertEquals("\"Mike Brock\"", test("\"\\\"Mike Brock\\\"\""));
0731: }
0732:
0733: public void testStringEscaping2() {
0734: assertEquals("MVEL's Parser is Fast",
0735: test("'MVEL\\'s Parser is Fast'"));
0736: }
0737:
0738: public void testEvalToBoolean() {
0739: assertEquals(true, (boolean) evalToBoolean("true ", "true"));
0740: assertEquals(true, (boolean) evalToBoolean("true ", "true"));
0741: }
0742:
0743: public void testCompiledMapStructures() {
0744: Serializable compiled = compileExpression("['foo':'bar'] contains 'foo'");
0745: executeExpression(compiled, null, null, Boolean.class);
0746: }
0747:
0748: public void testSubListInMap() {
0749: assertEquals(
0750: "pear",
0751: test("map = ['test' : 'poo', 'foo' : [c, 'pear']]; map['foo'][1]"));
0752: }
0753:
0754: public void testCompiledMethodCall() {
0755: Serializable compiled = compileExpression("c.getClass()");
0756: assertEquals(String.class, executeExpression(compiled,
0757: new Base(), createTestMap()));
0758: }
0759:
0760: public void testStaticNamespaceCall() {
0761: assertEquals(java.util.ArrayList.class,
0762: test("java.util.ArrayList"));
0763: }
0764:
0765: public void testStaticNamespaceClassWithMethod() {
0766: assertEquals("FooBar",
0767: test("java.lang.String.valueOf('FooBar')"));
0768: }
0769:
0770: public void testConstructor() {
0771: assertEquals("foo",
0772: test("a = 'foobar'; new String(a.toCharArray(), 0, 3)"));
0773: }
0774:
0775: public void testStaticNamespaceClassWithField() {
0776: assertEquals(Integer.MAX_VALUE,
0777: test("java.lang.Integer.MAX_VALUE"));
0778: }
0779:
0780: public void testStaticNamespaceClassWithField2() {
0781: assertEquals(Integer.MAX_VALUE, test("Integer.MAX_VALUE"));
0782: }
0783:
0784: public void testStaticFieldAsMethodParm() {
0785: assertEquals(String.valueOf(Integer.MAX_VALUE),
0786: test("String.valueOf(Integer.MAX_VALUE)"));
0787: }
0788:
0789: public void testEmptyIf() {
0790: assertEquals(5, test("a = 5; if (a == 5) { }; return a;"));
0791: }
0792:
0793: public void testEmptyIf2() {
0794: assertEquals(5, test("a=5;if(a==5){};return a;"));
0795: }
0796:
0797: public void testIf() {
0798: assertEquals(10,
0799: test("if (5 > 4) { return 10; } else { return 5; }"));
0800: }
0801:
0802: public void testIf2() {
0803: assertEquals(10,
0804: test("if (5 < 4) { return 5; } else { return 10; }"));
0805: }
0806:
0807: public void testIf3() {
0808: assertEquals(10, test("if(5<4){return 5;}else{return 10;}"));
0809: }
0810:
0811: public void testIfAndElse() {
0812: assertEquals(
0813: true,
0814: test("if (false) { return false; } else { return true; }"));
0815: }
0816:
0817: public void testIfAndElseif() {
0818: assertEquals(
0819: true,
0820: test("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;"));
0821: }
0822:
0823: public void testIfAndElseIfCondensedGrammar() {
0824: assertEquals("Foo",
0825: test("if (false) return 'Bar'; else return 'Foo';"));
0826: }
0827:
0828: public void testForEach2() {
0829: assertEquals(
0830: 6,
0831: test("total = 0; a = {1,2,3}; foreach(item : a) { total += item }; total"));
0832: }
0833:
0834: public void testForEach3() {
0835: assertEquals(
0836: true,
0837: test("a = {1,2,3}; foreach (i : a) { if (i == 1) { return true; } }"));
0838: }
0839:
0840: public void testForEach4() {
0841: assertEquals(
0842: "OneTwoThreeFour",
0843: test("a = {1,2,3,4}; builder = ''; foreach (i : a) {"
0844: + " if (i == 1) { builder += 'One' } else if (i == 2) { builder += 'Two' } "
0845: + "else if (i == 3) { builder += 'Three' } else { builder += 'Four' }"
0846: + "}; builder;"));
0847: }
0848:
0849: public void testWith() {
0850: assertEquals(
0851: "OneTwo",
0852: test("with (foo) {aValue = 'One',bValue='Two'}; foo.aValue + foo.bValue;"));
0853: }
0854:
0855: public void testWith2() {
0856: assertEquals("OneTwo", test("with (foo) { \n"
0857: + "aValue = 'One', // this is a comment \n"
0858: + "bValue='Two' // this is also a comment \n"
0859: + "}; \n" + "foo.aValue + foo.bValue;"));
0860: }
0861:
0862: // public void testAssertion() {
0863: // try {
0864: // test("assert false");
0865: // assertTrue(false);
0866: // }
0867: // catch (AssertionError error) {
0868: // }
0869: // }
0870:
0871: // public void testAssertion2() {
0872: // try {
0873: // test("assert true;");
0874: // }
0875: // catch (AssertionError error) {
0876: // assertTrue(false);
0877: // }
0878: // }
0879:
0880: public void testMagicArraySize() {
0881: assertEquals(5, test("stringArray.size()"));
0882: }
0883:
0884: public void testMagicArraySize2() {
0885: assertEquals(5, test("intArray.size()"));
0886: }
0887:
0888: public void testStaticVarAssignment() {
0889: assertEquals("1", test("String mikeBrock = 1; mikeBrock"));
0890: }
0891:
0892: // public void testIntentionalFailure() {
0893: // try {
0894: // test("int = 0"); // should fail because int is a reserved word.
0895: // assertTrue(false);
0896: // }
0897: // catch (Exception e) {
0898: // }
0899: // }
0900:
0901: public void testImport() {
0902: assertEquals(HashMap.class,
0903: test("import java.util.HashMap; HashMap;"));
0904: }
0905:
0906: public void testStaticImport() {
0907: assertEquals(2.0,
0908: test("import_static java.lang.Math.sqrt; sqrt(4)"));
0909: }
0910:
0911: public void testFunctionPointer() {
0912: assertEquals(2.0,
0913: test("squareRoot = java.lang.Math.sqrt; squareRoot(4)"));
0914: }
0915:
0916: public void testFunctionPointerAsParam() {
0917: assertEquals(
0918: "2.0",
0919: test("squareRoot = Math.sqrt; new String(String.valueOf(squareRoot(4)));"));
0920: }
0921:
0922: public void testFunctionPointerInAssignment() {
0923: assertEquals(
0924: 5.0,
0925: test("squareRoot = Math.sqrt; i = squareRoot(25); return i;"));
0926: }
0927:
0928: public void testIncrementOperator() {
0929: assertEquals(2, test("x = 1; x++; x"));
0930: }
0931:
0932: public void testPreIncrementOperator() {
0933: assertEquals(2, test("x = 1; ++x"));
0934: }
0935:
0936: public void testDecrementOperator() {
0937: assertEquals(1, test("x = 2; x--; x"));
0938: }
0939:
0940: public void testPreDecrementOperator() {
0941: assertEquals(1, test("x = 2; --x"));
0942: }
0943:
0944: public void testQualifiedStaticTyping() {
0945: assertEquals(
0946: 20,
0947: test("java.math.BigDecimal a = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal b = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal c = a + b; return c; "));
0948: }
0949:
0950: public void testUnQualifiedStaticTyping() {
0951: assertEquals(
0952: 20.0f,
0953: testCompiledSimple(
0954: "import java.math.BigDecimal; BigDecimal a = new BigDecimal( 10.0 ); BigDecimal b = new BigDecimal( 10.0 ); BigDecimal c = a + b; return c; ",
0955: new HashMap()));
0956: }
0957:
0958: public void testObjectCreation() {
0959: assertEquals(6, test("new Integer( 6 )"));
0960: }
0961:
0962: public void testTernary4() {
0963: assertEquals("<test>", test("true ? '<test>' : '<poo>'"));
0964: }
0965:
0966: public void testStringAsCollection() {
0967: assertEquals('o', test("abc = 'foo'; abc[1]"));
0968: }
0969:
0970: public void testSubExpressionIndexer() {
0971: assertEquals(
0972: "bar",
0973: test("xx = new java.util.HashMap(); xx.put('foo', 'bar'); prop = 'foo'; xx[prop];"));
0974: }
0975:
0976: public void testCompileTimeLiteralReduction() {
0977: assertEquals(1000, test("10 * 100"));
0978: }
0979:
0980: public void testInterfaceResolution() {
0981: Serializable ex = MVEL
0982: .compileExpression("foo.collectionTest.size()");
0983:
0984: Map map = createTestMap();
0985: Foo foo = (Foo) map.get("foo");
0986: foo.setCollectionTest(new HashSet());
0987: Object result1 = MVEL.executeExpression(ex, foo, map);
0988:
0989: foo.setCollectionTest(new ArrayList());
0990: Object result2 = MVEL.executeExpression(ex, foo, map);
0991:
0992: assertEquals(result1, result2);
0993: }
0994:
0995: /**
0996: * Start collections framework based compliance tests
0997: */
0998: public void testCreationOfSet() {
0999: assertEquals("foo bar foo bar",
1000: test("set = new java.util.LinkedHashSet(); "
1001: + "set.add('foo');" + "set.add('bar');"
1002: + "output = '';" + "foreach (item : set) {"
1003: + "output = output + item + ' ';" + "} "
1004: + "foreach (item : set) {"
1005: + "output = output + item + ' ';" + "} "
1006: + "output = output.trim();"
1007: + "if (set.size() == 2) { return output; }"));
1008:
1009: }
1010:
1011: public void testCreationOfList() {
1012: assertEquals(5, test("l = new java.util.LinkedList();"
1013: + "l.add('fun');" + "l.add('happy');" + "l.add('fun');"
1014: + "l.add('slide');" + "l.add('crap');"
1015: + "poo = new java.util.ArrayList(l);" + "poo.size();"));
1016: }
1017:
1018: public void testMapOperations() {
1019: assertEquals("poo5", test("l = new java.util.ArrayList();"
1020: + "l.add('plop');" + "l.add('poo');"
1021: + "m = new java.util.HashMap();" + "m.put('foo', l);"
1022: + "m.put('cah', 'mah');" + "m.put('bar', 'foo');"
1023: + "m.put('sarah', 'mike');" + "m.put('edgar', 'poe');"
1024: + "" + "if (m.edgar == 'poe') {"
1025: + "return m.foo[1] + m.size();" + "}"));
1026: }
1027:
1028: public void testStackOperations() {
1029: assertEquals(10, test("stk = new java.util.Stack();"
1030: + "stk.push(5);" + "stk.push(5);"
1031: + "stk.pop() + stk.pop();"));
1032: }
1033:
1034: public void testSystemOutPrint() {
1035: test("a = 0;\r\nSystem.out.println('This is a test');");
1036: }
1037:
1038: public void testBreakpoints() {
1039: ExpressionCompiler compiler = new ExpressionCompiler(
1040: "a = 5;\nb = 5;\n\nif (a == b) {\n\nSystem.out.println('Good');\nreturn a + b;\n}\n");
1041: System.out.println("-------\n" + compiler.getExpression()
1042: + "\n-------\n");
1043:
1044: compiler.setDebugSymbols(true);
1045:
1046: ParserContext ctx = new ParserContext();
1047: ctx.setSourceFile("test.mv");
1048:
1049: CompiledExpression compiled = compiler.compile(ctx);
1050:
1051: System.out.println(DebugTools.decompile(compiled));
1052:
1053: MVELRuntime.registerBreakpoint("test.mv", 7);
1054:
1055: Debugger testDebugger = new Debugger() {
1056:
1057: public int onBreak(Frame frame) {
1058: System.out.println("Breakpoint [source:"
1059: + frame.getSourceName() + "; line:"
1060: + frame.getLineNumber() + "]");
1061:
1062: return 0;
1063: }
1064:
1065: };
1066:
1067: MVELRuntime.setThreadDebugger(testDebugger);
1068:
1069: assertEquals(10, MVEL.executeDebugger(compiled, null,
1070: new MapVariableResolverFactory(createTestMap())));
1071: }
1072:
1073: public void testBreakpoints2() {
1074: ExpressionCompiler compiler = new ExpressionCompiler(
1075: "System.out.println('test the debugger');\n a = 0;");
1076: compiler.setDebugSymbols(true);
1077:
1078: ParserContext ctx = new ParserContext();
1079: ctx.setSourceFile("test.mv");
1080:
1081: CompiledExpression compiled = compiler.compile(ctx);
1082:
1083: System.out.println(DebugTools.decompile(compiled));
1084: }
1085:
1086: public void testBreakpoints3() {
1087: String expr = "System.out.println( \"a1\" );\n"
1088: + "System.out.println( \"a2\" );\n"
1089: + "System.out.println( \"a3\" );\n"
1090: + "System.out.println( \"a4\" );\n";
1091:
1092: ExpressionCompiler compiler = new ExpressionCompiler(expr);
1093: // compiler.setDebugSymbols(true);
1094:
1095: ParserContext context = new ParserContext();
1096: context.addImport("System", System.class);
1097: context.setStrictTypeEnforcement(true);
1098: context.setDebugSymbols(true);
1099: context.setSourceFile("mysource");
1100:
1101: Serializable compiledExpression = compiler.compile(context);
1102:
1103: String s = org.mvel.debug.DebugTools
1104: .decompile(compiledExpression);
1105:
1106: System.out.println("output: " + s);
1107:
1108: int fromIndex = 0;
1109: int count = 0;
1110: while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
1111: count++;
1112: }
1113: assertEquals(4, count);
1114:
1115: }
1116:
1117: public void testBreakpointsAcrossWith() {
1118: String line1 = "System.out.println( \"a1\" );\n";
1119: String line2 = "c = new Cheese();\n";
1120: String line3 = "with ( c ) { type = 'cheddar',\n"
1121: + " price = 10 };\n";
1122: String line4 = "System.out.println( \"a1\" );\n";
1123: String expr = line1 + line2 + line3 + line4;
1124:
1125: System.out.println(expr);
1126:
1127: ExpressionCompiler compiler = new ExpressionCompiler(expr);
1128: // compiler.setDebugSymbols(true);
1129:
1130: ParserContext context = new ParserContext();
1131: context.addImport("System", System.class);
1132: context.addImport("Cheese", Cheese.class);
1133: context.setStrictTypeEnforcement(true);
1134: context.setDebugSymbols(true);
1135: context.setSourceFile("mysource");
1136:
1137: Serializable compiledExpression = compiler.compile(context);
1138:
1139: String s = org.mvel.debug.DebugTools
1140: .decompile(compiledExpression);
1141:
1142: System.out.println("output: " + s);
1143:
1144: int fromIndex = 0;
1145: int count = 0;
1146: while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
1147: count++;
1148: }
1149: assertEquals(5, count);
1150:
1151: }
1152:
1153: public void testBreakpointsAcrossComments() {
1154: String expression = "/** This is a comment\n" + // 1
1155: " * Second comment line\n" + // 2
1156: " * Third Comment Line\n" + // 3
1157: " */\n" + // 4
1158: "System.out.println('4');\n" + // 5
1159: "System.out.println('5');\n" + // 6
1160: "a = 0;\n" + // 7
1161: "b = 1;\n" + // 8
1162: "a + b"; // 9
1163:
1164: ExpressionCompiler compiler = new ExpressionCompiler(expression);
1165: compiler.setDebugSymbols(true);
1166:
1167: System.out.println("Expression:\n------------");
1168: System.out.println(expression);
1169: System.out.println("------------");
1170:
1171: ParserContext ctx = new ParserContext();
1172: ctx.setSourceFile("test2.mv");
1173:
1174: CompiledExpression compiled = compiler.compile(ctx);
1175:
1176: System.out.println(DebugTools.decompile(compiled));
1177:
1178: MVELRuntime.registerBreakpoint("test2.mv", 9);
1179:
1180: Debugger testDebugger = new Debugger() {
1181:
1182: public int onBreak(Frame frame) {
1183: System.out.println("Breakpoint Encountered [source:"
1184: + frame.getSourceName() + "; line:"
1185: + frame.getLineNumber() + "]");
1186: System.out.println("vars:"
1187: + frame.getFactory().getKnownVariables());
1188: System.out.println("Resume Execution");
1189: return 0;
1190: }
1191:
1192: };
1193:
1194: MVELRuntime.setThreadDebugger(testDebugger);
1195:
1196: assertEquals(1, MVEL.executeDebugger(compiled, null,
1197: new MapVariableResolverFactory(createTestMap())));
1198: }
1199:
1200: public void testBreakpointsAcrossComments2() {
1201: ExpressionCompiler compiler = new ExpressionCompiler(
1202: "// This is a comment\n" + // 1
1203: "//Second comment line\n" + // 2
1204: "//Third Comment Line\n" + // 3
1205: "\n" + // 4
1206: "//Test\n" + // 5
1207: "System.out.println('4');\n" + // 6
1208: "//System.out.println('5'); \n" + // 7
1209: "a = 0;\n" + // 8
1210: "b = 1;\n" + // 9
1211: " a + b"); // 10
1212:
1213: compiler.setDebugSymbols(true);
1214:
1215: ParserContext ctx = new ParserContext();
1216: ctx.setSourceFile("test2.mv");
1217:
1218: CompiledExpression compiled = compiler.compile(ctx);
1219:
1220: System.out.println(DebugTools.decompile(compiled));
1221:
1222: MVELRuntime.registerBreakpoint("test2.mv", 6);
1223: MVELRuntime.registerBreakpoint("test2.mv", 8);
1224: MVELRuntime.registerBreakpoint("test2.mv", 9);
1225: MVELRuntime.registerBreakpoint("test2.mv", 10);
1226:
1227: Debugger testDebugger = new Debugger() {
1228: public int onBreak(Frame frame) {
1229: System.out.println("Breakpoint [source:"
1230: + frame.getSourceName() + "; line:"
1231: + frame.getLineNumber() + "]");
1232: return 0;
1233: }
1234: };
1235:
1236: MVELRuntime.setThreadDebugger(testDebugger);
1237:
1238: assertEquals(1, MVEL.executeDebugger(compiled, null,
1239: new MapVariableResolverFactory(createTestMap())));
1240: }
1241:
1242: public void testBreakpoints4() {
1243: String expression = "System.out.println('foo');\n"
1244: + "a = new Foo();\n" + "update (a) { name = 'bar' };\n"
1245: + "System.out.println('name:' + a.name);\n"
1246: + "return a.name;";
1247:
1248: Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
1249: Map<String, Macro> macros = new HashMap<String, Macro>();
1250:
1251: interceptors.put("Update", new Interceptor() {
1252: public int doBefore(ASTNode node,
1253: VariableResolverFactory factory) {
1254: ((WithNode) node).getNestedStatement().getValue(null,
1255: factory);
1256: System.out
1257: .println("fired update interceptor -- before");
1258: return 0;
1259: }
1260:
1261: public int doAfter(Object val, ASTNode node,
1262: VariableResolverFactory factory) {
1263: System.out.println("fired update interceptor -- after");
1264: return 0;
1265: }
1266: });
1267:
1268: macros.put("update", new Macro() {
1269: public String doMacro() {
1270: return "@Update with";
1271: }
1272: });
1273:
1274: expression = parseMacros(expression, macros);
1275:
1276: ExpressionCompiler compiler = new ExpressionCompiler(expression);
1277: compiler.setDebugSymbols(true);
1278:
1279: ParserContext ctx = new ParserContext();
1280: ctx.setSourceFile("test2.mv");
1281: ctx.addImport("Foo", Foo.class);
1282: ctx.setInterceptors(interceptors);
1283:
1284: CompiledExpression compiled = compiler.compile(ctx);
1285:
1286: System.out.println("\nExpression:------------");
1287: System.out.println(expression);
1288: System.out.println("------------");
1289:
1290: System.out.println(DebugTools.decompile(compiled));
1291:
1292: MVELRuntime.registerBreakpoint("test2.mv", 3);
1293: MVELRuntime.registerBreakpoint("test2.mv", 4);
1294: MVELRuntime.registerBreakpoint("test2.mv", 5);
1295: // MVELRuntime.registerBreakpoint("test2.mv", 10);
1296:
1297: Debugger testDebugger = new Debugger() {
1298: public int onBreak(Frame frame) {
1299: System.out.println("Breakpoint [source:"
1300: + frame.getSourceName() + "; line:"
1301: + frame.getLineNumber() + "]");
1302: return 0;
1303: }
1304: };
1305:
1306: MVELRuntime.setThreadDebugger(testDebugger);
1307:
1308: assertEquals("bar", MVEL.executeDebugger(compiled, null,
1309: new MapVariableResolverFactory(createTestMap())));
1310: }
1311:
1312: public void testBreakpoints5() {
1313: String expression = "System.out.println('foo');\r\n"
1314: + "a = new Foo();\r\n"
1315: + "a.name = 'bar'\r\n"
1316: + "foo.happy();\r\n"
1317: + "System.out.println( 'name:' + a.name ); \r\n"
1318: + "System.out.println( 'name:' + a.name ); \r\n"
1319: + "System.out.println( 'name:' + a.name ); \r\n"
1320: + "return a.name;";
1321:
1322: Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
1323: Map<String, Macro> macros = new HashMap<String, Macro>();
1324:
1325: interceptors.put("Update", new Interceptor() {
1326: public int doBefore(ASTNode node,
1327: VariableResolverFactory factory) {
1328: ((WithNode) node).getNestedStatement().getValue(null,
1329: factory);
1330: System.out
1331: .println("fired update interceptor -- before");
1332: return 0;
1333: }
1334:
1335: public int doAfter(Object val, ASTNode node,
1336: VariableResolverFactory factory) {
1337: System.out.println("fired update interceptor -- after");
1338: return 0;
1339: }
1340: });
1341:
1342: macros.put("update", new Macro() {
1343: public String doMacro() {
1344: return "@Update with";
1345: }
1346: });
1347:
1348: expression = parseMacros(expression, macros);
1349:
1350: ExpressionCompiler compiler = new ExpressionCompiler(expression);
1351: compiler.setDebugSymbols(true);
1352:
1353: ParserContext ctx = new ParserContext();
1354: ctx.setSourceFile("test2.mv");
1355: ctx.addImport("Foo", Foo.class);
1356: ctx.setInterceptors(interceptors);
1357:
1358: CompiledExpression compiled = compiler.compile(ctx);
1359:
1360: System.out.println("\nExpression:------------");
1361: System.out.println(expression);
1362: System.out.println("------------");
1363:
1364: System.out.println(DebugTools.decompile(compiled));
1365: MVELRuntime.registerBreakpoint("test2.mv", 1);
1366: // MVELRuntime.registerBreakpoint("test2.mv", 10);
1367:
1368: Debugger testDebugger = new Debugger() {
1369: public int onBreak(Frame frame) {
1370: System.out.println("Breakpoint [source:"
1371: + frame.getSourceName() + "; line:"
1372: + frame.getLineNumber() + "]");
1373: // System.out.println("Stepover");
1374: return Debugger.STEP_OVER;
1375: }
1376: };
1377:
1378: MVELRuntime.setThreadDebugger(testDebugger);
1379:
1380: System.out.println("\n==RUN==\n");
1381:
1382: assertEquals("bar", MVEL.executeDebugger(compiled, null,
1383: new MapVariableResolverFactory(createTestMap())));
1384:
1385: // MVELRuntime.setThreadDebugger(null);
1386: }
1387:
1388: public void testDebugSymbolsWithWindowsLinedEndings()
1389: throws Exception {
1390: String expr = " System.out.println( \"a1\" );\r\n"
1391: + " System.out.println( \"a2\" );\r\n"
1392: + " System.out.println( \"a3\" );\r\n"
1393: + " System.out.println( \"a4\" );\r\n";
1394:
1395: ExpressionCompiler compiler = new ExpressionCompiler(expr);
1396: compiler.setDebugSymbols(true);
1397:
1398: ParserContext ctx = new ParserContext();
1399: ctx.setStrictTypeEnforcement(true);
1400: ctx.setDebugSymbols(true);
1401: ctx.setSourceFile("mysource");
1402:
1403: Serializable compiledExpression = compiler.compile(ctx);
1404:
1405: String s = org.mvel.debug.DebugTools
1406: .decompile(compiledExpression);
1407:
1408: System.out.println(s);
1409:
1410: int fromIndex = 0;
1411: int count = 0;
1412: while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
1413: count++;
1414: }
1415: assertEquals(4, count);
1416:
1417: }
1418:
1419: public void testDebugSymbolsWithUnixLinedEndings() throws Exception {
1420: String expr = " System.out.println( \"a1\" );\n"
1421: + " System.out.println( \"a2\" );\n"
1422: + " System.out.println( \"a3\" );\n"
1423: + " System.out.println( \"a4\" );\n";
1424:
1425: ExpressionCompiler compiler = new ExpressionCompiler(expr);
1426: compiler.setDebugSymbols(true);
1427:
1428: ParserContext ctx = new ParserContext();
1429: ctx.setStrictTypeEnforcement(true);
1430: ctx.setDebugSymbols(true);
1431: ctx.setSourceFile("mysource");
1432:
1433: Serializable compiledExpression = compiler.compile(ctx);
1434:
1435: String s = org.mvel.debug.DebugTools
1436: .decompile(compiledExpression);
1437:
1438: int fromIndex = 0;
1439: int count = 0;
1440: while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
1441: count++;
1442: }
1443: assertEquals(4, count);
1444:
1445: }
1446:
1447: public void testDebugSymbolsWithMixedLinedEndings()
1448: throws Exception {
1449: String expr = " System.out.println( \"a1\" );\n"
1450: + " System.out.println( \"a2\" );\r\n"
1451: + " System.out.println( \"a3\" );\n"
1452: + " System.out.println( \"a4\" );\r\n";
1453:
1454: ExpressionCompiler compiler = new ExpressionCompiler(expr);
1455: compiler.setDebugSymbols(true);
1456:
1457: ParserContext ctx = new ParserContext();
1458: ctx.setStrictTypeEnforcement(true);
1459: ctx.setDebugSymbols(true);
1460: ctx.setSourceFile("mysource");
1461:
1462: Serializable compiledExpression = compiler.compile(ctx);
1463:
1464: String s = org.mvel.debug.DebugTools
1465: .decompile(compiledExpression);
1466:
1467: System.out.println(s);
1468:
1469: int fromIndex = 0;
1470: int count = 0;
1471: while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
1472: count++;
1473: }
1474: assertEquals(4, count);
1475:
1476: }
1477:
1478: public void testReflectionCache() {
1479: assertEquals("happyBar", test("foo.happy(); foo.bar.happy()"));
1480: }
1481:
1482: public void testVarInputs() {
1483: ExpressionCompiler compiler = new ExpressionCompiler(
1484: "test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;");
1485:
1486: compiler.compile();
1487:
1488: ParserContext pCtx = compiler.getParserContextState();
1489:
1490: assertEquals(4, pCtx.getInputs().size());
1491:
1492: assertTrue(pCtx.getInputs().containsKey("test"));
1493: assertTrue(pCtx.getInputs().containsKey("foo"));
1494: assertTrue(pCtx.getInputs().containsKey("bo"));
1495: assertTrue(pCtx.getInputs().containsKey("trouble"));
1496:
1497: assertEquals(2, pCtx.getVariables().size());
1498:
1499: assertTrue(pCtx.getVariables().containsKey("bleh"));
1500: assertTrue(pCtx.getVariables().containsKey("twa"));
1501:
1502: assertEquals(String.class, pCtx.getVarOrInputType("bleh"));
1503: }
1504:
1505: public void testVarInputs2() {
1506: ExpressionCompiler compiler = new ExpressionCompiler(
1507: "test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;");
1508:
1509: ParserContext ctx = new ParserContext();
1510: ctx.setRetainParserState(true);
1511:
1512: compiler.compile(ctx);
1513:
1514: System.out.println(ctx.getVarOrInputType("bleh"));
1515: }
1516:
1517: public void testVarInputs3() {
1518: ExpressionCompiler compiler = new ExpressionCompiler(
1519: "addresses['home'].street");
1520: compiler.compile();
1521:
1522: assertFalse(compiler.getParserContextState().getInputs()
1523: .keySet().contains("home"));
1524: }
1525:
1526: public void testVarInputs4() {
1527: ExpressionCompiler compiler = new ExpressionCompiler(
1528: "System.out.println( message );");
1529: compiler.compile();
1530:
1531: assertTrue(compiler.getParserContextState().getInputs()
1532: .keySet().contains("message"));
1533: }
1534:
1535: public void testAnalyzer() {
1536: ExpressionCompiler compiler = new ExpressionCompiler(
1537: "order.id == 10");
1538: compiler.compile();
1539:
1540: for (String input : compiler.getParserContextState()
1541: .getInputs().keySet()) {
1542: System.out.println("input>" + input);
1543: }
1544:
1545: assertEquals(1, compiler.getParserContextState().getInputs()
1546: .size());
1547: assertTrue(compiler.getParserContextState().getInputs()
1548: .containsKey("order"));
1549: }
1550:
1551: public void testClassImportViaFactory() {
1552: MapVariableResolverFactory mvf = new MapVariableResolverFactory(
1553: createTestMap());
1554: ClassImportResolverFactory classes = new ClassImportResolverFactory();
1555: classes.addClass(HashMap.class);
1556:
1557: ResolverTools.appendFactory(mvf, classes);
1558:
1559: Serializable compiled = compileExpression(
1560: "HashMap map = new HashMap()", classes
1561: .getImportedClasses());
1562:
1563: assertTrue(executeExpression(compiled, mvf) instanceof HashMap);
1564: }
1565:
1566: public void testSataticClassImportViaFactory() {
1567: MapVariableResolverFactory mvf = new MapVariableResolverFactory(
1568: createTestMap());
1569: ClassImportResolverFactory classes = new ClassImportResolverFactory();
1570: classes.addClass(Person.class);
1571:
1572: ResolverTools.appendFactory(mvf, classes);
1573:
1574: Serializable compiled = compileExpression(
1575: "p = new Person('tom'); return p.name;", classes
1576: .getImportedClasses());
1577:
1578: assertEquals("tom", executeExpression(compiled, mvf));
1579: }
1580:
1581: public void testSataticClassImportViaFactoryAndWithModification() {
1582: MapVariableResolverFactory mvf = new MapVariableResolverFactory(
1583: createTestMap());
1584: ClassImportResolverFactory classes = new ClassImportResolverFactory();
1585: classes.addClass(Person.class);
1586:
1587: ResolverTools.appendFactory(mvf, classes);
1588:
1589: Serializable compiled = compileExpression(
1590: "p = new Person('tom'); p.age = 20; with( p ) { age = p.age + 1 }; return p.age;",
1591: classes.getImportedClasses());
1592:
1593: assertEquals(21, executeExpression(compiled, mvf));
1594: }
1595:
1596: public void testCheeseConstructor() {
1597: MapVariableResolverFactory mvf = new MapVariableResolverFactory(
1598: createTestMap());
1599: ClassImportResolverFactory classes = new ClassImportResolverFactory();
1600: classes.addClass(Cheese.class);
1601:
1602: ResolverTools.appendFactory(mvf, classes);
1603:
1604: Serializable compiled = compileExpression(
1605: "cheese = new Cheese(\"cheddar\", 15);", classes
1606: .getImportedClasses());
1607:
1608: assertTrue(executeExpression(compiled, mvf) instanceof Cheese);
1609: }
1610:
1611: public void testInterceptors() {
1612: Interceptor testInterceptor = new Interceptor() {
1613: public int doBefore(ASTNode node,
1614: VariableResolverFactory factory) {
1615: System.out.println("BEFORE Node: " + node.getName());
1616: return 0;
1617: }
1618:
1619: public int doAfter(Object val, ASTNode node,
1620: VariableResolverFactory factory) {
1621: System.out.println("AFTER Node: " + node.getName());
1622: return 0;
1623: }
1624: };
1625:
1626: Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
1627: interceptors.put("test", testInterceptor);
1628:
1629: Serializable compiled = compileExpression(
1630: "@test System.out.println('MIDDLE');", null,
1631: interceptors);
1632:
1633: executeExpression(compiled);
1634: }
1635:
1636: public void testMacroSupport() {
1637: Map<String, Object> vars = new HashMap<String, Object>();
1638: vars.put("foo", new Foo());
1639:
1640: Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
1641: Map<String, Macro> macros = new HashMap<String, Macro>();
1642:
1643: interceptors.put("Modify", new Interceptor() {
1644: public int doBefore(ASTNode node,
1645: VariableResolverFactory factory) {
1646: ((WithNode) node).getNestedStatement().getValue(null,
1647: factory);
1648: factory.createVariable("mod", "FOOBAR!");
1649: return 0;
1650: }
1651:
1652: public int doAfter(Object val, ASTNode node,
1653: VariableResolverFactory factory) {
1654: return 0;
1655: }
1656: });
1657:
1658: macros.put("modify", new Macro() {
1659: public String doMacro() {
1660: return "@Modify with";
1661: }
1662: });
1663:
1664: ExpressionCompiler compiler = new ExpressionCompiler(
1665: parseMacros("modify (foo) { aValue = 'poo' }; mod",
1666: macros));
1667: compiler.setDebugSymbols(true);
1668:
1669: ParserContext ctx = new ParserContext(null, interceptors, null);
1670: ctx.setSourceFile("test.mv");
1671:
1672: CompiledExpression compiled = compiler.compile(ctx);
1673:
1674: assertEquals("FOOBAR!", MVEL.executeExpression(compiled, null,
1675: vars));
1676: }
1677:
1678: public void testMacroSupportWithDebugging() {
1679: Map<String, Object> vars = new HashMap<String, Object>();
1680: vars.put("foo", new Foo());
1681:
1682: Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>();
1683: Map<String, Macro> macros = new HashMap<String, Macro>();
1684:
1685: interceptors.put("Modify", new Interceptor() {
1686: public int doBefore(ASTNode node,
1687: VariableResolverFactory factory) {
1688: ((WithNode) node).getNestedStatement().getValue(null,
1689: factory);
1690:
1691: factory.createVariable("mod", "FOOBAR!");
1692:
1693: return 0;
1694: }
1695:
1696: public int doAfter(Object val, ASTNode node,
1697: VariableResolverFactory factory) {
1698: return 0;
1699: }
1700: });
1701:
1702: macros.put("modify", new Macro() {
1703: public String doMacro() {
1704: return "@Modify with";
1705: }
1706: });
1707:
1708: ExpressionCompiler compiler = new ExpressionCompiler(
1709: parseMacros("System.out.println('hello');\n"
1710: + "System.out.println('bye');\n"
1711: + "modify (foo) { aValue = 'poo', \n"
1712: + " aValue = 'poo' };\n mod", macros));
1713: compiler.setDebugSymbols(true);
1714:
1715: ParserContext ctx = new ParserContext(null, interceptors, null);
1716: ctx.setSourceFile("test.mv");
1717:
1718: CompiledExpression compiled = compiler.compile(ctx);
1719:
1720: MVELRuntime.setThreadDebugger(new Debugger() {
1721:
1722: public int onBreak(Frame frame) {
1723: System.out.println(frame.getSourceName() + ":"
1724: + frame.getLineNumber());
1725:
1726: return Debugger.STEP;
1727: }
1728: });
1729:
1730: MVELRuntime.registerBreakpoint("test.mv", 3);
1731:
1732: System.out.println(DebugTools.decompile(compiled));
1733:
1734: assertEquals("FOOBAR!", MVEL.executeDebugger(compiled, null,
1735: new MapVariableResolverFactory(vars)));
1736: }
1737:
1738: public void testExecuteCoercionTwice() {
1739: Map<String, Object> vars = new HashMap<String, Object>();
1740: vars.put("foo", new Foo());
1741: vars.put("$value", new Long(5));
1742:
1743: ExpressionCompiler compiler = new ExpressionCompiler(
1744: "with (foo) { countTest = $value };");
1745: compiler.setDebugSymbols(true);
1746:
1747: ParserContext ctx = new ParserContext();
1748: ctx.setSourceFile("test.mv");
1749:
1750: CompiledExpression compiled = compiler.compile(ctx);
1751:
1752: MVEL.executeExpression(compiled, null, vars);
1753:
1754: MVEL.executeExpression(compiled, null, vars);
1755: }
1756:
1757: public void testComments() {
1758: assertEquals(10, test("// This is a comment\n5 + 5"));
1759: }
1760:
1761: public void testComments2() {
1762: assertEquals(20, test("10 + 10; // This is a comment"));
1763: }
1764:
1765: public void testComments3() {
1766: assertEquals(30, test("/* This is a test of\r\n"
1767: + "MVEL's support for\r\n" + "multi-line comments\r\n"
1768: + "*/\r\n 15 + 15"));
1769: }
1770:
1771: public void testComments4() {
1772: assertEquals(50, test("/** This is a fun test script **/\r\n"
1773: + "a = 10;\r\n" + "/**\r\n"
1774: + "* Here is a useful variable\r\n" + "*/\r\n"
1775: + "b = 20; // set b to '20'\r\n"
1776: + "return ((a + b) * 2) - 10;\r\n"
1777: + "// last comment\n"));
1778: }
1779:
1780: public void testSubtractNoSpace1() {
1781: assertEquals(59, test("hour-1"));
1782: }
1783:
1784: public void testStrictTypingCompilation() {
1785: ExpressionCompiler compiler = new ExpressionCompiler(
1786: "a.foo;\nb.foo;\n x = 5");
1787: ParserContext ctx = new ParserContext();
1788: ctx.setStrictTypeEnforcement(true);
1789:
1790: try {
1791: compiler.compile(ctx);
1792: } catch (CompileException e) {
1793: e.printStackTrace();
1794: assertEquals(2, e.getErrors().size());
1795: return;
1796: }
1797: assertTrue(false);
1798: }
1799:
1800: public void testStrictStaticMethodCall() {
1801: ExpressionCompiler compiler = new ExpressionCompiler(
1802: "Bar.staticMethod()");
1803: ParserContext ctx = new ParserContext();
1804: ctx.addImport("Bar", Bar.class);
1805: ctx.setStrictTypeEnforcement(true);
1806:
1807: Serializable s = compiler.compile(ctx);
1808:
1809: DebugTools.decompile(s);
1810:
1811: assertEquals(1, executeExpression(s));
1812: }
1813:
1814: public void testStrictTypingCompilation2() throws Exception {
1815: ParserContext ctx = new ParserContext();
1816: //noinspection RedundantArrayCreation
1817: ctx.addImport("getRuntime", new MethodStub(Runtime.class
1818: .getMethod("getRuntime", new Class[] {})));
1819:
1820: ctx.setStrictTypeEnforcement(true);
1821:
1822: ExpressionCompiler compiler = new ExpressionCompiler(
1823: "getRuntime()");
1824: StaticMethodImportResolverFactory si = new StaticMethodImportResolverFactory(
1825: ctx);
1826:
1827: Serializable expression = compiler.compile(ctx);
1828:
1829: serializationTest(expression);
1830:
1831: assertTrue(executeExpression(expression, si) instanceof Runtime);
1832: }
1833:
1834: public void testStrictTypingCompilation3()
1835: throws NoSuchMethodException {
1836: ParserContext ctx = new ParserContext();
1837:
1838: ctx.setStrictTypeEnforcement(true);
1839:
1840: ExpressionCompiler compiler = new ExpressionCompiler(
1841: "message='Hello';b=7;\nSystem.out.println(message + ';' + b);\n"
1842: + "System.out.println(message + ';' + b); b");
1843:
1844: assertEquals(7, executeExpression(compiler.compile(ctx),
1845: new DefaultLocalVariableResolverFactory()));
1846: }
1847:
1848: public void testStrictTypingCompilation4()
1849: throws NoSuchMethodException {
1850: ParserContext ctx = new ParserContext();
1851:
1852: ctx.addImport(Foo.class);
1853: ctx.setStrictTypeEnforcement(true);
1854:
1855: ExpressionCompiler compiler = new ExpressionCompiler(
1856: "x_a = new Foo()");
1857:
1858: compiler.compile(ctx);
1859:
1860: assertEquals(Foo.class, ctx.getVariables().get("x_a"));
1861: }
1862:
1863: public void testProvidedExternalTypes() {
1864: ExpressionCompiler compiler = new ExpressionCompiler("foo.bar");
1865: ParserContext ctx = new ParserContext();
1866: ctx.setStrictTypeEnforcement(true);
1867: ctx.addInput("foo", Foo.class);
1868:
1869: compiler.compile(ctx);
1870: }
1871:
1872: public void testEqualityRegression() {
1873: ExpressionCompiler compiler = new ExpressionCompiler(
1874: "price == (new Integer( 5 ) + 5 ) ");
1875: compiler.compile();
1876: }
1877:
1878: public void testEvaluationRegression() {
1879: ExpressionCompiler compiler = new ExpressionCompiler(
1880: "(p.age * 2)");
1881: compiler.compile();
1882: assertTrue(compiler.getParserContextState().getInputs()
1883: .containsKey("p"));
1884: }
1885:
1886: public void testAssignmentRegression() {
1887: ExpressionCompiler compiler = new ExpressionCompiler(
1888: "total = total + $cheese.price");
1889: compiler.compile();
1890: }
1891:
1892: public void testTypeRegression() {
1893: ExpressionCompiler compiler = new ExpressionCompiler(
1894: "total = 0");
1895: ParserContext ctx = new ParserContext();
1896: ctx.setStrictTypeEnforcement(true);
1897: compiler.compile(ctx);
1898: assertEquals(Integer.class, compiler.getParserContextState()
1899: .getVarOrInputType("total"));
1900: }
1901:
1902: public void testDateComparison() {
1903: // map.put("dt1", new Date(currentTimeMillis() - 100000));
1904: // map.put("dt2", new Date(currentTimeMillis()));
1905:
1906: assertTrue((Boolean) test("dt1 < dt2"));
1907: }
1908:
1909: public void testDynamicDeop() {
1910: Serializable s = MVEL.compileExpression("name");
1911:
1912: assertEquals("dog", MVEL.executeExpression(s, new Foo()));
1913: assertEquals("dog", MVEL.executeExpression(s, new Foo()
1914: .getBar()));
1915: }
1916:
1917: public void testVirtProperty() {
1918: Map<String, Object> testMap = new HashMap<String, Object>();
1919: testMap.put("test", "foo");
1920:
1921: Map<String, Object> vars = new HashMap<String, Object>();
1922: vars.put("mp", testMap);
1923:
1924: assertEquals("bar", MVEL.executeExpression(
1925: compileExpression("mp.test = 'bar'; mp.test"), vars));
1926: }
1927:
1928: public void testMapPropertyCreateCondensed() {
1929: assertEquals(
1930: "foo",
1931: test("map = new java.util.HashMap(); map['test'] = 'foo'; map['test'];"));
1932: }
1933:
1934: public void testClassLiteral() {
1935: assertEquals(String.class, test("java.lang.String"));
1936: }
1937:
1938: public void testDeepMethod() {
1939: assertEquals(
1940: false,
1941: test("foo.bar.testList.add(new String()); foo.bar.testList == empty"));
1942: }
1943:
1944: public void testArrayAccessorAssign() {
1945: assertEquals("foo",
1946: test("a = {'f00', 'bar'}; a[0] = 'foo'; a[0]"));
1947: }
1948:
1949: public void testListAccessorAssign() {
1950: assertEquals(
1951: "bar",
1952: test("a = new java.util.ArrayList(); a.add('foo'); a.add('BAR'); a[1] = 'bar'; a[1]"));
1953: }
1954:
1955: public void testBracketInString() {
1956: test("System.out.println('1)your guess was:');");
1957: }
1958:
1959: public void testNesting() {
1960: assertEquals("foo",
1961: test("new String(new String(new String(\"foo\")));"));
1962: }
1963:
1964: public void testDeepPropertyAdd() {
1965: assertEquals(10, test("foo.countTest+ 10"));
1966: }
1967:
1968: public void testDeepAssignmentIncrement() {
1969: assertEquals(
1970: true,
1971: test("foo.countTest += 5; if (foo.countTest == 5) { foo.countTest = 0; return true; } else { foo.countTest = 0; return false; }"));
1972: }
1973:
1974: public void testDeepAssignmentWithBlock() {
1975: assertEquals(
1976: true,
1977: test("with (foo) { countTest += 5 }; if (foo.countTest == 5) { foo.countTest = 0; return true; } else { foo.countTest = 0; return false; }"));
1978: }
1979:
1980: public void testTypeCast() {
1981: assertEquals("10", test("(String) 10"));
1982: }
1983:
1984: public void testMapAccessSemantics() {
1985: Map<String, Object> outermap = new HashMap<String, Object>();
1986: Map<String, Object> innermap = new HashMap<String, Object>();
1987:
1988: innermap.put("test", "foo");
1989: outermap.put("innermap", innermap);
1990:
1991: assertEquals("foo", testCompiledSimple("innermap['test']",
1992: outermap, null));
1993: }
1994:
1995: public void testMapBindingSemantics() {
1996: Map<String, Object> outermap = new HashMap<String, Object>();
1997: Map<String, Object> innermap = new HashMap<String, Object>();
1998:
1999: innermap.put("test", "foo");
2000: outermap.put("innermap", innermap);
2001:
2002: MVEL.setProperty(outermap, "innermap['test']", "bar");
2003:
2004: assertEquals("bar", testCompiledSimple("innermap['test']",
2005: outermap, null));
2006: }
2007:
2008: public void testSetSemantics() {
2009: Bar bar = new Bar();
2010: Foo foo = new Foo();
2011:
2012: assertEquals("dog", MVEL.getProperty("name", bar));
2013: assertEquals("dog", MVEL.getProperty("name", foo));
2014: }
2015:
2016: public void testMapBindingSemantics2() {
2017: Map<String, Object> outermap = new HashMap<String, Object>();
2018: Map<String, Object> innermap = new HashMap<String, Object>();
2019:
2020: innermap.put("test", "foo");
2021: outermap.put("innermap", innermap);
2022:
2023: Serializable s = MVEL.compileSetExpression("innermap['test']");
2024:
2025: MVEL.executeSetExpression(s, outermap, "bar");
2026:
2027: assertEquals("bar", testCompiledSimple("innermap['test']",
2028: outermap, null));
2029: }
2030:
2031: public void testDynamicImports() {
2032: ParserContext ctx = new ParserContext();
2033: ctx.addPackageImport("java.util");
2034:
2035: ExpressionCompiler compiler = new ExpressionCompiler("HashMap");
2036: Serializable s = compiler.compile(ctx);
2037:
2038: assertEquals(HashMap.class, MVEL.executeExpression(s));
2039:
2040: compiler = new ExpressionCompiler(
2041: "map = new HashMap(); map.size()");
2042: s = compiler.compile(ctx);
2043:
2044: assertEquals(0, MVEL.executeExpression(s,
2045: new DefaultLocalVariableResolverFactory()));
2046: }
2047:
2048: public void testDynamicImportsOnNestedExpressions() {
2049: ParserContext ctx = new ParserContext();
2050: ctx.addPackageImport("org.mvel.tests.main.res");
2051:
2052: ExpressionCompiler compiler = new ExpressionCompiler(
2053: "new Cheesery(\"bobbo\", new Cheese(\"cheddar\", 15))");
2054: Serializable s = compiler.compile(ctx);
2055:
2056: Cheesery p1 = new Cheesery("bobbo", new Cheese("cheddar", 15));
2057: Cheesery p2 = (Cheesery) MVEL.executeExpression(s,
2058: new DefaultLocalVariableResolverFactory());
2059:
2060: assertEquals(p1, p2);
2061: }
2062:
2063: public void testDynamicImportsWithNullConstructorParam() {
2064: ParserContext ctx = new ParserContext();
2065: ctx.addPackageImport("org.mvel.tests.main.res");
2066:
2067: ExpressionCompiler compiler = new ExpressionCompiler(
2068: "new Cheesery(\"bobbo\", null)");
2069: Serializable s = compiler.compile(ctx);
2070:
2071: Cheesery p1 = new Cheesery("bobbo", null);
2072:
2073: Cheesery p2 = (Cheesery) MVEL.executeExpression(s,
2074: new DefaultLocalVariableResolverFactory());
2075:
2076: assertEquals(p1, p2);
2077: }
2078:
2079: public void testDynamicImportsWithIdentifierSameAsClassWithDiffCase() {
2080: ParserContext ctx = new ParserContext();
2081: ctx.addPackageImport("org.mvel.tests.main.res");
2082: ctx.setStrictTypeEnforcement(false);
2083:
2084: ExpressionCompiler compiler = new ExpressionCompiler(
2085: "bar.add(\"hello\")");
2086: compiler.compile(ctx);
2087: }
2088:
2089: public void testTypedAssignment() {
2090: assertEquals(
2091: "foobar",
2092: test("java.util.Map map = new java.util.HashMap(); map.put('conan', 'foobar'); map['conan'];"));
2093: }
2094:
2095: public void testFQCNwithStaticInList() {
2096: assertEquals(Integer.MIN_VALUE,
2097: test("list = [java.lang.Integer.MIN_VALUE]; list[0]"));
2098: }
2099:
2100: public void testPrecedenceOrder() {
2101: assertTrue((Boolean) test("5 > 6 && 2 < 1 || 10 > 9"));
2102: }
2103:
2104: @SuppressWarnings({"unchecked"})
2105: public void testDifferentImplSameCompile() {
2106: Serializable compiled = compileExpression("a.funMap.hello");
2107:
2108: Map testMap = new HashMap();
2109:
2110: for (int i = 0; i < 100; i++) {
2111: Base b = new Base();
2112: b.funMap.put("hello", "dog");
2113: testMap.put("a", b);
2114:
2115: assertEquals("dog", executeExpression(compiled, testMap));
2116:
2117: b = new Base();
2118: b.funMap.put("hello", "cat");
2119: testMap.put("a", b);
2120:
2121: assertEquals("cat", executeExpression(compiled, testMap));
2122: }
2123: }
2124:
2125: @SuppressWarnings({"unchecked"})
2126: public void testInterfaceMethodCallWithSpace() {
2127: Serializable compiled = compileExpression("drools.retract (cheese)");
2128: Map map = new HashMap();
2129: DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper();
2130: map.put("drools", helper);
2131: Cheese cheese = new Cheese("stilton", 15);
2132: map.put("cheese", cheese);
2133:
2134: executeExpression(compiled, map);
2135: assertSame(cheese, helper.retracted.get(0));
2136: }
2137:
2138: @SuppressWarnings({"unchecked"})
2139: public void testInterfaceMethodCallWithMacro() {
2140: Map macros = new HashMap(1);
2141:
2142: macros.put("retract", new Macro() {
2143: public String doMacro() {
2144: return "drools.retract";
2145: }
2146: });
2147:
2148: Serializable compiled = compileExpression(parseMacros(
2149: "retract(cheese)", macros));
2150: Map map = new HashMap();
2151: DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper();
2152: map.put("drools", helper);
2153: Cheese cheese = new Cheese("stilton", 15);
2154: map.put("cheese", cheese);
2155:
2156: executeExpression(compiled, map);
2157: assertSame(cheese, helper.retracted.get(0));
2158: }
2159:
2160: @SuppressWarnings({"UnnecessaryBoxing"})
2161: public void testToList() {
2162: String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )";
2163:
2164: List list = (List) test(text);
2165:
2166: assertSame("dog", list.get(0));
2167: assertEquals("hello", list.get(1));
2168: assertEquals(new Integer(42), list.get(2));
2169: Map map = (Map) list.get(3);
2170: assertEquals("value1", map.get("key1"));
2171:
2172: List nestedList = (List) map.get("cat");
2173: assertEquals(14, nestedList.get(0));
2174: assertEquals("car", nestedList.get(1));
2175: assertEquals(42, nestedList.get(2));
2176:
2177: nestedList = (List) list.get(4);
2178: assertEquals(42, nestedList.get(0));
2179: map = (Map) nestedList.get(1);
2180: assertEquals("value1", map.get("cat"));
2181: }
2182:
2183: @SuppressWarnings({"UnnecessaryBoxing"})
2184: public void testToListStrictMode() {
2185: String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )";
2186:
2187: ParserContext ctx = new ParserContext();
2188: ctx.addInput("misc", MiscTestClass.class);
2189: ctx.addInput("foo", Foo.class);
2190: ctx.addInput("c", String.class);
2191:
2192: ctx.setStrictTypeEnforcement(true);
2193: ExpressionCompiler compiler = new ExpressionCompiler(text);
2194: Serializable expr = compiler.compile(ctx);
2195:
2196: List list = (List) executeExpression(expr, createTestMap());
2197:
2198: assertSame("dog", list.get(0));
2199: assertEquals("hello", list.get(1));
2200: assertEquals(new Integer(42), list.get(2));
2201: Map map = (Map) list.get(3);
2202: assertEquals("value1", map.get("key1"));
2203:
2204: List nestedList = (List) map.get("cat");
2205: assertEquals(14, nestedList.get(0));
2206: assertEquals("car", nestedList.get(1));
2207: assertEquals(42, nestedList.get(2));
2208:
2209: nestedList = (List) list.get(4);
2210: assertEquals(42, nestedList.get(0));
2211: map = (Map) nestedList.get(1);
2212: assertEquals("value1", map.get("cat"));
2213: }
2214:
2215: public void testParsingStability1() {
2216: assertEquals(
2217: true,
2218: test("( order.number == 1 || order.number == ( 1+1) || order.number == $id )"));
2219: }
2220:
2221: public void testParsingStability2() {
2222:
2223: ExpressionCompiler compiler = new ExpressionCompiler(
2224: "( dim.height == 1 || dim.height == ( 1+1) || dim.height == x )");
2225:
2226: Map<String, Object> imports = new HashMap<String, Object>();
2227: imports.put("java.awt.Dimension", Dimension.class);
2228:
2229: final ParserContext parserContext = new ParserContext(imports,
2230: null, "sourceFile");
2231:
2232: parserContext.setStrictTypeEnforcement(false);
2233:
2234: compiler.compile(parserContext);
2235:
2236: }
2237:
2238: public void testParsingStability3() {
2239: assertEquals(false, test("!( [\"X\", \"Y\"] contains \"Y\" )"));
2240: }
2241:
2242: public void testParsingStability4() {
2243: assertEquals(true, test("vv=\"Edson\"; !(vv ~= \"Mark\")"));
2244: }
2245:
2246: public void testConcatWithLineBreaks() {
2247: ExpressionCompiler parser = new ExpressionCompiler(
2248: "\"foo\"+\n\"bar\"");
2249:
2250: ParserContext ctx = new ParserContext();
2251: ctx.setDebugSymbols(true);
2252: ctx.setSourceFile("source.mv");
2253:
2254: Serializable c = parser.compile(ctx);
2255:
2256: assertEquals("foobar", MVEL.executeExpression(c));
2257: }
2258:
2259: /**
2260: * Community provided test cases
2261: */
2262: @SuppressWarnings({"unchecked"})
2263: public void testCalculateAge() {
2264: Calendar c1 = Calendar.getInstance();
2265: c1.set(1999, 0, 10); // 1999 jan 20
2266: Map objectMap = new HashMap(1);
2267: Map propertyMap = new HashMap(1);
2268: propertyMap.put("GEBDAT", c1.getTime());
2269: objectMap.put("EV_VI_ANT1", propertyMap);
2270: assertEquals(
2271: "N",
2272: testCompiledSimple(
2273: "new org.mvel.tests.main.res.PDFFieldUtil().calculateAge(EV_VI_ANT1.GEBDAT) >= 25 ? 'Y' : 'N'",
2274: null, objectMap));
2275: }
2276:
2277: /**
2278: * Provided by: Alex Roytman
2279: */
2280:
2281: public void testMethodResolutionWithNullParameter() {
2282: Context ctx = new Context();
2283: ctx.setBean(new Bean());
2284: Map<String, Object> vars = new HashMap<String, Object>();
2285: System.out.println("bean.today: "
2286: + eval("bean.today", ctx, vars));
2287: System.out.println("formatDate(bean.today): "
2288: + eval("formatDate(bean.today)", ctx, vars));
2289: //calling method with string param with null parameter works
2290: System.out.println("formatString(bean.nullString): "
2291: + eval("formatString(bean.nullString)", ctx, vars));
2292: System.out
2293: .println("bean.myDate = bean.nullDate: "
2294: + eval(
2295: "bean.myDate = bean.nullDate; return bean.nullDate;",
2296: ctx, vars));
2297: //calling method with Date param with null parameter fails
2298: System.out.println("formatDate(bean.myDate): "
2299: + eval("formatDate(bean.myDate)", ctx, vars));
2300: //same here
2301: System.out
2302: .println(eval("formatDate(bean.nullDate)", ctx, vars));
2303: }
2304:
2305: /**
2306: * Provided by: Phillipe Ombredanne
2307: */
2308: public void testCompileParserContextShouldNotLoopIndefinitelyOnValidJavaExpression() {
2309: String expr = " System.out.println( message );\n" + //
2310: "m.setMessage( \"Goodbye cruel world\" );\n" + //
2311: "System.out.println(m.getStatus());\n" + //
2312: "m.setStatus( Message.GOODBYE );\n";
2313:
2314: ExpressionCompiler compiler = new ExpressionCompiler(expr);
2315:
2316: ParserContext context = new ParserContext();
2317: context.setStrictTypeEnforcement(false);
2318:
2319: context.addImport("Message", Message.class);
2320: context.addInput("System", void.class);
2321: context.addInput("message", Object.class);
2322: context.addInput("m", Object.class);
2323:
2324: compiler.compile(context);
2325: }
2326:
2327: public void testStaticNested() {
2328: assertEquals(1, eval(
2329: "org.mvel.tests.main.AbstractTest$Message.GOODBYE",
2330: new HashMap()));
2331: }
2332:
2333: public void testStaticNestedWithImport() {
2334: String expr = "Message.GOODBYE;\n";
2335:
2336: ExpressionCompiler compiler = new ExpressionCompiler(expr);
2337:
2338: ParserContext context = new ParserContext();
2339: context.setStrictTypeEnforcement(false);
2340:
2341: context.addImport("Message", Message.class);
2342: Serializable compiledExpression = compiler.compile(context);
2343:
2344: assertEquals(1, MVEL.executeExpression(compiledExpression));
2345: }
2346:
2347: public void testStaticNestedWithMethodCall() {
2348: String expr = "item = new Item( \"Some Item\"); $msg.addItem( item ); return $msg";
2349:
2350: ExpressionCompiler compiler = new ExpressionCompiler(expr);
2351:
2352: ParserContext context = new ParserContext();
2353: context.setStrictTypeEnforcement(false);
2354:
2355: context.addImport("Message", Message.class);
2356: context.addImport("Item", Item.class);
2357: Serializable compiledExpression = compiler.compile(context);
2358:
2359: Map vars = new HashMap();
2360: vars.put("$msg", new Message());
2361: Message msg = (Message) MVEL.executeExpression(
2362: compiledExpression, vars);
2363: Item item = (Item) msg.getItems().get(0);
2364: assertEquals("Some Item", item.getName());
2365: }
2366:
2367: // public void testParserStringIssueNeverReturns() {
2368: // String expr = "Sstem.out.println(drools.workingMemory); ";
2369: //
2370: // ExpressionCompiler compiler = new ExpressionCompiler(expr);
2371: //
2372: // ParserContext context = new ParserContext();
2373: // context.setStrictTypeEnforcement(true);
2374: // context.addInput( "drools", KnowledgeHelper.class);
2375: //
2376: // RuleBase ruleBase = new RuleBaseImpl();
2377: // WorkingMemory wm = new WorkingMemoryImpl( ruleBase );
2378: // KnowledgeHelper drools = new DefaultKnowledgeHelper( wm );
2379: // Serializable compiledExpression = compiler.compile(context);
2380: //
2381: // Map vars = new HashMap();
2382: // vars.put( "drools", drools );
2383: // MVEL.executeExpression(compiledExpression, vars);
2384: // }
2385:
2386: public void testsequentialAccessorsThenMethodCall() {
2387: String expr = "System.out.println(drools.workingMemory); drools.workingMemory.ruleBase.removeRule(\"org.drools.examples\", \"some rule\"); ";
2388:
2389: ExpressionCompiler compiler = new ExpressionCompiler(expr);
2390:
2391: ParserContext context = new ParserContext();
2392: context.setStrictTypeEnforcement(true);
2393: context.addInput("drools", KnowledgeHelper.class);
2394:
2395: RuleBase ruleBase = new RuleBaseImpl();
2396: WorkingMemory wm = new WorkingMemoryImpl(ruleBase);
2397: KnowledgeHelper drools = new DefaultKnowledgeHelper(wm);
2398: Serializable compiledExpression = compiler.compile(context);
2399:
2400: Map vars = new HashMap();
2401: vars.put("drools", drools);
2402: MVEL.executeExpression(compiledExpression, vars);
2403: }
2404:
2405: /**
2406: * Provided by: Aadi Deshpande
2407: */
2408: public void testPropertyVerfierShoudldNotLoopIndefinately() {
2409: String expr = "\t\tmodel.latestHeadlines = $list;\n"
2410: + "model.latestHeadlines.add( 0, (model.latestHeadlines[2]) );";
2411:
2412: ExpressionCompiler compiler = new ExpressionCompiler(expr);
2413: compiler.setVerifying(true);
2414:
2415: ParserContext pCtx = new ParserContext();
2416: pCtx.addInput("$list", List.class);
2417: pCtx.addInput("model", Model.class);
2418:
2419: compiler.compile(pCtx);
2420: }
2421:
2422: public void testCompileWithNewInsideMethodCall() {
2423: String expr = " p.name = \"goober\";\n"
2424: + " System.out.println(p.name);\n"
2425: + " drools.insert(new Address(\"Latona\"));\n";
2426:
2427: ExpressionCompiler compiler = new ExpressionCompiler(expr);
2428:
2429: ParserContext context = new ParserContext();
2430: context.setStrictTypeEnforcement(false);
2431:
2432: context.addImport("Person", Person.class);
2433: context.addImport("Address", Address.class);
2434:
2435: context.addInput("p", Person.class);
2436: context.addInput("drools", Drools.class);
2437:
2438: compiler.compile(context);
2439: }
2440:
2441: /**
2442: * Submitted by: cleverpig
2443: */
2444:
2445: public void testBug4() {
2446: ClassA A = new ClassA();
2447: ClassB B = new ClassB();
2448: System.out.println(MVEL.getProperty("date", A));
2449: System.out.println(MVEL.getProperty("date", B));
2450: }
2451:
2452: /**
2453: * Submitted by: Michael Neale
2454: */
2455:
2456: public void testInlineCollectionParser1() {
2457: assertEquals(
2458: "q",
2459: ((Map) test("['Person.age' : [1, 2, 3, 4],'Person.rating' : 'q']"))
2460: .get("Person.rating"));
2461: assertEquals(
2462: "q",
2463: ((Map) test("['Person.age' : [1, 2, 3, 4], 'Person.rating' : 'q']"))
2464: .get("Person.rating"));
2465: }
2466:
2467: public void testIndexer() {
2468: assertEquals(
2469: "foobar",
2470: testCompiledSimple(
2471: "import java.util.LinkedHashMap; LinkedHashMap map = new LinkedHashMap();"
2472: + " map.put('a', 'foo'); map.put('b', 'bar'); s = ''; foreach (key : map.keySet()) { System.out.println(map[key]); s += map[key]; }; return s;",
2473: createTestMap()));
2474: }
2475:
2476: public void testLateResolveOfClass() {
2477: ExpressionCompiler compiler = new ExpressionCompiler(
2478: "System.out.println(new Foo());");
2479: ParserContext ctx = new ParserContext();
2480: ctx.addImport(Foo.class);
2481:
2482: CompiledExpression s = compiler.compile(ctx);
2483: compiler.removeParserContext();
2484:
2485: System.out.println(MVEL.executeExpression(s));
2486: }
2487:
2488: public void testClassAliasing() {
2489: assertEquals("foobar", test("Foo = String; new Foo('foobar')"));
2490: }
2491:
2492: public void testRandomExpression1() {
2493: assertEquals(
2494: "HelloWorld",
2495: test("if ((x15 = foo.bar) == foo.bar && x15 == foo.bar) { return 'HelloWorld'; } else { return 'GoodbyeWorld' } "));
2496: }
2497:
2498: public void testRandomExpression2() {
2499: assertEquals(
2500: 11,
2501: test("counterX = 0; foreach (item:{1,2,3,4,5,6,7,8,9,10}) { counterX++; }; return counterX + 1;"));
2502: }
2503:
2504: public void testRandomExpression3() {
2505: assertEquals(
2506: 0,
2507: test("counterX = 10; foreach (item:{1,1,1,1,1,1,1,1,1,1}) { counterX -= item; } return counterX;"));
2508: }
2509:
2510: public void testRandomExpression4() {
2511: assertEquals(
2512: true,
2513: test("result = org.mvel.MVEL.eval('10 * 3'); result == (10 * 3);"));
2514: }
2515:
2516: public void testRandomExpression5() {
2517: assertEquals(
2518: true,
2519: test("FooClassRef = foo.getClass(); fooInst = new FooClassRef(); name = org.mvel.MVEL.eval('name', fooInst); return name == 'dog'"));
2520: }
2521:
2522: public void testRandomExpression6() {
2523: assertEquals(
2524: 500,
2525: test("exprString = '250' + ' ' + '*' + ' ' + '2'; compiledExpr = org.mvel.MVEL.compileExpression(exprString);"
2526: + " return org.mvel.MVEL.executeExpression(compiledExpr);"));
2527: }
2528:
2529: public void testRandomExpression7() {
2530: assertEquals("FOOBAR", test("'foobar'.toUpperCase();"));
2531: }
2532:
2533: public void testRandomExpression8() {
2534: assertEquals(
2535: true,
2536: test("'someString'.intern(); 'someString'.hashCode() == 'someString'.hashCode();"));
2537: }
2538:
2539: public void testRandomExpression9() {
2540: assertEquals(
2541: false,
2542: test("_abc = 'someString'.hashCode(); _xyz = _abc + 1; _abc == _xyz"));
2543: }
2544:
2545: public void testRandomExpression10() {
2546: assertEquals(
2547: false,
2548: test("(_abc = (_xyz = 'someString'.hashCode()) + 1); _abc == _xyz"));
2549: }
2550:
2551: /**
2552: * Submitted by: Guerry Semones
2553: */
2554: private Map<Object, Object> outerMap;
2555: private Map<Object, Object> innerMap;
2556:
2557: public void testAddIntToMapWithMapSyntax() throws Throwable {
2558: outerMap = new HashMap<Object, Object>();
2559: innerMap = new HashMap<Object, Object>();
2560: outerMap.put("innerMap", innerMap);
2561:
2562: // fails because mvel checks for 'foo' in the outerMap,
2563: // rather than inside innerMap in outerMap
2564: PropertyAccessor.set(outerMap, "innerMap['foo']", 42);
2565:
2566: // mvel set it here
2567: // assertEquals(42, outerMap.get("foo"));
2568:
2569: // instead of here
2570: assertEquals(42, innerMap.get("foo"));
2571: }
2572:
2573: public void testUpdateIntInMapWithMapSyntax() throws Throwable {
2574:
2575: outerMap = new HashMap<Object, Object>();
2576: innerMap = new HashMap<Object, Object>();
2577: outerMap.put("innerMap", innerMap);
2578:
2579: // fails because mvel checks for 'foo' in the outerMap,
2580: // rather than inside innerMap in outerMap
2581: innerMap.put("foo", 21);
2582: PropertyAccessor.set(outerMap, "innerMap['foo']", 42);
2583:
2584: // instead of updating it here
2585: assertEquals(42, innerMap.get("foo"));
2586: }
2587:
2588: private HashMap<String, Object> context = new HashMap<String, Object>();
2589:
2590: public void before() {
2591: HashMap<String, Object> map = new HashMap<String, Object>();
2592:
2593: MyBean bean = new MyBean();
2594: bean.setVar(4);
2595:
2596: map.put("bean", bean);
2597: context.put("map", map);
2598: }
2599:
2600: public void testDeepProperty() {
2601:
2602: before();
2603: Serializable compiled = MVEL.compileExpression("map.bean.var");
2604:
2605: Object obj = MVEL.executeExpression(compiled, context);
2606: assertEquals(4, obj);
2607: }
2608:
2609: public void testDeepProperty2() {
2610: before();
2611:
2612: Serializable compiled = MVEL
2613: .compileExpression("map.bean.getVar()");
2614:
2615: Object obj = MVEL.executeExpression(compiled, context);
2616: assertEquals(4, obj);
2617: }
2618:
2619: public class MyBean {
2620: int var;
2621:
2622: public int getVar() {
2623: return var;
2624: }
2625:
2626: public void setVar(int var) {
2627: this .var = var;
2628: }
2629: }
2630:
2631: public static class TargetClass {
2632: private short _targetValue = 5;
2633:
2634: public short getTargetValue() {
2635: return _targetValue;
2636: }
2637: }
2638:
2639: public void testNestedMethodCall() {
2640: List elements = new ArrayList();
2641: elements.add(new TargetClass());
2642: Map variableMap = new HashMap();
2643: variableMap.put("elements", elements);
2644: eval(
2645: "results = new java.util.ArrayList(); foreach (element : elements) { if( {5} contains element.targetValue.intValue()) { results.add(element); } }; results",
2646: variableMap);
2647: }
2648:
2649: public void testBooleanEvaluation() {
2650: assertEquals(true, test("true||false||false"));
2651: }
2652:
2653: public void testBooleanEvaluation2() {
2654: assertEquals(true, test("equalityCheck(1,1)||fun||ackbar"));
2655: }
2656:
2657: /**
2658: * Submitted by: Dimitar Dimitrov
2659: */
2660: public void testFailing() {
2661: Map<String, Object> map = new HashMap<String, Object>();
2662: map.put("os", "windows");
2663: assertTrue((Boolean) eval("os ~= 'windows|unix'", map));
2664: }
2665:
2666: public void testSuccess() {
2667: Map<String, Object> map = new HashMap<String, Object>();
2668: map.put("os", "windows");
2669: assertTrue((Boolean) eval("'windows' ~= 'windows|unix'", map));
2670: assertFalse((Boolean) eval("time ~= 'windows|unix'",
2671: new java.util.Date()));
2672: }
2673:
2674: public void testBooleanStrAppend() {
2675: assertEquals("footrue", test("\"foo\" + true"));
2676: }
2677:
2678: public void testStringAppend() {
2679: assertEquals("catbar", test("c + 'bar'"));
2680: }
2681:
2682: public void testConvertableTo() {
2683: assertEquals(true, test("pi convertable_to Integer"));
2684: }
2685:
2686: public void testAssignPlus() {
2687: assertEquals(10, test("xx0 = 5; xx0 += 4; xx0 + 1"));
2688: }
2689:
2690: public void testAssignDiv() {
2691: assertEquals(2, test("xx0 = 20; xx0 /= 10; xx0"));
2692: }
2693:
2694: public void testAssignMult() {
2695: assertEquals(36, test("xx0 = 6; xx0 *= 6; xx0"));
2696: }
2697:
2698: public void testAssignSub() {
2699: assertEquals(11, test("xx0 = 15; xx0 -= 4; xx0"));
2700: }
2701:
2702: // public void testCommentsInWith() {
2703: // HashMap map = new HashMap();
2704: // map.put("f", new JFrame());
2705: // System.out.println(eval(
2706: // "with (f) {\n" +
2707: // "title = 'blah', // setting title\n" +
2708: // "alwaysOnTop = false \n" +
2709: // "}", map
2710: // ));
2711: // }
2712:
2713: public void testStaticWithExplicitParam() {
2714: PojoStatic pojo = new PojoStatic("10");
2715: eval("org.mvel.tests.main.res.AStatic.Process('10')", pojo,
2716: new HashMap());
2717: }
2718:
2719: public void testSimpleExpression() {
2720: PojoStatic pojo = new PojoStatic("10");
2721: eval("value!= null", pojo, new HashMap());
2722: }
2723:
2724: public void testStaticWithExpressionParam() {
2725: PojoStatic pojo = new PojoStatic("10");
2726: assertEquals(
2727: "java.lang.String",
2728: eval(
2729: "org.mvel.tests.main.res.AStatic.Process(value.getClass().getName().toString())",
2730: pojo));
2731: }
2732:
2733: public void testStringIndex() {
2734: assertEquals(true, test("a = 'foobar'; a[4] == 'a'"));
2735: }
2736:
2737: public void testArrayConstructionSupport1() {
2738: assertTrue(test("new String[5]") instanceof String[]);
2739: }
2740:
2741: public void testArrayConstructionSupport2() {
2742: assertTrue((Boolean) test("xStr = new String[5]; xStr.size() == 5"));
2743: }
2744:
2745: public void testArrayConstructionSupport3() {
2746: assertEquals(
2747: "foo",
2748: test("xStr = new String[5][5]; xStr[4][0] = 'foo'; xStr[4][0]"));
2749: }
2750:
2751: public void testArrayConstructionSupport4() {
2752: assertEquals(
2753: 10,
2754: test("xStr = new String[5][10]; xStr[4][0] = 'foo'; xStr[4].length"));
2755: }
2756:
2757: public void testNullSafe() {
2758: Foo foo = new Foo();
2759: foo.setBar(null);
2760:
2761: Map map = new HashMap();
2762: map.put("foo", foo);
2763:
2764: String expression = "foo.?bar.name == null";
2765: Serializable compiled = MVEL.compileExpression(expression);
2766:
2767: OptimizerFactory.setDefaultOptimizer("ASM");
2768: assertEquals(true, executeExpression(compiled, map));
2769: assertEquals(true, executeExpression(compiled, map)); // execute a second time (to search for optimizer problems)
2770:
2771: OptimizerFactory.setDefaultOptimizer("reflective");
2772: assertEquals(true, executeExpression(compiled, map));
2773: assertEquals(true, executeExpression(compiled, map)); // execute a second time (to search for optimizer problems)
2774:
2775: assertEquals(true, eval(expression, map));
2776: }
2777:
2778: /**
2779: * MVEL-57 (Submitted by: Rognvald Eaversen) -- Slightly modified by cbrock to include a positive testcase.
2780: */
2781: public void testMethodInvocationWithCollectionElement() {
2782: context = new HashMap();
2783: context.put("pojo", new POJO());
2784: context.put("number", "1192800637980");
2785:
2786: Object result = MVEL.eval("pojo.function(pojo.dates[0].time)",
2787: context);
2788: assertEquals(String.valueOf(((POJO) context.get("pojo"))
2789: .getDates().iterator().next().getTime()), result);
2790: }
2791:
2792: public void testNestedWithInList() {
2793: Recipient recipient1 = new Recipient();
2794: recipient1.setName("userName1");
2795: recipient1.setEmail("user1@domain.com");
2796:
2797: Recipient recipient2 = new Recipient();
2798: recipient2.setName("userName2");
2799: recipient2.setEmail("user2@domain.com");
2800:
2801: List list = new ArrayList();
2802: list.add(recipient1);
2803: list.add(recipient2);
2804:
2805: String text = "array = ["
2806: + "(with ( new Recipient() ) {name = 'userName1', email = 'user1@domain.com' }),"
2807: + "(with ( new Recipient() ) {name = 'userName2', email = 'user2@domain.com' })];\n";
2808:
2809: ParserContext context = new ParserContext();
2810: context.addImport(Recipient.class);
2811:
2812: ExpressionCompiler compiler = new ExpressionCompiler(text);
2813: Serializable execution = compiler.compile(context);
2814: List result = (List) MVEL.executeExpression(execution);
2815: assertEquals(list, result);
2816: }
2817:
2818: public void testNestedWithInMethod() {
2819: Recipient recipient1 = new Recipient();
2820: recipient1.setName("userName1");
2821: recipient1.setEmail("user1@domain.com");
2822:
2823: Recipients recipients = new Recipients();
2824: recipients.addRecipient(recipient1);
2825:
2826: String text = "recipients = new Recipients();\n"
2827: + "recipients.addRecipient( (with ( new Recipient() ) {name = 'userName1', email = 'user1@domain.com' }) );\n"
2828: + "return recipients;\n";
2829:
2830: ParserContext context;
2831: context = new ParserContext();
2832: context.addImport(Recipient.class);
2833: context.addImport(Recipients.class);
2834:
2835: ExpressionCompiler compiler = new ExpressionCompiler(text);
2836: Serializable execution = compiler.compile(context);
2837: Recipients result = (Recipients) MVEL
2838: .executeExpression(execution);
2839: assertEquals(recipients, result);
2840: }
2841:
2842: public void testNestedWithInComplexGraph() {
2843: Recipients recipients = new Recipients();
2844:
2845: Recipient recipient1 = new Recipient();
2846: recipient1.setName("user1");
2847: recipient1.setEmail("user1@domain.com");
2848: recipients.addRecipient(recipient1);
2849:
2850: Recipient recipient2 = new Recipient();
2851: recipient2.setName("user2");
2852: recipient2.setEmail("user2@domain.com");
2853: recipients.addRecipient(recipient2);
2854:
2855: EmailMessage msg = new EmailMessage();
2856: msg.setRecipients(recipients);
2857: msg.setFrom("from@domain.com");
2858:
2859: String text = "(with ( new EmailMessage() ) { recipients = (with (new Recipients()) { recipients = [(with ( new Recipient() ) {name = 'user1', email = 'user1@domain.com'}), (with ( new Recipient() ) {name = 'user2', email = 'user2@domain.com'}) ] }), "
2860: + " from = 'from@domain.com' } )";
2861: ParserContext context;
2862: context = new ParserContext();
2863: context.addImport(Recipient.class);
2864: context.addImport(Recipients.class);
2865: context.addImport(EmailMessage.class);
2866:
2867: ExpressionCompiler compiler = new ExpressionCompiler(text);
2868: Serializable execution = compiler.compile(context);
2869: EmailMessage result = (EmailMessage) MVEL
2870: .executeExpression(execution);
2871: assertEquals(msg, result);
2872:
2873: }
2874:
2875: public static class Recipient {
2876: private String name;
2877: private String email;
2878:
2879: public String getName() {
2880: return name;
2881: }
2882:
2883: public void setName(String name) {
2884: this .name = name;
2885: }
2886:
2887: public String getEmail() {
2888: return email;
2889: }
2890:
2891: public void setEmail(String email) {
2892: this .email = email;
2893: }
2894:
2895: @Override
2896: public int hashCode() {
2897: final int prime = 31;
2898: int result = 1;
2899: result = prime * result
2900: + ((email == null) ? 0 : email.hashCode());
2901: result = prime * result
2902: + ((name == null) ? 0 : name.hashCode());
2903: return result;
2904: }
2905:
2906: @Override
2907: public boolean equals(Object obj) {
2908: if (this == obj)
2909: return true;
2910: if (obj == null)
2911: return false;
2912: if (getClass() != obj.getClass())
2913: return false;
2914: final Recipient other = (Recipient) obj;
2915: if (email == null) {
2916: if (other.email != null)
2917: return false;
2918: } else if (!email.equals(other.email))
2919: return false;
2920: if (name == null) {
2921: if (other.name != null)
2922: return false;
2923: } else if (!name.equals(other.name))
2924: return false;
2925: return true;
2926: }
2927:
2928: }
2929:
2930: public static class Recipients {
2931: private List<Recipient> list = Collections.EMPTY_LIST;
2932:
2933: public void setRecipients(List<Recipient> recipients) {
2934: this .list = recipients;
2935: }
2936:
2937: public boolean addRecipient(Recipient recipient) {
2938: if (list == Collections.EMPTY_LIST) {
2939: this .list = new ArrayList<Recipient>();
2940: }
2941:
2942: if (!this .list.contains(recipient)) {
2943: this .list.add(recipient);
2944: return true;
2945: }
2946: return false;
2947: }
2948:
2949: public boolean removeRecipient(Recipient recipient) {
2950: return this .list.remove(recipient);
2951: }
2952:
2953: public List<Recipient> getRecipients() {
2954: return this .list;
2955: }
2956:
2957: public Recipient[] toArray() {
2958: return list.toArray(new Recipient[list.size()]);
2959: }
2960:
2961: @Override
2962: public int hashCode() {
2963: final int prime = 31;
2964: int result = 1;
2965: result = prime * result
2966: + ((list == null) ? 0 : list.hashCode());
2967: return result;
2968: }
2969:
2970: @Override
2971: public boolean equals(Object obj) {
2972: if (this == obj)
2973: return true;
2974: if (obj == null)
2975: return false;
2976: if (getClass() != obj.getClass())
2977: return false;
2978: final Recipients other = (Recipients) obj;
2979: if (list == null) {
2980: if (other.list != null)
2981: return false;
2982: } else if (!list.equals(other.list))
2983: return false;
2984: return true;
2985: }
2986:
2987: }
2988:
2989: public static class EmailMessage {
2990: private Recipients recipients;
2991: private String from;
2992:
2993: public EmailMessage() {
2994:
2995: }
2996:
2997: public Recipients getRecipients() {
2998: return recipients;
2999: }
3000:
3001: public void setRecipients(Recipients recipients) {
3002: this .recipients = recipients;
3003: }
3004:
3005: public String getFrom() {
3006: return from;
3007: }
3008:
3009: public void setFrom(String from) {
3010: this .from = from;
3011: }
3012:
3013: @Override
3014: public int hashCode() {
3015: final int prime = 31;
3016: int result = 1;
3017: result = prime * result
3018: + ((from == null) ? 0 : from.hashCode());
3019: result = prime
3020: * result
3021: + ((recipients == null) ? 0 : recipients.hashCode());
3022: return result;
3023: }
3024:
3025: @Override
3026: public boolean equals(Object obj) {
3027:
3028: if (this == obj)
3029: return true;
3030: if (obj == null)
3031: return false;
3032: if (getClass() != obj.getClass())
3033: return false;
3034: final EmailMessage other = (EmailMessage) obj;
3035: if (from == null) {
3036: if (other.from != null)
3037: return false;
3038: } else if (!from.equals(other.from))
3039: return false;
3040: if (recipients == null) {
3041: if (other.recipients != null)
3042: return false;
3043: } else if (!recipients.equals(other.recipients))
3044: return false;
3045: return true;
3046: }
3047:
3048: }
3049:
3050: public class POJO {
3051: private Set<Date> dates = new HashSet<Date>();
3052:
3053: public POJO() {
3054: dates.add(new Date());
3055: }
3056:
3057: public Set<Date> getDates() {
3058: return dates;
3059: }
3060:
3061: public void setDates(Set<Date> dates) {
3062: this .dates = dates;
3063: }
3064:
3065: public String function(long num) {
3066: return String.valueOf(num);
3067: }
3068: }
3069:
3070: public void testSubEvaluation() {
3071: HashMap<String, Object> map = new HashMap<String, Object>();
3072: map.put("EV_BER_BER_NR", "12345");
3073: map.put("EV_BER_BER_PRIV", Boolean.FALSE);
3074:
3075: assertEquals(
3076: "12345",
3077: testCompiledSimple(
3078: "EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')",
3079: null, map));
3080:
3081: map.put("EV_BER_BER_PRIV", Boolean.TRUE);
3082: assertEquals(
3083: "12345/PRIVAT",
3084: testCompiledSimple(
3085: "EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')",
3086: null, map));
3087: }
3088:
3089: public void testNestedMethod1() {
3090: Vector vectorA = new Vector();
3091: Vector vectorB = new Vector();
3092:
3093: vectorA.add("Foo");
3094:
3095: Map map = new HashMap();
3096: map.put("vecA", vectorA);
3097: map.put("vecB", vectorB);
3098:
3099: testCompiledSimple(
3100: "vecB.add(vecA.remove(0)); vecA.add('Foo');", null, map);
3101:
3102: assertEquals("Foo", vectorB.get(0));
3103: }
3104:
3105: public void testNegativeArraySizeBug() throws Exception {
3106: String expressionString1 = "results = new java.util.ArrayList(); foreach (element : elements) { if( ( {30, 214, 158, 31, 95, 223, 213, 86, 159, 34, 32, 96, 224, 160, 85, 201, 29, 157, 100, 146, 82, 203, 194, 145, 140, 81, 27, 166, 212, 38, 28, 94, 168, 23, 87, 150, 35, 149, 193, 33, 132, 206, 93, 196, 24, 88, 195, 36, 26, 154, 167, 108, 204, 74, 46, 25, 153, 202, 79, 207, 143, 43, 16, 80, 198, 208, 144, 41, 97, 142, 83, 18, 162, 103, 155, 98, 44, 17, 205, 77, 156, 141, 165, 102, 84, 37, 101, 222, 40, 104, 99, 177, 182, 22, 180, 21, 137, 221, 179, 78, 42, 178, 19, 183, 139, 218, 219, 39, 220, 20, 184, 217, 138, 62, 190, 171, 123, 113, 59, 118, 225, 124, 169, 60, 117, 1} contains element.attribute ) ) { results.add(element); } }; results";
3107: String expressionString2 = "results = new java.util.ArrayList(); foreach (element : elements) { if( ( {30, 214, 158, 31, 95, 223, 213, 86, 159, 34, 32, 96, 224, 160, 85, 201, 29, 157, 100, 146, 82, 203, 194, 145, 140, 81, 27, 166, 212, 38, 28, 94, 168, 23, 87, 150, 35, 149, 193, 33, 132, 206, 93, 196, 24, 88, 195, 36, 26, 154, 167, 108, 204, 74, 46, 25, 153, 202, 79, 207, 143, 43, 16, 80, 198, 208, 144, 41, 97, 142, 83, 18, 162, 103, 155, 98, 44, 17, 205, 77, 156, 141, 165, 102, 84, 37, 101, 222, 40, 104, 99, 177, 182, 22, 180, 21, 137, 221, 179, 78, 42, 178, 19, 183, 139, 218, 219, 39, 220, 20, 184, 217, 138, 62, 190, 171, 123, 113, 59, 118, 225, 124, 169, 60, 117, 1, 61, 189, 122, 68, 58, 119, 63, 226, 3, 172} contains element.attribute ) ) { results.add(element); } }; results";
3108:
3109: List<Target> targets = new ArrayList<Target>();
3110: targets.add(new Target(1));
3111: targets.add(new Target(999));
3112:
3113: Map vars = new HashMap();
3114: vars.put("elements", targets);
3115:
3116: assertEquals(1, ((List) testCompiledSimple(expressionString1,
3117: null, vars)).size());
3118: assertEquals(1, ((List) testCompiledSimple(expressionString2,
3119: null, vars)).size());
3120: }
3121:
3122: public static final class Target {
3123: private int _attribute;
3124:
3125: public Target(int attribute_) {
3126: _attribute = attribute_;
3127: }
3128:
3129: public int getAttribute() {
3130: return _attribute;
3131: }
3132: }
3133:
3134: public void testFunctionDefAndCall() {
3135: assertEquals("FoobarFoobar",
3136: test("function heyFoo() { return 'Foobar'; };\n"
3137: + "return heyFoo() + heyFoo();"));
3138: }
3139:
3140: public void testFunctionDefAndCall2() {
3141: ExpressionCompiler compiler = new ExpressionCompiler(
3142: "function heyFoo() { return 'Foobar'; };\n"
3143: + "return heyFoo() + heyFoo();");
3144:
3145: Serializable s = compiler.compile();
3146:
3147: Map<String, Function> m = CompilerTools
3148: .extractAllDeclaredFunctions((CompiledExpression) s);
3149:
3150: assertTrue(m.containsKey("heyFoo"));
3151:
3152: OptimizerFactory.setDefaultOptimizer("reflective");
3153:
3154: assertEquals("FoobarFoobar", MVEL.executeExpression(s,
3155: new HashMap()));
3156: assertEquals("FoobarFoobar", MVEL.executeExpression(s,
3157: new HashMap()));
3158: }
3159:
3160: public void testFunctionDefAndCall3() {
3161: assertEquals(
3162: "FOOBAR",
3163: test("function testFunction() { a = 'foo'; b = 'bar'; a + b; }; testFunction().toUpperCase(); "));
3164: }
3165:
3166: public void testFunctionDefAndCall4() {
3167: assertEquals(
3168: "barfoo",
3169: test("function testFunction(input) { return input; }; testFunction('barfoo');"));
3170: }
3171:
3172: public void testFunctionDefAndCall5() {
3173: assertEquals(
3174: 10,
3175: test("function testFunction(x, y) { return x + y; }; testFunction(7, 3);"));
3176: }
3177:
3178: public void testDynamicImports2() {
3179: assertEquals(BufferedReader.class,
3180: test("import java.io.*; BufferedReader"));
3181: }
3182:
3183: public void testStringWithTernaryIf() {
3184: test("System.out.print(\"Hello : \" + (foo != null ? \"FOO!\" : \"NO FOO\") + \". Bye.\");");
3185: }
3186:
3187: public void testFunctionsScript1() throws IOException {
3188: MVEL.evalFile(new File("samples/scripts/functions1.mvel"));
3189: }
3190:
3191: public void testQuickSortScript1() throws IOException {
3192: MVEL.evalFile(new File("samples/scripts/quicksort.mvel"));
3193: }
3194:
3195: public void testQuickSortScript2() throws IOException {
3196: Object[] sorted = (Object[]) test(new String(
3197: loadFromFile(new File("samples/scripts/quicksort.mvel"))));
3198: int last = -1;
3199: for (Object o : sorted) {
3200: if (last == -1) {
3201: last = (Integer) o;
3202: } else {
3203: assertTrue(((Integer) o) > last);
3204: last = (Integer) o;
3205: }
3206: }
3207: }
3208:
3209: public void testCompactIfElse() {
3210: assertEquals("foo", test("if (false) 'bar'; else 'foo';"));
3211: }
3212:
3213: public void testAndOpLiteral() {
3214: assertEquals(true, test("true && true"));
3215: }
3216:
3217: public void testAnonymousFunctionDecl() {
3218: assertEquals(
3219: 3,
3220: test("anonFunc = function (a,b) { return a + b; }; anonFunc(1,2)"));
3221: }
3222:
3223: public void testFunctionSemantics() {
3224: assertEquals(
3225: true,
3226: test("function fooFunction(a) { return a; }; x__0 = ''; 'boob' == fooFunction(x__0 = 'boob') && x__0 == 'boob';"));
3227: }
3228:
3229: public void testUseOfVarKeyword() {
3230: assertEquals("FOO_BAR",
3231: test("var barfoo = 'FOO_BAR'; return barfoo;"));
3232: }
3233:
3234: public void testSetExpressions1() {
3235: Map<String, Object> myMap = new HashMap<String, Object>();
3236:
3237: final Serializable fooExpr = MVEL.compileSetExpression("foo");
3238: MVEL.executeSetExpression(fooExpr, myMap, "blah");
3239: assertEquals("blah", myMap.get("foo"));
3240:
3241: MVEL.executeSetExpression(fooExpr, myMap, "baz");
3242: assertEquals("baz", myMap.get("foo"));
3243:
3244: }
3245:
3246: public void testInlineCollectionNestedObjectCreation() {
3247: Map m = (Map) test("['Person.age' : [1, 2, 3, 4], 'Person.rating' : ['High', 'Low'],"
3248: + " 'Person.something' : (new String('foo').toUpperCase())]");
3249:
3250: assertEquals("FOO", m.get("Person.something"));
3251: }
3252:
3253: public void testInlineCollectionNestedObjectCreation1() {
3254: Map m = (Map) test("[new String('foo') : new String('bar')]");
3255:
3256: assertEquals("bar", m.get("foo"));
3257: }
3258:
3259: public void testEgressType() {
3260: ExpressionCompiler compiler = new ExpressionCompiler(
3261: "( $cheese )");
3262: ParserContext context = new ParserContext();
3263: context.addInput("$cheese", Cheese.class);
3264:
3265: ExecutableStatement expr = compiler.compile(context);
3266:
3267: assertEquals(Cheese.class, expr.getKnownEgressType());
3268: }
3269:
3270: public void testDuplicateVariableDeclaration() {
3271: ExpressionCompiler compiler = new ExpressionCompiler(
3272: "String x = \"abc\"; Integer x = new Integer( 10 );");
3273: ParserContext context = new ParserContext();
3274:
3275: try {
3276: compiler.compile(context);
3277: fail("Compilation must fail with duplicate variable declaration exception.");
3278: } catch (CompileException ce) {
3279: // success
3280: }
3281: }
3282:
3283: public void testFullyQualifiedTypeAndCast() {
3284: assertEquals(
3285: 1,
3286: test("java.lang.Integer number = (java.lang.Integer) '1';"));
3287: }
3288:
3289: public void testAnonymousFunction() {
3290: assertEquals("foobar", test("a = function { 'foobar' }; a();"));
3291: }
3292:
3293: public void testThreadSafetyInterpreter1() {
3294:
3295: //First evaluation
3296: System.out.println("First evaluation: " + MVEL.eval("true"));
3297:
3298: new Thread(new Runnable() {
3299: public void run() {
3300: // Second evaluation - this succeeds only if the first evaluation is not commented out
3301: System.out.println("Second evaluation: "
3302: + MVEL.eval("true"));
3303: }
3304: }).start();
3305: }
3306:
3307: }
|