mvel-2.0.18.orig/0000755000175000017500000000000011412747055013406 5ustar drazzibdrazzibmvel-2.0.18.orig/META-INF/0000755000175000017500000000000011412747012014537 5ustar drazzibdrazzibmvel-2.0.18.orig/META-INF/MANIFEST.MF0000644000175000017500000001140711372027604016177 0ustar drazzibdrazzibManifest-Version: 1.0 Export-Package: org.mvel2;uses:="org.mvel2.util,org.mvel2.conversion,o rg.mvel2.integration.impl,org.mvel2.optimizers.impl.refl.nodes,org.mv el2.integration,org.mvel2.compiler,org.mvel2.ast,org.mvel2.debug";ver sion="2.0.18",org.mvel2.asm;version="2.0.18",org.mvel2.asm.signature; version="2.0.18",org.mvel2.asm.util;uses:="org.mvel2.asm,org.mvel2.as m.signature";version="2.0.18",org.mvel2.ast;uses:="org.mvel2.integrat ion,org.mvel2.optimizers,org.mvel2,org.mvel2.debug,org.mvel2.compiler ,org.mvel2.util,org.mvel2.math,org.mvel2.integration.impl";version="2 .0.18",org.mvel2.compiler;uses:="org.mvel2.integration,org.mvel2,org. mvel2.util,org.mvel2.ast,org.mvel2.optimizers,org.mvel2.integration.i mpl,org.mvel2.optimizers.impl.refl.nodes";version="2.0.18",org.mvel2. conversion;uses:="org.mvel2,org.mvel2.util,org.mvel2.compiler";versio n="2.0.18",org.mvel2.debug;uses:="org.mvel2.integration,org.mvel2.uti l,org.mvel2.ast,org.mvel2.compiler,org.mvel2";version="2.0.18",org.mv el2.integration;uses:="org.mvel2.ast";version="2.0.18",org.mvel2.inte gration.impl;uses:="org.mvel2.integration,org.mvel2,org.mvel2.ast,org .mvel2.util";version="2.0.18",org.mvel2.math;uses:="org.mvel2,org.mve l2.debug,org.mvel2.util";version="2.0.18",org.mvel2.optimizers;uses:= "org.mvel2,org.mvel2.util,org.mvel2.compiler,org.mvel2.integration,or g.mvel2.optimizers.dynamic,org.mvel2.optimizers.impl.asm,org.mvel2.op timizers.impl.refl";version="2.0.18",org.mvel2.optimizers.dynamic;use s:="org.mvel2.compiler,org.mvel2.util,org.mvel2.integration,org.mvel2 .optimizers,org.mvel2,org.mvel2.optimizers.impl.asm";version="2.0.18" ,org.mvel2.optimizers.impl.asm;uses:="org.mvel2.integration,org.mvel2 .optimizers.impl.refl.nodes,org.mvel2.util,org.mvel2.asm,org.mvel2.op timizers,org.mvel2,org.mvel2.compiler,org.mvel2.ast";version="2.0.18" ,org.mvel2.optimizers.impl.refl;uses:="org.mvel2.optimizers.impl.refl .nodes,org.mvel2.integration,org.mvel2.util,org.mvel2.optimizers.impl .refl.collection,org.mvel2.optimizers,org.mvel2,org.mvel2.compiler,or g.mvel2.ast";version="2.0.18",org.mvel2.optimizers.impl.refl.collecti on;uses:="org.mvel2.integration,org.mvel2.compiler,org.mvel2,org.mvel 2.util";version="2.0.18",org.mvel2.optimizers.impl.refl.nodes;uses:=" org.mvel2.integration,org.mvel2.compiler,org.mvel2,org.mvel2.util,org .mvel2.ast,org.mvel2.optimizers";version="2.0.18",org.mvel2.sh;uses:= "org.mvel2,org.mvel2.templates,org.mvel2.integration.impl,org.mvel2.i ntegration,org.mvel2.util,org.mvel2.sh.command.basic,org.mvel2.sh.com mand.file";version="2.0.18",org.mvel2.sh.command.basic;uses:="org.mve l2.sh,org.mvel2.sh.text,org.mvel2.util,org.mvel2";version="2.0.18",or g.mvel2.sh.command.file;uses:="org.mvel2.sh";version="2.0.18",org.mve l2.sh.text;uses:="org.mvel2.util";version="2.0.18",org.mvel2.template s;uses:="org.mvel2.templates.res,org.mvel2.templates.util,org.mvel2,o rg.mvel2.util,org.mvel2.integration.impl,org.mvel2.integration,org.mv el2.templates.util.io";version="2.0.18",org.mvel2.templates.res;uses: ="org.mvel2.templates,org.mvel2.integration,org.mvel2.templates.util, org.mvel2,org.mvel2.util,org.mvel2.integration.impl";version="2.0.18" ,org.mvel2.templates.util;uses:="org.mvel2.templates.res,org.mvel2.te mplates,org.mvel2.util";version="2.0.18",org.mvel2.templates.util.io; uses:="org.mvel2.templates.util,org.mvel2.util";version="2.0.18",org. mvel2.util;uses:="org.mvel2.ast,org.mvel2.integration,org.mvel2,org.m vel2.compiler,org.mvel2.integration.impl,org.mvel2.math,sun.misc";ver sion="2.0.18" Bundle-Version: 2.0.18 Tool: Bnd-0.0.357 Bundle-Name: mvel2 Bnd-LastModified: 1273507710974 Created-By: 1.6.0_17 (Apple Inc.) Bundle-ManifestVersion: 2 Bundle-SymbolicName: org.mvel2 Import-Package: org.mvel2;version="2.0",org.mvel2.asm;version="2.0",or g.mvel2.asm.signature;version="2.0",org.mvel2.asm.util;version="2.0", org.mvel2.ast;version="2.0",org.mvel2.compiler;version="2.0",org.mvel 2.conversion;version="2.0",org.mvel2.debug;version="2.0",org.mvel2.in tegration;version="2.0",org.mvel2.integration.impl;version="2.0",org. mvel2.math;version="2.0",org.mvel2.optimizers;version="2.0",org.mvel2 .optimizers.dynamic;version="2.0",org.mvel2.optimizers.impl.asm;versi on="2.0",org.mvel2.optimizers.impl.refl;version="2.0",org.mvel2.optim izers.impl.refl.collection;version="2.0",org.mvel2.optimizers.impl.re fl.nodes;version="2.0",org.mvel2.sh;version="2.0",org.mvel2.sh.comman d.basic;version="2.0",org.mvel2.sh.command.file;version="2.0",org.mve l2.sh.text;version="2.0",org.mvel2.templates;version="2.0",org.mvel2. templates.res;version="2.0",org.mvel2.templates.util;version="2.0",or g.mvel2.templates.util.io;version="2.0",org.mvel2.util;version="2.0", sun.misc;resolution:=optional mvel-2.0.18.orig/samples/0000755000175000017500000000000011412747012015043 5ustar drazzibdrazzibmvel-2.0.18.orig/samples/scripts/0000755000175000017500000000000011412747013016533 5ustar drazzibdrazzibmvel-2.0.18.orig/samples/scripts/multilinestring.mvel0000644000175000017500000000015011030011257022633 0ustar drazzibdrazzib System.out.println( "Hello, are you there? Is it wonderful? Did you try to escape the population?" ); mvel-2.0.18.orig/samples/scripts/quicksort.mvel0000644000175000017500000000133111162250032021432 0ustar drazzibdrazzib/** * Sample MVEL 2.0 Script * "QuickSort" * by: Christopher Michael Brock */ array = null; def swap(i, j) { temp = array[i]; array[i] = array[j]; array[j] = temp; } def partition(low, high) { pivotPoint = array[low]; i = low - 1; j = high + 1; while (i < j) { i++; while (array[i] < pivotPoint) ++i; j--; while (array[j] > pivotPoint) --j; if (i < j) swap(i, j); } j; //return j } def sort(low, high) { if (low < high) { var p; sort(low, p = partition(low, high)); sort(p + 1, high); } } def quicksort() { sort(0, array.length - 1); } array = {99,20,21,209,10,77,8,9,55,73,41,50}; quicksort(); array; // return arraymvel-2.0.18.orig/samples/scripts/randomguess.mvel0000644000175000017500000000135310723643743021762 0ustar drazzibdrazzib/** * Sample MVEL 2.0 Script * "Random Guess" * by: Christopher Michael Brock */ import java.io.*; // // Seed the random number // $num = (int) Math.random() * 100; $guesses = 0; $in = -1; // // Setup the STDIN line reader. // $linereader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("I'm Thinking of a Number Between 1 and 100... Can you guess what it is? "); // // Main program loop // while ($in != $num) { if ($in != -1) { System.out.print("Nope. The number is: " + ($num < $in ? "Lower" : "Higher") + ". What's your next guess? "); } if (($in = $linereader.readLine().trim()) == empty) $in = -2; $guesses++; } System.out.println("You got it! It took you " + $guesses + " tries"); mvel-2.0.18.orig/samples/scripts/quicksort2.mvel0000644000175000017500000000134411057433533021534 0ustar drazzibdrazzib/** * Sample MVEL 2.0 Script * "QuickSort" * by: Christopher Michael Brock */ array = null; def swap(i, j) { temp = array[i]; array[i] = array[j]; array[j] = temp; } def partition(low, high) { pivotPoint = array[low]; i = low - 1; j = high + 1; while (i < j) { i += 1; while (array[i] < pivotPoint) i += 1; j -= 1; while (array[j] > pivotPoint) j -= 1; if (i < j) swap(i, j); } j; //return j } def sort(low, high) { if (low < high) { var p; sort(low, p = partition(low, high)); sort(p + 1, high); } } def quicksort() { sort(0, array.length - 1); } array = {50,20,21,209,10,77,8,9,55,73,41,99}; quicksort(); array; // return arraymvel-2.0.18.orig/samples/scripts/functions1.mvel0000644000175000017500000000053411025275200021505 0ustar drazzibdrazzib/** * Sample MVEL 2.0 Script * "Functions Demonstration" * by: Christopher Michael Brock */ def isGood(obj) { return !(obj.toLowerCase() contains "evil"); } def describe(obj) { System.out.println(obj + " is " + (isGood(obj) ? "Good" : "Evil")); } $test1 = "Mr. Good"; $test2 = "Mr. Evil"; describe($test1); describe($test2);mvel-2.0.18.orig/samples/scripts/multibyte.mvel0000644000175000017500000000001411134146135021430 0ustar drazzibdrazziba = "?????";mvel-2.0.18.orig/samples/scripts/quicksort3.mvel0000644000175000017500000000134011155433536021533 0ustar drazzibdrazzib/** * Sample MVEL 2.0 Script * "QuickSort" * by: Christopher Michael Brock */ array = null; def swap(i, j) { temp = array[i]; array[i] = array[j]; array[j] = temp; } def partition(low, high) { int pivotPoint = array[low], i = low - 1, j = high + 1; while (i < j) { i += 1; while (array[i] < pivotPoint) i += 1; j -= 1; while (array[j] > pivotPoint) j -= 1; if (i < j) swap(i, j); } j; //return j } def sort(low, high) { if (low < high) { var p; sort(low, p = partition(low, high)); sort(p + 1, high); } } def quicksort() { sort(0, array.length - 1); } array = {50,20,21,209,10,77,8,9,55,73,41,99}; quicksort(); array; // return arraymvel-2.0.18.orig/samples/scripts/fquicksort.mvel0000644000175000017500000000123211164070104021602 0ustar drazzibdrazzib/** * Sample MVEL 2.0 Script * "Functional QuickSort" * by: Christopher Michael Brock, Inspired by: Dhanji Prasanna */ import java.util.*; // the main quicksort algorithm def quicksort(list) { if (list.size() <= 1) { list; } else { pivot = list[0]; concat(quicksort(($ in list if $ < pivot)), pivot, quicksort(($ in list if $ > pivot))); } } // define method to concatenate lists. def concat(list1, pivot, list2) { concatList = new ArrayList(list1); concatList.add(pivot); concatList.addAll(list2); concatList; } // create a list to sort list = [5,2,4,1,18,10,15,1,0]; // sort it! quicksort(list);mvel-2.0.18.orig/pom.xml0000644000175000017500000001627611372027604014733 0ustar drazzibdrazzib 4.0.0 org.mvel mvel2 jar 2.0.18 mvel http://mvel.codehaus.org/ scm:svn:https://svn.codehaus.org/mvel/tags/mvel2-2.0.18 apache-snapshots Apache Snapshot Repository http://repository.apache.org/snapshots/ true org.apache.maven.wagon wagon-webdav 1.0-beta-2 org.apache.maven.plugins maven-compiler-plugin 2.0.1 1.5 1.5 UTF-8 org.apache.maven.plugins maven-jar-plugin org.mvel2.sh.Main org.mvel2 org.apache.maven.plugins maven-surefire-plugin true mvel.disable.jit true file.encoding UTF-8 **/*Test.java **/*Tests.java **/UsageDemos.java **/CompiledUnitTestEx.java **/PerfTest.java **/DroolsTest.java **/FailureTests.java **/PerformanceTest.java **/CompiledPerformanceTests.java **/MVELThreadTest.java org.apache.maven.plugins maven-release-plugin 2.0-beta-9 https://svn.codehaus.org/mvel/tags/ false clean install true maven-jar-plugin META-INF/MANIFEST.MF org.apache.felix maven-bundle-plugin 2.0.1 true manifest process-classes manifest META-INF org.mvel2 mvel2 sun.*;resolution:=optional, * . build.properties org.apache.maven.plugins maven-surefire-report-plugin junit junit 3.8.1 test com.thoughtworks.xstream xstream 1.3.1 test codehaus.org Codehaus Maven Repository dav:https://dav.codehaus.org/repository/mvel/ codehaus.org Codehaus Snapshot Maven Repository dav:https://dav.codehaus.org/snapshots.repository/mvel/ false mvel-2.0.18.orig/LICENSE.txt0000644000175000017500000002411510555047246015236 0ustar drazzibdrazzib Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. mvel-2.0.18.orig/lib/0000755000175000017500000000000011412747035014152 5ustar drazzibdrazzibmvel-2.0.18.orig/.classpath0000644000175000017500000000151311167215375015373 0ustar drazzibdrazzib mvel-2.0.18.orig/.project0000644000175000017500000000043710654604056015061 0ustar drazzibdrazzib mvel org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature mvel-2.0.18.orig/build.properties0000644000175000017500000000052511334113710016611 0ustar drazzibdrazzibsrc.includes = .,\ build.properties,\ META-INF/,\ src/,\ pom.xml bin.includes = .,\ META-INF/,\ build.properties,\ source.. = src/main/java/,\ src/main/resources/ output.. = target/classes/ jars.compile.order = . mvel-2.0.18.orig/gae.patch0000644000175000017500000001010311261146517015154 0ustar drazzibdrazzibIndex: src/main/java/org/mvel2/optimizers/dynamic/DynamicOptimizer.java =================================================================== --- src/main/java/org/mvel2/optimizers/dynamic/DynamicOptimizer.java (revision 2278) +++ src/main/java/org/mvel2/optimizers/dynamic/DynamicOptimizer.java Tue Sep 22 14:24:54 EST 2009 @@ -37,13 +37,18 @@ public static long timeSpan = 100; public static int maximumTenure = 1500; public static int totalRecycled = 0; + private static volatile boolean useSafeClassloading = false; + public static void useSafeClassloading(boolean useSafe) { + useSafeClassloading = useSafe; + } + public void init() { _init(); } private static void _init() { - setMVELClassLoader(classLoader = new DynamicClassLoader(currentThread().getContextClassLoader(), maximumTenure)); + setMVELClassLoader(classLoader = new DynamicClassLoader(currentThread().getContextClassLoader(), maximumTenure, useSafeClassloading)); } public static void enforceTenureLimit() { Index: src/main/java/org/mvel2/util/JITClassLoader.java =================================================================== --- src/main/java/org/mvel2/util/JITClassLoader.java (revision 2724) +++ src/main/java/org/mvel2/util/JITClassLoader.java Tue Sep 22 14:21:09 EST 2009 @@ -26,7 +26,7 @@ private static boolean sunJVM; private static Object sunUnsafe; - static { + private static void init() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); @@ -39,9 +39,13 @@ } } - - public JITClassLoader(ClassLoader classLoader) { + public JITClassLoader(ClassLoader classLoader, boolean useSafeClassloading) { super(classLoader); + + if (useSafeClassloading) + sunJVM = false; + else + init(); } public Class defineClassX(String className, byte[] b, int off, int len) { Index: src/main/java/org/mvel2/optimizers/impl/asm/ASMAccessorOptimizer.java =================================================================== --- src/main/java/org/mvel2/optimizers/impl/asm/ASMAccessorOptimizer.java (revision 2746) +++ src/main/java/org/mvel2/optimizers/impl/asm/ASMAccessorOptimizer.java Tue Sep 22 15:26:40 EST 2009 @@ -1946,7 +1946,12 @@ } private static MVELClassLoader classLoader; + private static volatile boolean useSafeClassloading = false; + public static void useSafeClassloading(boolean useSafe) { + useSafeClassloading = useSafe; + } + public static void setMVELClassLoader(MVELClassLoader cl) { classLoader = cl; } @@ -1957,7 +1962,7 @@ public void init() { try { - classLoader = new JITClassLoader(currentThread().getContextClassLoader()); + classLoader = new JITClassLoader(currentThread().getContextClassLoader(), useSafeClassloading); } catch (Exception e) { throw new RuntimeException(e); Index: src/main/java/org/mvel2/optimizers/dynamic/DynamicClassLoader.java =================================================================== --- src/main/java/org/mvel2/optimizers/dynamic/DynamicClassLoader.java (revision 2360) +++ src/main/java/org/mvel2/optimizers/dynamic/DynamicClassLoader.java Mon Sep 21 19:02:04 EST 2009 @@ -34,7 +34,7 @@ private static boolean sunJVM; private static Object sunUnsafe; - static { + private static void init() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); @@ -48,11 +48,18 @@ } - public DynamicClassLoader(ClassLoader classLoader, int tenureLimit) { + public DynamicClassLoader(ClassLoader classLoader, int tenureLimit, boolean useSafeClassloading) { super(classLoader); this.tenureLimit = tenureLimit; + + // Do not call init() from here. =0 + if (useSafeClassloading) + sunJVM = false; + else + init(); } + public Class defineClassX(String className, byte[] b, int start, int end) { totalClasses++; if (sunJVM) { mvel-2.0.18.orig/src/0000755000175000017500000000000011412747040014167 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/0000755000175000017500000000000011412747040015113 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/0000755000175000017500000000000011412747040016034 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/0000755000175000017500000000000011412747040016623 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/0000755000175000017500000000000011412747055017656 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/sh/0000755000175000017500000000000011412747054020267 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/sh/DefaultEnvironment.java0000644000175000017500000000164011077460760024747 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh; public interface DefaultEnvironment { public static final String PROMPT = "[@{ new java.text.SimpleDateFormat('hh:mmaa').format(new java.util.Date(System.currentTimeMillis()))}] mvel2$ "; } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/text/0000755000175000017500000000000011412747054021253 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/sh/text/TextUtil.java0000644000175000017500000000272711077460760023713 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.text; import org.mvel2.util.StringAppender; import static java.lang.String.valueOf; public class TextUtil { public static String pad(int colLength, int tabPos) { StringAppender sAppend = new StringAppender(); for (int len = tabPos - colLength; len != -1; len--) { sAppend.append(' '); } return sAppend.toString(); } public static String paint(char c, int amount) { StringAppender append = new StringAppender(); for (; amount != -1; amount--) { append.append(c); } return append.toString(); } public static String padTwo(Object first, Object second, int tab) { return new StringAppender(valueOf(first)).append(pad(valueOf(first).length(), tab)).append(second).toString(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/CommandSet.java0000644000175000017500000000146011077460760023170 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh; import java.util.Map; public interface CommandSet { public Map load(); } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/CommandException.java0000644000175000017500000000211711077460760024373 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh; public class CommandException extends RuntimeException { public CommandException() { super(); } public CommandException(String message) { super(message); } public CommandException(String message, Throwable cause) { super(message, cause); } public CommandException(Throwable cause) { super(cause); } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/0000755000175000017500000000000011412747054021705 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/file/0000755000175000017500000000000011412747054022624 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/file/FileCommandSet.java0000644000175000017500000000224311077460760026325 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.file; import org.mvel2.sh.Command; import org.mvel2.sh.CommandSet; import java.util.HashMap; import java.util.Map; public class FileCommandSet implements CommandSet { public Map load() { Map cmd = new HashMap(); cmd.put("ls", new DirList()); cmd.put("cd", new ChangeWorkingDir()); cmd.put("pwd", new PrintWorkingDirectory()); return cmd; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/file/ChangeWorkingDir.java0000644000175000017500000000405711077460760026665 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.file; import org.mvel2.sh.Command; import org.mvel2.sh.CommandException; import org.mvel2.sh.ShellSession; import java.io.File; public class ChangeWorkingDir implements Command { public Object execute(ShellSession session, String[] args) { File cwd = new File(session.getEnv().get("$CWD")); if (args.length == 0 || ".".equals(args[0])) return null; else if ("..".equals(args[0])) { if (cwd.getParentFile() != null) { cwd = cwd.getParentFile(); } else { throw new CommandException("already at top-level directory"); } } else if (args[0].charAt(0) == '/') { cwd = new File(args[0]); if (!cwd.exists()) { throw new CommandException("no such directory: " + args[0]); } } else { cwd = new File(cwd.getAbsolutePath() + "/" + args[0]); if (!cwd.exists()) { throw new CommandException("no such directory: " + args[0]); } } session.getEnv().put("$CWD", cwd.getAbsolutePath()); return null; } public String getDescription() { return "changes the working directory"; } public String getHelp() { return "no help yet"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/file/PrintWorkingDirectory.java0000644000175000017500000000217611077460760030022 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.file; import org.mvel2.sh.Command; import org.mvel2.sh.ShellSession; public class PrintWorkingDirectory implements Command { public Object execute(ShellSession session, String[] args) { System.out.println(session.getEnv().get("$CWD")); return null; } public String getDescription() { return "prints the current working directory"; } public String getHelp() { return "no help yet."; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/file/DirList.java0000644000175000017500000000370211077460760025046 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.file; import org.mvel2.sh.Command; import org.mvel2.sh.CommandException; import org.mvel2.sh.ShellSession; import java.io.File; public class DirList implements Command { public Object execute(ShellSession session, String[] args) { File current = new File(session.getEnv().get("$CWD")); if (!current.isDirectory()) throw new CommandException("cannot list directory : " + session.getEnv().get("$CWD") + " is not a directory"); File[] files = current.listFiles(); if (files.length == 0) return null; else { System.out.append("Total ").append(String.valueOf(files.length)).append("\n"); } for (File file : current.listFiles()) { if (file.isDirectory()) { System.out.append(file.getName()).append("/"); } else { System.out.append(file.getName()); } System.out.append("\n"); } System.out.flush(); return null; } public String getDescription() { return "performs a list of files and directories in the current working dir."; } public String getHelp() { return "no help yet"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/basic/0000755000175000017500000000000011412747054022766 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/basic/Set.java0000644000175000017500000000347611124351426024370 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.basic; import org.mvel2.sh.Command; import org.mvel2.sh.CommandException; import org.mvel2.sh.ShellSession; import org.mvel2.util.StringAppender; import java.util.Map; public class Set implements Command { public Object execute(ShellSession session, String[] args) { Map env = session.getEnv(); if (args.length == 0) { for (String var : env.keySet()) { System.out.println(var + " = " + env.get(var)); } } else if (args.length == 1) { throw new CommandException("incorrect number of parameters"); } else { StringAppender sbuf = new StringAppender(); for (int i = 1; i < args.length; i++) { sbuf.append(args[i]); if (i < args.length) sbuf.append(" "); } env.put(args[0], sbuf.toString().trim()); } return null; } public String getDescription() { return "sets an environment variable"; } public String getHelp() { return null; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/basic/PushContext.java0000644000175000017500000000222311077460760026117 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.basic; import org.mvel2.MVEL; import org.mvel2.sh.Command; import org.mvel2.sh.ShellSession; public class PushContext implements Command { public Object execute(ShellSession session, String[] args) { session.setCtxObject(MVEL.eval(args[0], session.getCtxObject(), session.getVariables())); return "Changed Context"; } public String getDescription() { return null; } public String getHelp() { return null; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/basic/BasicCommandSet.java0000644000175000017500000000250211231742247026622 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.basic; import org.mvel2.sh.Command; import org.mvel2.sh.CommandSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.HashMap; public class BasicCommandSet implements CommandSet { public Map load() { Map cmds = new HashMap(); cmds.put("set", new Set()); cmds.put("push", new PushContext()); cmds.put("help", new Help()); cmds.put("showvars", new ShowVars()); cmds.put("inspect", new ObjectInspector()); cmds.put("exit", new Exit()); return cmds; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/basic/Exit.java0000644000175000017500000000214611077460760024550 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.basic; import org.mvel2.sh.Command; import org.mvel2.sh.ShellSession; public class Exit implements Command { public Object execute(ShellSession session, String[] args) { System.exit(0); return null; } public String getDescription() { return "exits the command shell"; } public String getHelp() { return "No help yet."; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/basic/ObjectInspector.java0000644000175000017500000001256011077460760026735 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.basic; import org.mvel2.sh.Command; import org.mvel2.sh.ShellSession; import org.mvel2.sh.text.TextUtil; import static org.mvel2.sh.text.TextUtil.padTwo; import org.mvel2.util.StringAppender; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.LinkedList; import java.util.List; public class ObjectInspector implements Command { private static final int PADDING = 17; public Object execute(ShellSession session, String[] args) { if (args.length == 0) { System.out.println("inspect: requires an argument."); return null; } if (!session.getVariables().containsKey(args[0])) { System.out.println("inspect: no such variable: " + args[0]); return null; } Object val = session.getVariables().get(args[0]); System.out.println("Object Inspector"); System.out.println(TextUtil.paint('-', PADDING)); if (val == null) { System.out.println("[Value is Null]"); return null; } Class cls = val.getClass(); boolean serialized = true; long serializedSize = 0; try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(outStream)); objectOut.writeObject(val); objectOut.flush(); outStream.flush(); serializedSize = outStream.size(); } catch (Exception e) { serialized = false; } write("VariableName", args[0]); write("Hashcode", val.hashCode()); write("ClassType", cls.getName()); write("Serializable", serialized); if (serialized) { write("SerializedSize", serializedSize + " bytes"); } write("ClassHierarchy", renderClassHeirarchy(cls)); write("Fields", cls.getFields().length); renderFields(cls); write("Methods", cls.getMethods().length); renderMethods(cls); System.out.println(); return null; } private static String renderClassHeirarchy(Class cls) { List list = new LinkedList(); list.add(cls.getName()); while ((cls = cls.getSuperclass()) != null) { list.add(cls.getName()); } StringAppender output = new StringAppender(); for (int i = list.size() - 1; i != -1; i--) { output.append(list.get(i)); if ((i - 1) != -1) output.append(" -> "); } return output.toString(); } private static void renderFields(Class cls) { Field[] fields = cls.getFields(); for (int i = 0; i < fields.length; i++) { write("", fields[i].getType().getName() + " " + fields[i].getName()); } } private static void renderMethods(Class cls) { Method[] methods = cls.getMethods(); Method m; StringAppender appender = new StringAppender(); int mf; for (int i = 0; i < methods.length; i++) { appender.append(TextUtil.paint(' ', PADDING + 2)); if (((mf = (m = methods[i]).getModifiers()) & Modifier.PUBLIC) != 0) appender.append("public"); else if ((mf & Modifier.PRIVATE) != 0) appender.append("private"); else if ((mf & Modifier.PROTECTED) != 0) appender.append("protected"); appender.append(' ').append(m.getReturnType().getName()).append(' ').append(m.getName()).append("("); Class[] parmTypes = m.getParameterTypes(); for (int y = 0; y < parmTypes.length; y++) { if (parmTypes[y].isArray()) { appender.append(parmTypes[y].getComponentType().getName() + "[]"); } else { appender.append(parmTypes[y].getName()); } if ((y + 1) < parmTypes.length) appender.append(", "); } appender.append(")"); if (m.getDeclaringClass() != cls) { appender.append(" [inherited from: ").append(m.getDeclaringClass().getName()).append("]"); } if ((i + 1) < methods.length) appender.append('\n'); } System.out.println(appender.toString()); } private static void write(Object first, Object second) { System.out.println(padTwo(first, ": " + second, PADDING)); } public String getDescription() { return "inspects an object"; } public String getHelp() { return "No help yet"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/basic/ShowVars.java0000644000175000017500000000356611077460760025422 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.basic; import org.mvel2.sh.Command; import org.mvel2.sh.CommandException; import org.mvel2.sh.ShellSession; import java.util.Map; public class ShowVars implements Command { public Object execute(ShellSession session, String[] args) { boolean values = false; Map vars = session.getVariables(); for (int i = 0; i < args.length; i++) { if ("-values".equals(args[i])) values = true; else throw new CommandException("unknown argument: " + args[i]); } System.out.println("Printing Variables ..."); if (values) { for (String key : vars.keySet()) { System.out.println(key + " => " + String.valueOf(vars.get(key))); } } else { for (String key : vars.keySet()) { System.out.println(key); } } System.out.println(" ** " + vars.size() + " variables total."); return null; } public String getDescription() { return "shows current variables"; } public String getHelp() { return "no help yet"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/command/basic/Help.java0000644000175000017500000000253511077460760024531 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh.command.basic; import org.mvel2.sh.Command; import org.mvel2.sh.ShellSession; import static org.mvel2.sh.text.TextUtil.pad; public class Help implements Command { public Object execute(ShellSession session, String[] args) { for (String command : session.getCommands().keySet()) { System.out.println(command + pad(command.length(), 25) + "- " + session.getCommands().get(command).getDescription()); } return null; } public String getDescription() { return "displays help for available shell commands"; } public String getHelp() { return "No help yet"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/ShellSession.java0000644000175000017500000004202411257005261023541 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh; import static org.mvel2.MVEL.*; import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.sh.command.basic.BasicCommandSet; import org.mvel2.sh.command.file.FileCommandSet; import org.mvel2.templates.TemplateRuntime; import static org.mvel2.util.PropertyTools.contains; import org.mvel2.util.StringAppender; import org.mvel2.ast.ASTNode; import org.mvel2.ParserContext; import org.mvel2.MVELInterpretedRuntime; import java.io.*; import static java.lang.Boolean.parseBoolean; import static java.lang.Runtime.getRuntime; import static java.lang.System.arraycopy; import static java.lang.System.getProperty; import java.util.*; import static java.util.ResourceBundle.getBundle; /** * A shell session. */ public class ShellSession { public static final String PROMPT_VAR = "$PROMPT"; private static final String[] EMPTY = new String[0]; private final Map commands = new HashMap(); private Map variables; private Map env; private Object ctxObject; ParserContext pCtx = new ParserContext(); VariableResolverFactory lvrf; private int depth; private int cdepth; private boolean multi = false; private int multiIndentSize = 0; private PrintStream out = System.out; private String prompt; private String commandBuffer; StringAppender inBuffer = new StringAppender(); final BufferedReader readBuffer = new BufferedReader(new InputStreamReader(System.in)); public ShellSession() { System.out.println("Starting session..."); variables = new HashMap(); env = new HashMap(); commands.putAll(new BasicCommandSet().load()); commands.putAll(new FileCommandSet().load()); env.put(PROMPT_VAR, DefaultEnvironment.PROMPT); env.put("$OS_NAME", getProperty("os.name")); env.put("$OS_VERSION", getProperty("os.version")); env.put("$JAVA_VERSION", getProperty("java.version")); env.put("$CWD", new File(".").getAbsolutePath()); env.put("$COMMAND_PASSTRU", "false"); env.put("$PRINTOUTPUT", "true"); env.put("$ECHO", "false"); env.put("$SHOW_TRACES", "true"); env.put("$USE_OPTIMIZER_ALWAYS", "false"); env.put("$PATH", ""); try { ResourceBundle bundle = getBundle(".mvelsh.properties"); Enumeration enumer = bundle.getKeys(); String key; while (enumer.hasMoreElements()) { env.put(key = enumer.nextElement(), bundle.getString(key)); } } catch (MissingResourceException e) { System.out.println("No config file found. Loading default config."); if (!contains(getProperty("os.name").toLowerCase(), "windows")) { env.put("$PATH", "/bin:/usr/bin:/sbin:/usr/sbin"); } } lvrf = new MapVariableResolverFactory(variables, new MapVariableResolverFactory(env)); } public ShellSession(String init) { this(); exec(init); } private void _exec() { String[] inTokens; Object outputBuffer; final PrintStream sysPrintStream = System.out; final PrintStream sysErrorStream = System.err; final InputStream sysInputStream = System.in; File execFile; if ("true".equals(env.get("$ECHO"))) { out.println(">" + commandBuffer); out.flush(); } inTokens = inBuffer.append(commandBuffer).toString().split("\\s"); if (inTokens.length != 0 && commands.containsKey(inTokens[0])) { commandBuffer = null; String[] passParameters; if (inTokens.length > 1) { arraycopy(inTokens, 1, passParameters = new String[inTokens.length - 1], 0, passParameters.length); } else { passParameters = EMPTY; } try { commands.get(inTokens[0]).execute(this, passParameters); } catch (CommandException e) { out.append("Error: ").append(e.getMessage()).append("\n"); } } else { commandBuffer = null; try { if (shouldDefer(inBuffer)) { multi = true; return; } else { multi = false; } if (parseBoolean(env.get("$USE_OPTIMIZER_ALWAYS"))) { outputBuffer = executeExpression(compileExpression(inBuffer.toString()), ctxObject, lvrf); } else { MVELInterpretedRuntime runtime = new MVELInterpretedRuntime(inBuffer.toString(), ctxObject, lvrf); runtime.newContext(pCtx); outputBuffer = runtime.parse(); } } catch (Exception e) { if ("true".equals(env.get("$COMMAND_PASSTHRU"))) { String[] paths; String s; if ((s = inTokens[0]).startsWith("./")) { s = new File(env.get("$CWD")).getAbsolutePath() + s.substring(s.indexOf('/')); paths = new String[]{s}; } else { paths = env.get("$PATH").split("(:|;)"); } boolean successfulExec = false; for (String execPath : paths) { if ((execFile = new File(execPath + "/" + s)).exists() && execFile.isFile()) { successfulExec = true; String[] execString = new String[inTokens.length]; execString[0] = execFile.getAbsolutePath(); System.arraycopy(inTokens, 1, execString, 1, inTokens.length - 1); try { final Process p = getRuntime().exec(execString); final OutputStream outStream = p.getOutputStream(); final InputStream inStream = p.getInputStream(); final InputStream errStream = p.getErrorStream(); final RunState runState = new RunState(this); final Thread pollingThread = new Thread(new Runnable() { public void run() { byte[] buf = new byte[25]; int read; while (true) { try { while ((read = inStream.read(buf)) > 0) { for (int i = 0; i < read; i++) { sysPrintStream.print((char) buf[i]); } sysPrintStream.flush(); } if (!runState.isRunning()) break; } catch (Exception e) { break; } } sysPrintStream.flush(); if (!multi) { multiIndentSize = (prompt = String.valueOf(TemplateRuntime.eval(env.get("$PROMPT"), variables))).length(); out.append(prompt); } else { out.append(">").append(indent((multiIndentSize - 1) + (depth * 4))); } } }); final Thread watchThread = new Thread(new Runnable() { public void run() { Thread runningThread = new Thread(new Runnable() { public void run() { try { String read; while (runState.isRunning()) { while ((read = readBuffer.readLine()) != null) { if (runState.isRunning()) { for (char c : read.toCharArray()) { outStream.write((byte) c); } } else { runState.getSession().setCommandBuffer(read); break; } } } outStream.write((byte) '\n'); outStream.flush(); } catch (Exception e2) { } } }); runningThread.setPriority(Thread.MIN_PRIORITY); runningThread.start(); try { p.waitFor(); } catch (InterruptedException e) { // nothing; } sysPrintStream.flush(); runState.setRunning(false); try { runningThread.join(); } catch (InterruptedException e) { // nothing;Ç } } }); pollingThread.setPriority(Thread.MIN_PRIORITY); pollingThread.start(); watchThread.setPriority(Thread.MIN_PRIORITY); watchThread.start(); watchThread.join(); try { pollingThread.notify(); } catch (Exception ne) { } } catch (Exception e2) { // fall through; } } } if (successfulExec) { inBuffer.reset(); return; } } ByteArrayOutputStream stackTraceCap = new ByteArrayOutputStream(); PrintStream capture = new PrintStream(stackTraceCap); e.printStackTrace(capture); capture.flush(); env.put("$LAST_STACK_TRACE", new String(stackTraceCap.toByteArray())); if (parseBoolean(env.get("$SHOW_TRACE"))) { out.println(env.get("$LAST_STACK_TRACE")); } else { out.println(e.toString()); } inBuffer.reset(); return; } if (outputBuffer != null && "true".equals(env.get("$PRINTOUTPUT"))) { out.println(String.valueOf(outputBuffer)); } } inBuffer.reset(); } //todo: fix this public void run() { final BufferedReader readBuffer = new BufferedReader(new InputStreamReader(System.in)); try { //noinspection InfiniteLoopStatement while (true) { printPrompt(); if (commandBuffer == null) { commandBuffer = readBuffer.readLine(); } _exec(); } } catch (Exception e) { e.printStackTrace(); System.out.println("unexpected exception. exiting."); } } public void printPrompt() { if (!multi) { multiIndentSize = (prompt = String.valueOf(TemplateRuntime.eval(env.get("$PROMPT"), variables))).length(); out.append(prompt); } else { out.append(">").append(indent((multiIndentSize - 1) + (depth * 4))); } } public boolean shouldDefer(StringAppender inBuf) { char[] buffer = new char[inBuf.length()]; inBuf.getChars(0, inBuf.length(), buffer, 0); depth = cdepth = 0; for (int i = 0 ; i < buffer.length; i++) { switch (buffer[i]) { case '/': if (i+1 0 ; } public String indent(int size) { StringBuffer sbuf = new StringBuffer(); for (int i = 0; i < size; i++) sbuf.append(" "); return sbuf.toString(); } public Map getCommands() { return commands; } public Map getVariables() { return variables; } public Map getEnv() { return env; } public Object getCtxObject() { return ctxObject; } public void setCtxObject(Object ctxObject) { this.ctxObject = ctxObject; } public String getCommandBuffer() { return commandBuffer; } public void setCommandBuffer(String commandBuffer) { this.commandBuffer = commandBuffer; } public void exec(String command) { for (String c : command.split("\n")) { inBuffer.append(c); _exec(); } } public static final class RunState { private boolean running = true; private ShellSession session; public RunState(ShellSession session) { this.session = session; } public ShellSession getSession() { return session; } public void setSession(ShellSession session) { this.session = session; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } } } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/Command.java0000644000175000017500000000156311077460760022520 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh; public interface Command { public Object execute(ShellSession session, String[] args); public String getDescription(); public String getHelp(); } mvel-2.0.18.orig/src/main/java/org/mvel2/sh/Main.java0000644000175000017500000000250611131461725022015 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.sh; import org.mvel2.MVEL; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { if (args.length != 0) { MVEL.evalFile(new File(args[0])); } else { showSplash(); new ShellSession().run(); } } private static void showSplash() { System.out.println("\nMVEL-Shell (MVELSH)"); System.out.println("Copyright (C) 2008, Christopher Brock, The Codehaus"); System.out.println("Version " + MVEL.VERSION + "." + MVEL.VERSION_SUB + "\n"); } } mvel-2.0.18.orig/src/main/java/org/mvel2/MVEL.java0000644000175000017500000014005611363353131021263 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 MVFLEX/Valhalla Project and the Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import static org.mvel2.DataConversion.convert; import static org.mvel2.MVELRuntime.execute; import org.mvel2.compiler.*; import org.mvel2.integration.Interceptor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.ClassImportResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.optimizers.impl.refl.nodes.GetterAccessor; import static org.mvel2.util.ParseTools.loadFromFile; import static org.mvel2.util.ParseTools.optimizeTree; import java.io.File; import java.io.IOException; import java.io.Serializable; import static java.lang.Boolean.getBoolean; import static java.lang.String.valueOf; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; /** * The MVEL convienence class is a collection of static methods that provides a set of easy integration points for * MVEL. The vast majority of MVEL's core functionality can be directly accessed through methods in this class. */ public class MVEL { public static final String NAME = "MVEL (MVFLEX Expression Language)"; public static final String VERSION = "2.0.18"; public static final String VERSION_SUB = ""; public static final String CODENAME = "enceladus"; static boolean DEBUG_FILE = getBoolean("mvel2.debug.fileoutput"); static String ADVANCED_DEBUGGING_FILE = System.getProperty("mvel2.debugging.file") == null ? "mvel_debug.txt" : System.getProperty("mvel2.debugging.file"); static boolean ADVANCED_DEBUG = getBoolean("mvel2.advanced_debugging"); static boolean WEAK_CACHE = getBoolean("mvel2.weak_caching"); static boolean NO_JIT = getBoolean("mvel2.disable.jit"); public static boolean COMPILER_OPT_ALLOW_NAKED_METH_CALL = getBoolean("mvel2.compiler.allow_naked_meth_calls"); public static boolean COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = getBoolean("mvel2.compiler.allow_override_all_prophandling"); static boolean OPTIMIZER = true; static { if (System.getProperty("mvel2.optimizer") != null) { OPTIMIZER = getBoolean("mvel2.optimizer"); } } // don't construct this! private MVEL() { } public static boolean isAdvancedDebugging() { return ADVANCED_DEBUG; } public static String getDebuggingOutputFileName() { return ADVANCED_DEBUGGING_FILE; } public static boolean isFileDebugging() { return DEBUG_FILE; } /** * Evaluate an expression and return the value. * * @param expression A String containing the expression to be evaluated. * @return the resultant value */ public static Object eval(String expression) { return new MVELInterpretedRuntime(expression, MVELRuntime.IMMUTABLE_DEFAULT_FACTORY).parse(); } /** * Evaluate an expression against a context object. Expressions evaluated against a context object are designed * to treat members of that context object as variables in the expression. For example: *

     * MVEL.eval("foo == 1", ctx);
     * 
* In this case, the identifier foo would be resolved against the ctx object. So it would have * the equivalent of: ctc.getFoo() == 1 in Java. * * @param expression A String containing the expression to be evaluated. * @param ctx The context object to evaluate against. * @return The resultant value */ public static Object eval(String expression, Object ctx) { return new MVELInterpretedRuntime(expression, ctx, MVELRuntime.IMMUTABLE_DEFAULT_FACTORY).parse(); } /** * Evaluate an expression with externally injected variables via a {@link VariableResolverFactory}. A factory * provides the means by which MVEL can resolve external variables. MVEL contains a straight-forward implementation * for wrapping Maps: {@link MapVariableResolverFactory}, which is used implicitly when calling overloaded methods * in this class that use Maps. *

* An example: *


     * Map varsMap = new HashMap();
     * varsMap.put("x", 5);
     * varsMap.put("y", 2);
     * 

* VariableResolverFactory factory = new MapVariableResolverFactory(varsMap); *

* Integer i = (Integer) MVEL.eval("x * y", factory); *

* assert i == 10; *

* * @param expression A String containing the expression to be evaluated. * @param resolverFactory The instance of the VariableResolverFactory to be used. * @return The resultant value. */ public static Object eval(String expression, VariableResolverFactory resolverFactory) { return new MVELInterpretedRuntime(expression, resolverFactory).parse(); } /** * Evaluates an expression against a context object and injected variables from a {@link VariableResolverFactory}. * This method of execution will prefer to find variables from the factory and then from the context. * * @param expression A string containing the expression to be evaluated * @param ctx The context object to evaluate against. * @param resolverFactory The instance of the VariableResolverFactory to be used. * @return The resultant value * @see #eval(String, org.mvel2.integration.VariableResolverFactory) */ public static Object eval(String expression, Object ctx, VariableResolverFactory resolverFactory) { return new MVELInterpretedRuntime(expression, ctx, resolverFactory).parse(); } /** * Evaluates an expression against externally injected variables. This is a wrapper convenience method which * wraps the provided Map of vars in a {@link MapVariableResolverFactory} * * @param expression A string containing the expression to be evaluated. * @param vars A map of vars to be injected * @return The resultant value * @see #eval(String, org.mvel2.integration.VariableResolverFactory) */ public static Object eval(String expression, Map vars) { return new MVELInterpretedRuntime(expression, null, new MapVariableResolverFactory(vars)).parse(); } /** * Evaluates an expression against a context object and externally injected variables. This is a wrapper * convenience method which wraps the provided Map of vars in a {@link MapVariableResolverFactory} * * @param expression A string containing the expression to be evaluated. * @param ctx The context object to evaluate against. * @param vars A map of vars to be injected * @return The resultant value * @see #eval(String, VariableResolverFactory) */ public static Object eval(String expression, Object ctx, Map vars) { return new MVELInterpretedRuntime(expression, ctx, new MapVariableResolverFactory(vars)).parse(); } /** * Evaluates an expression and, if necessary, coerces the resultant value to the specified type. Example: *

     * Float output = MVEL.eval("5 + 5", Float.class);
     * 
*

* This converts an expression that would otherwise return an Integer to a Float. * * @param expression A string containing the expression to be evaluated. * @param toType The target type that the resultant value will be converted to, if necessary. * @return The resultant value. */ public static T eval(String expression, Class toType) { return convert(new MVELInterpretedRuntime(expression).parse(), toType); } /** * Evaluates an expression against a context object and, if necessary, coerces the resultant value to the specified * type. * * @param expression A string containing the expression to be evaluated. * @param ctx The context object to evaluate against. * @param toType The target type that the resultant value will be converted to, if necessary. * @return The resultant value * @see #eval(String,Class) */ public static T eval(String expression, Object ctx, Class toType) { return convert(new MVELInterpretedRuntime(expression, ctx).parse(), toType); } /** * Evaluates an expression against externally injected variables and, if necessary, coerces the resultant value * to the specified type. * * @param expression A string containing the expression to be evaluated * @param vars The variables to be injected * @param toType The target type that the resultant value will be converted to, if necessary. * @return The resultant value * @see #eval(String,VariableResolverFactory) * @see #eval(String,Class) */ public static T eval(String expression, VariableResolverFactory vars, Class toType) { return convert(new MVELInterpretedRuntime(expression, null, vars).parse(), toType); } /** * Evaluates an expression against externally injected variables. The resultant value is coerced to the specified * type if necessary. This is a wrapper convenience method which wraps the provided Map of vars in a * {@link MapVariableResolverFactory} * * @param expression A string containing the expression to be evaluated. * @param vars A map of vars to be injected * @param toType The target type the resultant value will be converted to, if necessary. * @return The resultant value * @see #eval(String, org.mvel2.integration.VariableResolverFactory) */ public static T eval(String expression, Map vars, Class toType) { return convert(new MVELInterpretedRuntime(expression, null, new MapVariableResolverFactory(vars)).parse(), toType); } /** * Evaluates an expression against a context object and externally injected variables. If necessary, the resultant * value is coerced to the specified type. * * @param expression A string containing the expression to be evaluated. * @param ctx The context object to evaluate against * @param vars The vars to be injected * @param toType The target type that the resultant value will be converted to, if necessary. * @return The resultant value. * @see #eval(String,Object,VariableResolverFactory) * @see #eval(String,Class) */ public static T eval(String expression, Object ctx, VariableResolverFactory vars, Class toType) { return convert(new MVELInterpretedRuntime(expression, ctx, vars).parse(), toType); } /** * Evaluates an expression against a context object and externally injected variables. If necessary, the resultant * value is coerced to the specified type. * * @param expression A string containing the expression to be evaluated. * @param ctx The context object to evaluate against * @param vars A Map of variables to be injected. * @param toType The target type that the resultant value will be converted to, if necessary. * @return The resultant value. * @see #eval(String,Object,VariableResolverFactory) * @see #eval(String,Class) */ public static T eval(String expression, Object ctx, Map vars, Class toType) { return convert(new MVELInterpretedRuntime(expression, ctx, new MapVariableResolverFactory(vars)).parse(), toType); } /** * Evaluates an expression and returns the resultant value as a String. * * @param expression A string containing the expressino to be evaluated. * @return The resultant value */ public static String evalToString(String expression) { try { return valueOf(eval(expression)); } catch (EndWithValue end) { return valueOf(end.getValue()); } } /** * Evaluates an expression and returns the resultant value as a String. * * @param expression A string containing the expressino to be evaluated. * @param ctx The context object to evaluate against * @return The resultant value * @see #eval(String,Object) */ public static String evalToString(String expression, Object ctx) { try { return valueOf(eval(expression, ctx)); } catch (EndWithValue end) { return valueOf(end.getValue()); } } /** * Evaluates an expression and returns the resultant value as a String. * * @param expression A string containing the expressino to be evaluated. * @param vars The variables to be injected * @return The resultant value * @see #eval(String,VariableResolverFactory) */ public static String evalToString(String expression, VariableResolverFactory vars) { try { return valueOf(eval(expression, vars)); } catch (EndWithValue end) { return valueOf(end.getValue()); } } /** * Evaluates an expression and returns the resultant value as a String. * * @param expression A string containing the expressino to be evaluated. * @param vars A Map of variables to be injected * @return The resultant value * @see #eval(String,Map) */ public static String evalToString(String expression, Map vars) { try { return valueOf(eval(expression, vars)); } catch (EndWithValue end) { return valueOf(end.getValue()); } } /** * Evaluates an expression and returns the resultant value as a String. * * @param expression A string containing the expressino to be evaluated. * @param ctx The context object to evaluate against. * @param vars The variables to be injected * @return The resultant value * @see #eval(String,Map) */ public static String evalToString(String expression, Object ctx, VariableResolverFactory vars) { try { return valueOf(eval(expression, ctx, vars)); } catch (EndWithValue end) { return valueOf(end.getValue()); } } /** * Evaluates an expression and returns the resultant value as a String. * * @param expression A string containing the expressino to be evaluated. * @param ctx The context object to evaluate against. * @param vars A Map of variables to be injected * @return The resultant value * @see #eval(String,Map) */ public static String evalToString(String expression, Object ctx, Map vars) { try { return valueOf(eval(expression, ctx, vars)); } catch (EndWithValue end) { return valueOf(end.getValue()); } } /** * Evaluate an expression and return the value. * * @param expression A char[] containing the expression to be evaluated. * @return The resultant value * @see #eval(String) */ public static Object eval(char[] expression) { try { return new MVELInterpretedRuntime(expression, MVELRuntime.IMMUTABLE_DEFAULT_FACTORY).parse(); } catch (EndWithValue end) { return end.getValue(); } } /** * Evaluate an expression against a context object and return the value * * @param expression A char[] containing the expression to be evaluated. * @param ctx The context object to evaluate against * @return The resultant value * @see #eval(String,Object) */ public static Object eval(char[] expression, Object ctx) { try { return new MVELInterpretedRuntime(expression, ctx).parse(); } catch (EndWithValue end) { return end.getValue(); } } public static T eval(char[] expression, Class type) { try { return convert(new MVELInterpretedRuntime(expression).parse(), type); } catch (EndWithValue end) { return (T) end.getValue(); } } /** * Evaluate an expression against a context object and return the value * * @param expression A char[] containing the expression to be evaluated. * @param ctx The context object to evaluate against * @param vars The variables to be injected * @return The resultant value * @see #eval(String,Object,VariableResolverFactory) */ public static Object eval(char[] expression, Object ctx, VariableResolverFactory vars) { try { return new MVELInterpretedRuntime(expression, ctx, vars).parse(); } catch (EndWithValue end) { return end.getValue(); } } /** * Evaluate an expression against a context object and return the value * * @param expression A char[] containing the expression to be evaluated. * @param ctx The context object to evaluate against * @param vars A Map of variables to be injected * @return The resultant value * @see #eval(String,Object,Map) */ public static Object eval(char[] expression, Object ctx, Map vars) { try { return new MVELInterpretedRuntime(expression, ctx, vars).parse(); } catch (EndWithValue end) { return end.getValue(); } } /** * Evaluate an expression with a context object and injected variables and return the value. If necessary convert * the resultant value to the specified type. * * @param expression A char[] containing the expression to be evaluated. * @param ctx The context object to evaluate against * @param vars A Map of variables to be injected * @param toType The target type the resultant value will be converted to, if necessary. * @return The resultant value * @see #eval(String,Object,Map,Class) */ public static T eval(char[] expression, Object ctx, Map vars, Class toType) { try { return convert(new MVELInterpretedRuntime(expression, ctx, vars).parse(), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } /** * Evaluate an expression with a context object and return the value. If necessary convert * the resultant value to the specified type. * * @param expression A char[] containing the expression to be evaluated. * @param ctx The context object to evaluate against * @param toType The target type the resultant value will be converted to, if necessary. * @return The resultant value * @see #eval(String,Object,Class) */ public static T eval(char[] expression, Object ctx, Class toType) { try { return convert(new MVELInterpretedRuntime(expression, ctx).parse(), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } /** * Evaluate an expression with a context object and injected variables and return the value. If necessary convert * the resultant value to the specified type. * * @param expression A char[] containing the expression to be evaluated. * @param ctx The context object to evaluate against * @param vars The variables to be injected * @param toType The target type the resultant value will be converted to, if necessary. * @return The resultant value * @see #eval(String,Object,VariableResolverFactory,Class) */ public static T eval(char[] expression, Object ctx, VariableResolverFactory vars, Class toType) { try { return convert(new MVELInterpretedRuntime(expression, ctx, vars).parse(), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } /** * Evaluate an expression with injected variables and return the value. If necessary convert * the resultant value to the specified type. * * @param expression A char[] containing the expression to be evaluated. * @param vars The variables to be injected * @param toType The target type the resultant value will be converted to, if necessary. * @return The resultant value * @see #eval(String,VariableResolverFactory,Class) */ public static T eval(char[] expression, VariableResolverFactory vars, Class toType) { try { return convert(new MVELInterpretedRuntime(expression, null, vars).parse(), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } /** * Evaluate an expression with injected variables and return the resultant value. If necessary convert * the resultant value to the specified type. * * @param expression A char[] containing the expression to be evaluated. * @param vars The variables to be injected * @param toType The target type the resultant value will be converted to, if necessary. * @return The resultant value * @see #eval(String,Map,Class) */ public static T eval(char[] expression, Map vars, Class toType) { try { return convert(new MVELInterpretedRuntime(expression, null, vars).parse(), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } /** * Evaluate a script from a file and return the resultant value. * * @param file The file to process * @return The resultant value * @throws IOException Exception thrown if there is an IO problem accessing the file. */ public static Object evalFile(File file) throws IOException { return _evalFile(file, null, new MapVariableResolverFactory(new HashMap())); } public static Object evalFile(File file, String encoding) throws IOException { return _evalFile(file, encoding, null, new MapVariableResolverFactory(new HashMap())); } /** * Evaluate a script from a file, against a context object and return the resultant value. * * @param file The file to process * @param ctx The context to evaluate the script against. * @return The resultant value * @throws IOException Exception thrown if there is an IO problem accessing the file. */ public static Object evalFile(File file, Object ctx) throws IOException { return _evalFile(file, ctx, new MapVariableResolverFactory(new HashMap())); } public static Object evalFile(File file, String encoding, Object ctx) throws IOException { return _evalFile(file, encoding, ctx, new MapVariableResolverFactory(new HashMap())); } /** * Evaluate a script from a file with injected variables and return the resultant value. * * @param file The file to process * @param vars Variables to be injected * @return The resultant value * @throws IOException Exception thrown if there is an IO problem accessing the file. */ public static Object evalFile(File file, Map vars) throws IOException { return _evalFile(file, null, new MapVariableResolverFactory(vars)); } /** * Evaluate a script from a file with injected variables and a context object, then return the resultant value. * * @param file The file to process * @param ctx The context to evaluate the script against. * @param vars Variables to be injected * @return The resultant value * @throws IOException Exception thrown if there is an IO problem accessing the file. */ public static Object evalFile(File file, Object ctx, Map vars) throws IOException { return _evalFile(file, ctx, new MapVariableResolverFactory(vars)); } public static Object evalFile(File file, String encoding, Object ctx, Map vars) throws IOException { return _evalFile(file, encoding, ctx, new MapVariableResolverFactory(vars)); } /** * Evaluate a script from a file with injected variables and a context object, then return the resultant value. * * @param file The file to process * @param ctx The context to evaluate the script against. * @param vars Variables to be injected * @return The resultant value * @throws IOException Exception thrown if there is an IO problem accessing the file. */ public static Object evalFile(File file, Object ctx, VariableResolverFactory vars) throws IOException { return _evalFile(file, ctx, vars); } public static Object evalFile(File file, String encoding, Object ctx, VariableResolverFactory vars) throws IOException { return _evalFile(file, encoding, ctx, vars); } private static Object _evalFile(File file, Object ctx, VariableResolverFactory factory) throws IOException { return _evalFile(file, null, ctx, factory); } private static Object _evalFile(File file, String encoding, Object ctx, VariableResolverFactory factory) throws IOException { try { return eval(loadFromFile(file, encoding), ctx, factory); } catch (EndWithValue end) { return end.getValue(); } } /** * Evaluate an expression in Boolean-only mode against a root context object and injected variables. * * @param expression A string containing the expression to be evaluated. * @param ctx The context against which to evaluate the expression * @param vars The variables to be injected * @return The resultant value as a Boolean */ public static Boolean evalToBoolean(String expression, Object ctx, Map vars) { try { return eval(expression, ctx, vars, Boolean.class); } catch (EndWithValue end) { return convert(end.getValue(), Boolean.class); } } /** * Evaluate an expression in Boolean-only mode against a root context object. * * @param expression A string containing the expression to be evaluated. * @param ctx The context against which to evaluate the expression * @return The resultant value as a Boolean */ public static Boolean evalToBoolean(String expression, Object ctx) { try { return eval(expression, ctx, Boolean.class); } catch (EndWithValue end) { return convert(end.getValue(), Boolean.class); } } /** * Evaluate an expression in Boolean-only mode against a root context object and injected variables. * * @param expression A string containing the expression to be evaluated. * @param ctx The context against which to evaluate the expression * @param vars The variables to be injected * @return The resultant value as a Boolean */ public static Boolean evalToBoolean(String expression, Object ctx, VariableResolverFactory vars) { try { return eval(expression, ctx, vars, Boolean.class); } catch (EndWithValue end) { return convert(end.getValue(), Boolean.class); } } /** * Evaluate an expression in Boolean-only with injected variables. * * @param expression A string containing the expression to be evaluated. * @param vars The variables to be injected * @return The resultant value as a Boolean */ public static Boolean evalToBoolean(String expression, VariableResolverFactory vars) { try { return eval(expression, vars, Boolean.class); } catch (EndWithValue end) { return convert(end.getValue(), Boolean.class); } } /** * Evaluate an expression in Boolean-only with injected variables. * * @param expression A string containing the expression to be evaluated. * @param vars The variables to be injected * @return The resultant value as a Boolean */ public static Boolean evalToBoolean(String expression, Map vars) { try { return evalToBoolean(expression, null, vars); } catch (EndWithValue end) { return convert(end.getValue(), Boolean.class); } } /** * Performs an analysis compile, which will populate the ParserContext with type, input and variable information, * but will not produce a payload. * * @param expression - the expression to analyze * @param ctx - the parser context */ public static void analysisCompile(char[] expression, ParserContext ctx) { ExpressionCompiler compiler = new ExpressionCompiler(expression); compiler.setVerifyOnly(true); compiler.compile(ctx); } public static void analysisCompile(String expression, ParserContext ctx) { analysisCompile(expression.toCharArray(), ctx); } public static Class analyze(char[] expression, ParserContext ctx) { ExpressionCompiler compiler = new ExpressionCompiler(expression); compiler.setVerifyOnly(true); compiler.compile(ctx); return compiler.getReturnType(); } public static Class analyze(String expression, ParserContext ctx) { return analyze(expression.toCharArray(), ctx); } /** * Compiles an expression and returns a Serializable object containing the compiled expression. The returned value * can be reused for higher-performance evaluation of the expression. It is used in a straight forward way: *


     * 

* // Compile the expression * Serializable compiled = MVEL.compileExpression("x * 10"); *

* // Create a Map to hold the variables. * Map vars = new HashMap(); *

* // Create a factory to envelop the variable map * VariableResolverFactory factory = new MapVariableResolverFactory(vars); *

* int total = 0; * for (int i = 0; i < 100; i++) { * // Update the 'x' variable. * vars.put("x", i); *

* // Execute the expression against the compiled payload and factory, and add the result to the total variable. * total += (Integer) MVEL.executeExpression(compiled, factory); * } *

* // Total should be 49500 * assert total == 49500; *

*

* The above example demonstrates a compiled expression being reused ina tight, closed, loop. Doing this greatly * improves performance as re-parsing of the expression is not required, and the runtime can dynamically compile * the expression to bytecode of necessary. * * @param expression A String contaiing the expression to be compiled. * @return The cacheable compiled payload. */ public static Serializable compileExpression(String expression) { return compileExpression(expression, null, null, null); } /** * Compiles an expression and returns a Serializable object containing the compiled expression. This method * also accept a Map of imports. The Map's keys are String's representing the imported, short-form name of the * Classes or Methods imported. An import of a Method is essentially a static import. This is a substitute for * needing to declare import statements within the actual script. *

*


     * Map imports = new HashMap();
     * imports.put("HashMap", java.util.HashMap.class); // import a class
     * imports.put("time", MVEL.getStaticMethod(System.class, "currentTimeMillis", new Class[0])); // import a static method
     * 

* // Compile the expression * Serializable compiled = MVEL.compileExpression("map = new HashMap(); map.put('time', time()); map.time"); *

* // Execute with a blank Map to allow vars to be declared. * Long val = (Long) MVEL.executeExpression(compiled, new HashMap()); *

* assert val > 0; *

* * @param expression A String contaiing the expression to be compiled. * @param imports A String-Class/String-Method pair Map containing imports for the compiler. * @return The cacheable compiled payload. */ public static Serializable compileExpression(String expression, Map imports) { return compileExpression(expression, imports, null, null); } /** * Compiles an expression and returns a Serializable object containing the compiled expression. This method * accepts a Map of imports and Interceptors. See {@link #compileExpression(String,Map)} for information on * imports. The imports parameter in this method is optional and it is safe to pass a null * value.
* {@link org.mvel2.integration.Interceptor Interceptors} are markers within an expression that allow external hooks * to be tied into the expression. *

*


     * // Create a Map to hold the interceptors.
     * Map interceptors = new HashMap();
     * 

* // Create a simple interceptor. * Interceptor logInterceptor = new Interceptor() { * public int doBefore(ASTNode node, VariableResolverFactory factory) { * System.out.println("Interceptor called before!"); * } *

* public int doAfter(Object exitValue, ASTNode node, VariableResolverFactory factory) { * System.out.println("Interceptor called after!"); * } * }; *

* // Add the interceptor to the Map. * interceptors.put("log", logInterceptor); *

* // Create an expression * String expr = "list = [1,2,3,4,5]; @log for (item : list) { System.out.println(item); }; *

* Serializable compiled = MVEL.compileExpression(expr, null, interceptors); *

* // Execute expression with a blank Map to allow vars to be declared. * MVEL.executeExpression(compiled, new HashMap()); *

*

* The above example demonstrates inserting an interceptor into a piece of code. The @log interceptor * wraps the subsequent statement. In this case, the interceptor is fired before the for loop and * after the for loop finishes. * * @param expression A String containing the expression to be evaluated. * @param imports A String-Class/String-Method pair Map containing imports for the compiler. * @param interceptors A Map of registered interceptors. * @return A cacheable compiled payload. */ public static Serializable compileExpression(String expression, Map imports, Map interceptors) { return compileExpression(expression, imports, interceptors, null); } /** * Compiles an expression, and accepts a {@link ParserContext} instance. The ParserContext object is the * fine-grained configuration object for the MVEL parser and compiler. * * @param expression A string containing the expression to be compiled. * @param ctx The parser context * @return A cacheable compiled payload. */ public static Serializable compileExpression(String expression, ParserContext ctx) { return optimizeTree(new ExpressionCompiler(expression).compile(ctx)); } public static Serializable compileExpression(String expression, Map imports, Map interceptors, String sourceName) { return compileExpression(expression, new ParserContext(imports, interceptors, sourceName)); } public static Serializable compileExpression(char[] expression, ParserContext ctx) { return optimizeTree(new ExpressionCompiler(expression).compile(ctx)); } /** * Compiles an expression and returns a Serializable object containing the compiled * expression. * * @param expression The expression to be compiled * @param imports Imported classes * @param interceptors Map of named interceptos * @param sourceName The name of the source file being evaluated (optional) * @return The cacheable compiled payload */ public static Serializable compileExpression(char[] expression, Map imports, Map interceptors, String sourceName) { return compileExpression(expression, new ParserContext(imports, interceptors, sourceName)); } public static Serializable compileExpression(char[] expression) { return compileExpression(expression, null, null, null); } public static Serializable compileExpression(char[] expression, Map imports) { return compileExpression(expression, imports, null, null); } public static Serializable compileExpression(char[] expression, Map imports, Map interceptors) { return compileExpression(expression, imports, interceptors, null); } public static Serializable compileGetExpression(String expression) { return new CompiledAccExpression(expression.toCharArray(), Object.class, new ParserContext()); } public static Serializable compileGetExpression(String expression, ParserContext ctx) { return new CompiledAccExpression(expression.toCharArray(), Object.class, ctx); } public static Serializable compileGetExpression(char[] expression) { return new CompiledAccExpression(expression, Object.class, new ParserContext()); } public static Serializable compileGetExpression(char[] expression, ParserContext ctx) { return new CompiledAccExpression(expression, Object.class, ctx); } public static Serializable compileSetExpression(String expression) { return new CompiledAccExpression(expression.toCharArray(), Object.class, new ParserContext()); } public static Serializable compileSetExpression(String expression, ParserContext ctx) { return new CompiledAccExpression(expression.toCharArray(), Object.class, ctx); } public static Serializable compileSetExpression(String expression, Class ingressType, ParserContext ctx) { return new CompiledAccExpression(expression.toCharArray(), ingressType, ctx); } public static Serializable compileSetExpression(char[] expression) { return new CompiledAccExpression(expression, Object.class, new ParserContext()); } public static Serializable compileSetExpression(char[] expression, ParserContext ctx) { return new CompiledAccExpression(expression, Object.class, ctx); } public static Serializable compileSetExpression(char[] expression, Class ingressType, ParserContext ctx) { return new CompiledAccExpression(expression, ingressType, ctx); } public static void executeSetExpression(Serializable compiledSet, Object ctx, Object value) { ((CompiledAccExpression) compiledSet).setValue(ctx, ctx, MVELRuntime.IMMUTABLE_DEFAULT_FACTORY, value); } public static void executeSetExpression(Serializable compiledSet, Object ctx, VariableResolverFactory vrf, Object value) { ((CompiledAccExpression) compiledSet).setValue(ctx, ctx, vrf, value); } public static Object executeExpression(Object compiledExpression) { try { return ((ExecutableStatement) compiledExpression).getValue(null, MVELRuntime.IMMUTABLE_DEFAULT_FACTORY); } catch (EndWithValue e) { return e.getValue(); } } /** * Executes a compiled expression. * * @param compiledExpression - * @param ctx - * @param vars - * @return - * @see #compileExpression(String) */ @SuppressWarnings({"unchecked"}) public static Object executeExpression(final Object compiledExpression, final Object ctx, final Map vars) { try { return ((ExecutableStatement) compiledExpression).getValue(ctx, vars != null ? new MapVariableResolverFactory(vars) : null); } catch (EndWithValue end) { return end.getValue(); } } public static Object executeExpression(final Object compiledExpression, final Object ctx, final VariableResolverFactory resolverFactory) { try { return ((ExecutableStatement) compiledExpression).getValue(ctx, resolverFactory); } catch (EndWithValue end) { return end.getValue(); } } /** * Executes a compiled expression. * * @param compiledExpression - * @param factory - * @return - * @see #compileExpression(String) */ public static Object executeExpression(final Object compiledExpression, final VariableResolverFactory factory) { try { return ((ExecutableStatement) compiledExpression).getValue(null, factory); } catch (EndWithValue end) { return end.getValue(); } } /** * Executes a compiled expression. * * @param compiledExpression - * @param ctx - * @return - * @see #compileExpression(String) */ public static Object executeExpression(final Object compiledExpression, final Object ctx) { try { return ((ExecutableStatement) compiledExpression).getValue(ctx, MVELRuntime.IMMUTABLE_DEFAULT_FACTORY); } catch (EndWithValue end) { return end.getValue(); } } /** * Executes a compiled expression. * * @param compiledExpression - * @param vars - * @return - * @see #compileExpression(String) */ @SuppressWarnings({"unchecked"}) public static Object executeExpression(final Object compiledExpression, final Map vars) { try { return ((ExecutableStatement) compiledExpression).getValue(null, new MapVariableResolverFactory(vars)); } catch (EndWithValue end) { return end.getValue(); } } /** * Execute a compiled expression and convert the result to a type * * @param compiledExpression - * @param ctx - * @param vars - * @param toType - * @return - */ @SuppressWarnings({"unchecked"}) public static T executeExpression(final Object compiledExpression, final Object ctx, final Map vars, Class toType) { try { return convert(executeExpression(compiledExpression, ctx, vars), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } public static T executeExpression(final Object compiledExpression, final Object ctx, final VariableResolverFactory vars, Class toType) { try { return convert(executeExpression(compiledExpression, ctx, vars), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } /** * Execute a compiled expression and convert the result to a type * * @param compiledExpression - * @param vars - * @param toType - * @return - */ @SuppressWarnings({"unchecked"}) public static T executeExpression(final Object compiledExpression, Map vars, Class toType) { try { return convert(executeExpression(compiledExpression, vars), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } /** * Execute a compiled expression and convert the result to a type. * * @param compiledExpression - * @param ctx - * @param toType - * @return - */ public static T executeExpression(final Object compiledExpression, final Object ctx, Class toType) { try { return convert(executeExpression(compiledExpression, ctx), toType); } catch (EndWithValue end) { return convert(end.getValue(), toType); } } public static void executeExpression(Iterable compiledExpression) { for (CompiledExpression ce : compiledExpression) { ce.getValue(null, null); } } public static void executeExpression(Iterable compiledExpression, Object ctx) { for (CompiledExpression ce : compiledExpression) { ce.getValue(ctx, null); } } public static void executeExpression(Iterable compiledExpression, Map vars) { executeExpression(compiledExpression, null, new MapVariableResolverFactory(vars)); } public static void executeExpression(Iterable compiledExpression, Object ctx, Map vars) { executeExpression(compiledExpression, ctx, new MapVariableResolverFactory(vars)); } public static void executeExpression(Iterable compiledExpression, Object ctx, VariableResolverFactory vars) { for (CompiledExpression ce : compiledExpression) { ce.getValue(ctx, vars); } } public static Object[] executeAllExpression(Serializable[] compiledExpressions, Object ctx, VariableResolverFactory vars) { if (compiledExpressions == null) return GetterAccessor.EMPTY; Object[] o = new Object[compiledExpressions.length]; for (int i = 0; i < compiledExpressions.length; i++) { o[i] = executeExpression(compiledExpressions[i], ctx, vars); } return o; } public static Object executeDebugger(CompiledExpression expression, Object ctx, VariableResolverFactory vars) { try { if (expression.isImportInjectionRequired()) { return execute(true, expression, ctx, new ClassImportResolverFactory(expression .getParserContext().getParserConfiguration(), vars)); } else { return execute(true, expression, ctx, vars); } } catch (EndWithValue e) { return e.getValue(); } } public static String parseMacros(String input, Map macros) { return new MacroProcessor(macros).parse(input); } public static String preprocess(char[] input, PreProcessor[] preprocessors) { char[] ex = input; for (PreProcessor proc : preprocessors) { ex = proc.parse(ex); } return new String(ex); } public static String preprocess(String input, PreProcessor[] preprocessors) { return preprocess(input.toCharArray(), preprocessors); } public static Object getProperty(String property, Object ctx) { return PropertyAccessor.get(property, ctx); } public static void setProperty(Object ctx, String property, Object value) { PropertyAccessor.set(ctx, property, value); } /** * A simple utility method to get a static method from a class with no checked exception. With throw a * RuntimeException if the method is not found or is not a static method. * * @param cls The class containing the static method * @param methodName The method name * @param signature The signature of the method * @return An instance of the Method */ public static Method getStaticMethod(Class cls, String methodName, Class[] signature) { try { Method m = cls.getMethod(methodName, signature); if ((m.getModifiers() & Modifier.STATIC) == 0) throw new RuntimeException("method not a static method: " + methodName); return m; } catch (NoSuchMethodException e) { throw new RuntimeException("no such method: " + methodName); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/0000755000175000017500000000000011412747044022061 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/dynamic/0000755000175000017500000000000011412747044023505 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/dynamic/DynamicSetAccessor.java0000644000175000017500000000653511110327536030077 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.dynamic; import org.mvel2.ParserContext; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import org.mvel2.optimizers.OptimizerFactory; import static java.lang.System.currentTimeMillis; public class DynamicSetAccessor implements DynamicAccessor { private char[] property; private boolean opt = false; private int runcount = 0; private long stamp; private ParserContext context; private final Accessor _safeAccessor; private Accessor _accessor; private String description; public DynamicSetAccessor(ParserContext context, char[] property, Accessor _accessor) { assert _accessor != null; this._safeAccessor = this._accessor = _accessor; this.context = context; this.property = property; this.stamp = System.currentTimeMillis(); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { if (!opt) { if (++runcount > DynamicOptimizer.tenuringThreshold) { if ((currentTimeMillis() - stamp) < DynamicOptimizer.timeSpan) { opt = true; return optimize(ctx, elCtx, variableFactory, value); } else { runcount = 0; stamp = currentTimeMillis(); } } } _accessor.setValue(ctx, elCtx, variableFactory, value); return value; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { throw new RuntimeException("value cannot be read with this accessor"); } private Object optimize(Object ctx, Object elCtx, VariableResolverFactory variableResolverFactory, Object value) { if (DynamicOptimizer.classLoader.isOverloaded()) { DynamicOptimizer.enforceTenureLimit(); } AccessorOptimizer ao = OptimizerFactory.getAccessorCompiler("ASM"); _accessor = ao.optimizeSetAccessor(context, property, ctx, elCtx, variableResolverFactory, false, value, value != null ? value.getClass() : Object.class); assert _accessor != null; return value; } public void deoptimize() { this._accessor = this._safeAccessor; opt = false; runcount = 0; stamp = currentTimeMillis(); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Class getKnownEgressType() { return _safeAccessor.getKnownEgressType(); } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/dynamic/DynamicGetAccessor.java0000644000175000017500000000751111151132047030052 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.dynamic; import org.mvel2.ParserContext; import org.mvel2.compiler.Accessor; import org.mvel2.compiler.AbstractParser; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import org.mvel2.optimizers.OptimizerFactory; import static java.lang.System.currentTimeMillis; public class DynamicGetAccessor implements DynamicAccessor { private char[] property; private long stamp; private int type; private int runcount; private boolean opt = false; private ParserContext context; private Accessor _safeAccessor; private Accessor _accessor; public DynamicGetAccessor(ParserContext context, char[] property, int type, Accessor _accessor) { this._safeAccessor = this._accessor = _accessor; this.type = type; this.property = property; this.context = context; stamp = currentTimeMillis(); } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (!opt) { if (++runcount > DynamicOptimizer.tenuringThreshold) { if ((currentTimeMillis() - stamp) < DynamicOptimizer.timeSpan) { opt = true; return optimize(ctx, elCtx, variableFactory); } else { runcount = 0; stamp = currentTimeMillis(); } } } return _accessor.getValue(ctx, elCtx, variableFactory); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { runcount++; return _accessor.setValue(ctx, elCtx, variableFactory, value); } private Object optimize(Object ctx, Object elCtx, VariableResolverFactory variableResolverFactory) { if (DynamicOptimizer.classLoader.isOverloaded()) { DynamicOptimizer.enforceTenureLimit(); } AccessorOptimizer ao = OptimizerFactory.getAccessorCompiler("ASM"); switch (type) { case DynamicOptimizer.REGULAR_ACCESSOR: _accessor = ao.optimizeAccessor(context, property, ctx, elCtx, variableResolverFactory, false, null); return ao.getResultOptPass(); case DynamicOptimizer.OBJ_CREATION: _accessor = ao.optimizeObjectCreation(context, property, ctx, elCtx, variableResolverFactory); return _accessor.getValue(ctx, elCtx, variableResolverFactory); case DynamicOptimizer.COLLECTION: _accessor = ao.optimizeCollection(AbstractParser.getCurrentThreadParserContext(), ctx, null, property, ctx, elCtx, variableResolverFactory); return _accessor.getValue(ctx, elCtx, variableResolverFactory); } return null; } public void deoptimize() { this._accessor = this._safeAccessor; opt = false; runcount = 0; stamp = currentTimeMillis(); } public long getStamp() { return stamp; } public int getRuncount() { return runcount; } public Class getKnownEgressType() { return _safeAccessor.getKnownEgressType(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/dynamic/DynamicCollectionAccessor.java0000644000175000017500000000643211151132047031427 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.dynamic; import org.mvel2.compiler.Accessor; import org.mvel2.compiler.AbstractParser; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.ParserContext; import static java.lang.System.currentTimeMillis; public class DynamicCollectionAccessor implements DynamicAccessor { private Object rootObject; private Class colType; private char[] property; private long stamp; private int type; private int runcount; private boolean opt = false; private Accessor _safeAccessor; private Accessor _accessor; public DynamicCollectionAccessor(Object rootObject, Class colType, char[] property, int type, Accessor _accessor) { this.rootObject = rootObject; this.colType = colType; this._safeAccessor = this._accessor = _accessor; this.type = type; this.property = property; stamp = currentTimeMillis(); } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (!opt) { if (++runcount > DynamicOptimizer.tenuringThreshold) { if ((currentTimeMillis() - stamp) < DynamicOptimizer.timeSpan) { opt = true; return optimize(AbstractParser.getCurrentThreadParserContext(), ctx, elCtx, variableFactory); } else { runcount = 0; stamp = currentTimeMillis(); } } } return _accessor.getValue(ctx, elCtx, variableFactory); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { runcount++; return _accessor.setValue(ctx, elCtx, variableFactory, value); } private Object optimize(ParserContext pCtx, Object ctx, Object elCtx, VariableResolverFactory variableResolverFactory) { if (DynamicOptimizer.classLoader.isOverloaded()) { DynamicOptimizer.enforceTenureLimit(); } _accessor = OptimizerFactory.getAccessorCompiler("ASM").optimizeCollection(pCtx, rootObject, colType, property, ctx, elCtx, variableResolverFactory); return _accessor.getValue(ctx, elCtx, variableResolverFactory); } public void deoptimize() { this._accessor = this._safeAccessor; opt = false; runcount = 0; stamp = currentTimeMillis(); } public long getStamp() { return stamp; } public int getRuncount() { return runcount; } public Class getKnownEgressType() { return colType; } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/dynamic/DynamicAccessor.java0000644000175000017500000000150111077457613027423 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.dynamic; import org.mvel2.compiler.Accessor; public interface DynamicAccessor extends Accessor { public void deoptimize(); } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/dynamic/DynamicClassLoader.java0000644000175000017500000000467411363353131030057 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.dynamic; import org.mvel2.util.MVELClassLoader; import sun.misc.Unsafe; import java.lang.reflect.Field; import java.util.LinkedList; public class DynamicClassLoader extends ClassLoader implements MVELClassLoader { private int totalClasses; private int tenureLimit; private final LinkedList allAccessors = new LinkedList(); // private static boolean sunJVM; // private static Object sunUnsafe; static { // try { // Field f = Unsafe.class.getDeclaredField("theUnsafe"); // f.setAccessible(true); // sunUnsafe = f.get(null); // sunJVM = true; // } // catch (Throwable t) { // t.printStackTrace(); // sunJVM = false; // } } public DynamicClassLoader(ClassLoader classLoader, int tenureLimit) { super(classLoader); this.tenureLimit = tenureLimit; } public Class defineClassX(String className, byte[] b, int start, int end) { totalClasses++; // if (sunJVM) { // return ((Unsafe) sunUnsafe).defineClass(className, b, start, end); // } // else { return super.defineClass(className, b, start, end); // } } public int getTotalClasses() { return totalClasses; } public DynamicAccessor registerDynamicAccessor(DynamicAccessor accessor) { allAccessors.add(accessor); assert accessor != null; return accessor; } public void deoptimizeAll() { synchronized (allAccessors) { for (DynamicAccessor a : allAccessors) { if (a != null) a.deoptimize(); } } } public boolean isOverloaded() { return tenureLimit < totalClasses; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/dynamic/DynamicOptimizer.java0000644000175000017500000001010311261146517027632 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.dynamic; import org.mvel2.ParserContext; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AbstractOptimizer; import org.mvel2.optimizers.AccessorOptimizer; import static org.mvel2.optimizers.OptimizerFactory.SAFE_REFLECTIVE; import static org.mvel2.optimizers.OptimizerFactory.getAccessorCompiler; import static org.mvel2.optimizers.impl.asm.ASMAccessorOptimizer.setMVELClassLoader; import static java.lang.Thread.currentThread; public class DynamicOptimizer extends AbstractOptimizer implements AccessorOptimizer { private AccessorOptimizer firstStage = getAccessorCompiler(SAFE_REFLECTIVE); public static DynamicClassLoader classLoader; public static int tenuringThreshold = 50; public static long timeSpan = 100; public static int maximumTenure = 1500; public static int totalRecycled = 0; private static volatile boolean useSafeClassloading = false; public void init() { _init(); } private static void _init() { setMVELClassLoader(classLoader = new DynamicClassLoader(currentThread().getContextClassLoader(), maximumTenure)); } public static void enforceTenureLimit() { if (classLoader.isOverloaded()) { classLoader.deoptimizeAll(); totalRecycled = +classLoader.getTotalClasses(); _init(); } } public static final int REGULAR_ACCESSOR = 0; public Accessor optimizeAccessor(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Class ingressType) { return classLoader.registerDynamicAccessor(new DynamicGetAccessor(pCtx, property, 0, firstStage.optimizeAccessor(pCtx, property, ctx, thisRef, factory, rootThisRef, ingressType))); } public static final int SET_ACCESSOR = 1; public Accessor optimizeSetAccessor(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Object value, Class valueType) { return classLoader.registerDynamicAccessor(new DynamicSetAccessor(pCtx, property, firstStage.optimizeSetAccessor(pCtx, property, ctx, thisRef, factory, rootThisRef, value, valueType))); } public static final int COLLECTION = 2; public Accessor optimizeCollection(ParserContext pCtx, Object rootObject, Class type, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory) { return classLoader.registerDynamicAccessor(new DynamicCollectionAccessor(rootObject, type, property, 2, firstStage.optimizeCollection(pCtx, rootObject, type, property, ctx, thisRef, factory))); } public static final int OBJ_CREATION = 3; public Accessor optimizeObjectCreation(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory) { return classLoader.registerDynamicAccessor(new DynamicGetAccessor(pCtx, property, 3, firstStage.optimizeObjectCreation(pCtx, property, ctx, thisRef, factory))); } public Object getResultOptPass() { return firstStage.getResultOptPass(); } public Class getEgressType() { return firstStage.getEgressType(); } public boolean isLiteralOnly() { return firstStage.isLiteralOnly(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/OptimizationNotSupported.java0000644000175000017500000000217511077457613030015 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers; public class OptimizationNotSupported extends RuntimeException { public OptimizationNotSupported() { super(); } public OptimizationNotSupported(String message) { super(message); } public OptimizationNotSupported(String message, Throwable cause) { super(message, cause); } public OptimizationNotSupported(Throwable cause) { super(cause); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/AbstractOptimizer.java0000644000175000017500000002270211345736415026402 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers; import org.mvel2.CompileException; import org.mvel2.compiler.AbstractParser; import static org.mvel2.util.ParseTools.*; import static java.lang.Thread.currentThread; import java.lang.reflect.Method; /** * @author Christopher Brock */ public class AbstractOptimizer extends AbstractParser { protected static final int BEAN = 0; protected static final int METH = 1; protected static final int COL = 2; protected static final int WITH = 3; protected int start = 0; protected boolean collection = false; protected boolean nullSafe = false; protected Class currType = null; /** * Try static access of the property, and return an instance of the Field, Method of Class if successful. * * @return - Field, Method or Class instance. */ protected Object tryStaticAccess() { int begin = cursor; try { /** * Try to resolve this *smartly* as a static class reference. * * This starts at the end of the token and starts to step backwards to figure out whether * or not this may be a static class reference. We search for method calls simply by * inspecting for ()'s. The first union area we come to where no brackets are present is our * test-point for a class reference. If we find a class, we pass the reference to the * property accessor along with trailing methods (if any). * */ boolean meth = false; int last = length; for (int i = length - 1; i > 0; i--) { switch (expr[i]) { case '.': if (!meth) { try { return Class.forName(new String(expr, 0, cursor = last), true, pCtx != null ? pCtx.getParserConfiguration().getClassLoader() : currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { Class cls = Class.forName(new String(expr, 0, i), true, pCtx != null ? pCtx.getParserConfiguration().getClassLoader() : currentThread().getContextClassLoader()); String name = new String(expr, i + 1, expr.length - i - 1); try { return cls.getField(name); } catch (NoSuchFieldException nfe) { for (Method m : cls.getMethods()) { if (name.equals(m.getName())) return m; } return null; } } } meth = false; last = i; break; case '}': i--; for (int d = 1; i > 0 && d != 0; i--) { switch (expr[i]) { case '}': d++; break; case '{': d--; break; case '"': case '\'': char s = expr[i]; while (i > 0 && (expr[i] != s && expr[i - 1] != '\\')) i--; } } break; case ')': i--; for (int d = 1; i > 0 && d != 0; i--) { switch (expr[i]) { case ')': d++; break; case '(': d--; break; case '"': case '\'': char s = expr[i]; while (i > 0 && (expr[i] != s && expr[i - 1] != '\\')) i--; } } meth = true; last = i++; break; case '\'': while (--i > 0) { if (expr[i] == '\'' && expr[i - 1] != '\\') { break; } } break; case '"': while (--i > 0) { if (expr[i] == '"' && expr[i - 1] != '\\') { break; } } break; } } } catch (Exception cnfe) { cursor = begin; } return null; } protected int nextSubToken() { skipWhitespace(); nullSafe = false; switch (expr[start = cursor]) { case '[': return COL; case '.': if ((start + 1) != length) { switch (expr[cursor = ++start]) { case '?': skipWhitespace(); if ((cursor = ++start) == length) { throw new CompileException("unexpected end of statement"); } nullSafe = true; fields = -1; break; case '{': return WITH; default: if (isWhitespace(expr[start])) { skipWhitespace(); start = cursor; } } } else { throw new CompileException("unexpected end of statement"); } break; } //noinspection StatementWithEmptyBody while (++cursor < length && isIdentifierPart(expr[cursor])) ; if (cursor < length) { skipWhitespace(); switch (expr[cursor]) { case '[': return COL; case '(': return METH; default: return BEAN; } } return 0; } protected String capture() { /** * Trim off any whitespace. */ return new String(expr, start = trimRight(start), trimLeft(cursor) - start); } /** * Skip to the next non-whitespace position. */ protected void whiteSpaceSkip() { if (cursor < length) //noinspection StatementWithEmptyBody while (isWhitespace(expr[cursor]) && ++cursor != length) ; } /** * @param c - character to scan to. * @return - returns true is end of statement is hit, false if the scan scar is countered. */ protected boolean scanTo(char c) { for (; cursor < length; cursor++) { switch (expr[cursor]) { case '\'': case '"': cursor = captureStringLiteral(expr[cursor], expr, cursor, expr.length); default: if (expr[cursor] == c) { return false; } } } return true; } protected int findLastUnion() { int split = -1; int depth = 0; for (int i = expr.length - 1; i != 0; i--) { switch (expr[i]) { case '}': case ']': depth++; break; case '{': case '[': if (--depth == 0) { split = i; collection = true; } break; case '.': if (depth == 0) { split = i; } break; } if (split != -1) break; } return split; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/AccessorOptimizer.java0000644000175000017500000000342211151132047026361 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers; import org.mvel2.ParserContext; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; public interface AccessorOptimizer { public void init(); public Accessor optimizeAccessor(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Class ingressType); public Accessor optimizeSetAccessor(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Object value, Class ingressType); public Accessor optimizeCollection(ParserContext pCtx, Object collectionGraph, Class type, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory); public Accessor optimizeObjectCreation(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory); public Object getResultOptPass(); public Class getEgressType(); public boolean isLiteralOnly(); } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/OptimizerFactory.java0000644000175000017500000001024711077457613026251 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers; import org.mvel2.CompileException; import org.mvel2.optimizers.dynamic.DynamicOptimizer; import org.mvel2.optimizers.impl.asm.ASMAccessorOptimizer; import org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer; import static java.lang.Thread.currentThread; import java.util.HashMap; import java.util.Map; public class OptimizerFactory { public static String DYNAMIC = "dynamic"; public static String SAFE_REFLECTIVE = "reflective"; private static String defaultOptimizer; private static final Map accessorCompilers = new HashMap(); private static ThreadLocal> threadOptimizer = new ThreadLocal>(); static { accessorCompilers.put(SAFE_REFLECTIVE, new ReflectiveAccessorOptimizer()); accessorCompilers.put(DYNAMIC, new DynamicOptimizer()); /** * By default, activate the JIT if ASM is present in the classpath */ try { currentThread().getContextClassLoader().loadClass("org.mvel2.asm.ClassWriter"); accessorCompilers.put("ASM", new ASMAccessorOptimizer()); } catch (ClassNotFoundException e) { defaultOptimizer = SAFE_REFLECTIVE; } catch (Throwable e) { e.printStackTrace(); System.err.println("[MVEL] Notice: Possible incorrect version of ASM present (3.0 required). " + "Disabling JIT compiler. Reflective Optimizer will be used."); defaultOptimizer = SAFE_REFLECTIVE; } if (Boolean.getBoolean("mvel2.disable.jit")) setDefaultOptimizer(SAFE_REFLECTIVE); else setDefaultOptimizer(DYNAMIC); } public static AccessorOptimizer getDefaultAccessorCompiler() { try { return accessorCompilers.get(defaultOptimizer).getClass().newInstance(); } catch (Exception e) { throw new CompileException("unable to instantiate accessor compiler", e); } } public static AccessorOptimizer getAccessorCompiler(String name) { try { return accessorCompilers.get(name).getClass().newInstance(); } catch (Exception e) { throw new CompileException("unable to instantiate accessor compiler", e); } } public static AccessorOptimizer getThreadAccessorOptimizer() { if (threadOptimizer.get() == null) { threadOptimizer.set(getDefaultAccessorCompiler().getClass()); } try { return threadOptimizer.get().newInstance(); } catch (Exception e) { throw new CompileException("unable to instantiate accessor compiler", e); } } public static void setThreadAccessorOptimizer(Class optimizer) { if (optimizer == null) throw new RuntimeException("null optimizer"); threadOptimizer.set(optimizer); } public static void setDefaultOptimizer(String name) { try { //noinspection unchecked AccessorOptimizer ao = accessorCompilers.get(defaultOptimizer = name); ao.init(); setThreadAccessorOptimizer(ao.getClass()); } catch (Exception e) { throw new CompileException("unable to instantiate accessor compiler", e); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/OptimizerHook.java0000644000175000017500000000267711077457613025552 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers; import org.mvel2.compiler.Accessor; /** * @author Christopher Brock */ public interface OptimizerHook { /** * Should answer back whether or not this hook understands how to work with the current * optimizer. * * @param optimizer - class type of the current optimizer being used * @return boolean */ public boolean isOptimizerSupported(Class optimizer); /** * The optimizer should delegate back to the hook through this method, passing an instance of itself * in the current state. * * @param optimizer - instance of optimizer * @return boolean */ public Accessor generateAccessor(AccessorOptimizer optimizer); } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/0000755000175000017500000000000011412747042023020 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/0000755000175000017500000000000011412747044023752 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/collection/0000755000175000017500000000000011412747044026105 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/collection/MapCreator.java0000644000175000017500000000350311073655510031005 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.collection; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import java.util.HashMap; import java.util.Map; /** * @author Christopher Brock */ public class MapCreator implements Accessor { private Accessor[] keys; private Accessor[] vals; private int size; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { Map map = new HashMap(size * 2); for (int i = size - 1; i != -1; i--) { //noinspection unchecked map.put(keys[i].getValue(ctx, elCtx, variableFactory), vals[i].getValue(ctx, elCtx, variableFactory)); } return map; } public MapCreator(Accessor[] keys, Accessor[] vals) { this.size = (this.keys = keys).length; this.vals = vals; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { // not implemented return null; } public Class getKnownEgressType() { return Map.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/collection/ExprValueAccessor.java0000644000175000017500000000563411222477143032355 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.collection; import org.mvel2.CompileException; import org.mvel2.ParserContext; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.Accessor; import org.mvel2.compiler.ExecutableLiteral; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.getSubComponentType; /** * @author Christopher Brock */ public class ExprValueAccessor implements Accessor { public ExecutableStatement stmt; public ExprValueAccessor(String ex, Class expectedType, Object ctx, VariableResolverFactory factory, ParserContext pCtx) { stmt = (ExecutableStatement) ParseTools.subCompileExpression(ex.toCharArray(), pCtx); //if (expectedType.isArray()) { Class tt = getSubComponentType(expectedType); Class et = stmt.getKnownEgressType(); if (stmt.getKnownEgressType() != null && !tt.isAssignableFrom(et)) { if ((stmt instanceof ExecutableLiteral) && canConvert(et, tt)) { try { stmt = new ExecutableLiteral(convert(stmt.getValue(ctx, factory), tt)); return; } catch (IllegalArgumentException e) { // fall through; } } if (pCtx != null && pCtx.isStrongTyping()) throw new CompileException("was expecting type: " + tt + "; but found type: " + (et == null ? "null" : et.getName())); } } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { return stmt.getValue(elCtx, variableFactory); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { // not implemented return null; } public ExecutableStatement getStmt() { return stmt; } public void setStmt(ExecutableStatement stmt) { this.stmt = stmt; } public Class getKnownEgressType() { return stmt.getKnownEgressType(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/collection/ArrayCreator.java0000644000175000017500000000420211076220016031333 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.collection; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Array; import static java.lang.reflect.Array.newInstance; /** * @author Christopher Brock */ public class ArrayCreator implements Accessor { public Accessor[] template; private Class arrayType; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (Object.class.equals(arrayType)) { Object[] newArray = new Object[template.length]; for (int i = 0; i < newArray.length; i++) { newArray[i] = template[i].getValue(ctx, elCtx, variableFactory); } return newArray; } else { Object newArray = newInstance(arrayType, template.length); for (int i = 0; i < template.length; i++) { Array.set(newArray, i, template[i].getValue(ctx, elCtx, variableFactory)); } return newArray; } } public ArrayCreator(Accessor[] template, Class arrayType) { this.template = template; this.arrayType = arrayType; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } public Class getKnownEgressType() { return arrayType; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/collection/ListCreator.java0000644000175000017500000000323011073655510031200 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.collection; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.FastList; import java.util.List; /** * @author Christopher Brock */ public class ListCreator implements Accessor { public Accessor[] values; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { Object[] template = new Object[values.length]; for (int i = 0; i < values.length; i++) { template[i] = values[i].getValue(ctx, elCtx, variableFactory); } return new FastList(template); } public ListCreator(Accessor[] values) { this.values = values; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } public Class getKnownEgressType() { return List.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/collection/MDArrayCreator.java0000644000175000017500000000434611073655510031575 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.collection; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Array; import static java.lang.reflect.Array.newInstance; /** * @author Christopher Brock */ public class MDArrayCreator implements Accessor { public Accessor[] template; private Class arrayType; private int dimension; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (Object.class.equals(arrayType)) { Object[] newArray = new Object[template.length]; for (int i = 0; i < newArray.length; i++) newArray[i] = template[i].getValue(ctx, elCtx, variableFactory); return newArray; } else { Object newArray = newInstance(arrayType, template.length); for (int i = 0; i < template.length; i++) { Object o = template[i].getValue(ctx, elCtx, variableFactory); Array.set(newArray, i, o); } return newArray; } } public MDArrayCreator(Accessor[] template, Class arrayType, int dimension) { this.template = template; this.arrayType = arrayType; this.dimension = dimension; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } public Class getKnownEgressType() { return arrayType; } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/ReflectiveAccessorOptimizer.java0000644000175000017500000013074211371320442032273 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.impl.refl; import org.mvel2.*; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import static org.mvel2.MVEL.eval; import org.mvel2.ast.Function; import org.mvel2.ast.TypeDescriptor; import static org.mvel2.ast.TypeDescriptor.getClassReference; import org.mvel2.compiler.Accessor; import org.mvel2.compiler.AccessorNode; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.compiler.PropertyVerifier; import org.mvel2.integration.GlobalListenerFactory; import static org.mvel2.integration.GlobalListenerFactory.*; import org.mvel2.integration.PropertyHandler; import static org.mvel2.integration.PropertyHandlerFactory.*; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AbstractOptimizer; import org.mvel2.optimizers.AccessorOptimizer; import org.mvel2.optimizers.impl.refl.collection.ArrayCreator; import org.mvel2.optimizers.impl.refl.collection.ExprValueAccessor; import org.mvel2.optimizers.impl.refl.collection.ListCreator; import org.mvel2.optimizers.impl.refl.collection.MapCreator; import org.mvel2.optimizers.impl.refl.nodes.*; import org.mvel2.util.ArrayTools; import static org.mvel2.util.CompilerTools.expectType; import org.mvel2.util.MethodStub; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.*; import static org.mvel2.util.PropertyTools.getFieldOrAccessor; import static org.mvel2.util.PropertyTools.getFieldOrWriteAccessor; import org.mvel2.util.StringAppender; import static java.lang.Integer.parseInt; import java.lang.reflect.*; import static java.lang.reflect.Array.getLength; import java.util.List; import java.util.Map; import java.util.WeakHashMap; public class ReflectiveAccessorOptimizer extends AbstractOptimizer implements AccessorOptimizer { private AccessorNode rootNode; private AccessorNode currNode; private Object ctx; private Object thisRef; private Object val; private VariableResolverFactory variableFactory; private static final int DONE = -1; private static final Object[] EMPTYARG = new Object[0]; private static final Class[] EMPTYCLS = new Class[0]; private boolean first = true; private boolean literal = false; private static final Map REFLECTIVE_ACCESSOR_CACHE = new WeakHashMap(); private Class ingressType; private Class returnType; public ReflectiveAccessorOptimizer() { } public void init() { } private ReflectiveAccessorOptimizer(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory variableFactory) { this.pCtx = pCtx; this.expr = property; this.length = property != null ? property.length : 0; this.ctx = ctx; this.variableFactory = variableFactory; this.thisRef = thisRef; } private static int createSignatureHash(String expr, Object ctx) { if (ctx == null) { return expr.hashCode(); } else { return expr.hashCode() + ctx.getClass().hashCode(); } } public static Object get(String expression, Object ctx) { int hash = createSignatureHash(expression, ctx); Accessor accessor = REFLECTIVE_ACCESSOR_CACHE.get(hash); if (accessor != null) { return accessor.getValue(ctx, null, null); } else { REFLECTIVE_ACCESSOR_CACHE.put(hash, accessor = new ReflectiveAccessorOptimizer() .optimizeAccessor(getCurrentThreadParserContext(), expression.toCharArray(), ctx, null, null, false, null)); return accessor.getValue(ctx, null, null); } } public Accessor optimizeAccessor(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory, boolean root, Class ingressType) { this.rootNode = this.currNode = null; this.start = this.cursor = 0; this.first = true; this.length = (this.expr = property).length; this.ctx = ctx; this.thisRef = thisRef; this.variableFactory = factory; this.ingressType = ingressType; this.pCtx = pCtx; return compileGetChain(); } public Accessor optimizeSetAccessor(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Object value, Class ingressType) { this.rootNode = this.currNode = null; this.start = this.cursor = 0; this.first = true; this.length = (this.expr = property).length; this.ctx = ctx; this.thisRef = thisRef; this.variableFactory = factory; this.ingressType = ingressType; char[] root = null; int split = findLastUnion(); PropertyVerifier verifier = new PropertyVerifier(property, this.pCtx = pCtx); if (split != -1) { root = subset(property, 0, split++); //todo: must use the property verifier. property = subset(property, split, property.length - split); } if (root != null) { this.length = (this.expr = root).length; compileGetChain(); ctx = this.val; } if (ctx == null) { throw new PropertyAccessException("could not access property: " + new String(property) + "; parent is null: " + new String(expr)); } try { this.length = (this.expr = property).length; this.cursor = this.start = 0; skipWhitespace(); if (collection) { int start = cursor; if (cursor == length) throw new PropertyAccessException("unterminated '['"); if (scanTo(']')) throw new PropertyAccessException("unterminated '['"); String ex = new String(property, start, cursor - start); if (ctx instanceof Map) { if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(Map.class)) { propHandlerSet(ex, ctx, Map.class, value); } else { //noinspection unchecked ((Map) ctx).put(eval(ex, ctx, variableFactory), convert(value, returnType = verifier.analyze())); addAccessorNode(new MapAccessorNest(ex, returnType)); } return rootNode; } else if (ctx instanceof List) { if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(List.class)) { propHandlerSet(ex, ctx, List.class, value); } else { //noinspection unchecked ((List) ctx).set(eval(ex, ctx, variableFactory, Integer.class), convert(value, returnType = verifier.analyze())); addAccessorNode(new ListAccessorNest(ex, returnType)); } return rootNode; } else if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(ctx.getClass())) { propHandlerSet(ex, ctx, ctx.getClass(), value); return rootNode; } else if (ctx.getClass().isArray()) { if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(Array.class)) { propHandlerSet(ex, ctx, Array.class, value); } else { //noinspection unchecked Array.set(ctx, eval(ex, ctx, variableFactory, Integer.class), convert(value, getBaseComponentType(ctx.getClass()))); addAccessorNode(new ArrayAccessorNest(ex)); } return rootNode; } else { throw new PropertyAccessException("cannot bind to collection property: " + new String(property) + ": not a recognized collection type: " + ctx.getClass()); } } else if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(ctx.getClass())) { propHandlerSet(new String(property), ctx, ctx.getClass(), value); return rootNode; } String tk = new String(property); if (hasSetListeners()) { notifySetListeners(ctx, tk, variableFactory, value); addAccessorNode(new Notify(tk)); } Member member = getFieldOrWriteAccessor(ctx.getClass(), tk, value == null ? null : ingressType); if (member instanceof Field) { Field fld = (Field) member; if (value != null && !fld.getType().isAssignableFrom(value.getClass())) { if (!canConvert(fld.getType(), value.getClass())) { throw new ConversionException("cannot convert type: " + value.getClass() + ": to " + fld.getType()); } fld.set(ctx, convert(value, fld.getType())); addAccessorNode(new DynamicFieldAccessor(fld)); } else { fld.set(ctx, value); addAccessorNode(new FieldAccessor(fld)); } } else if (member != null) { Method meth = (Method) member; if (value != null && !meth.getParameterTypes()[0].isAssignableFrom(value.getClass())) { if (!canConvert(meth.getParameterTypes()[0], value.getClass())) { throw new ConversionException("cannot convert type: " + value.getClass() + ": to " + meth.getParameterTypes()[0]); } meth.invoke(ctx, convert(value, meth.getParameterTypes()[0])); } else { meth.invoke(ctx, value); } addAccessorNode(new SetterAccessor(meth)); } else if (ctx instanceof Map) { //noinspection unchecked ((Map) ctx).put(tk, value); addAccessorNode(new MapAccessor(tk)); } else { throw new PropertyAccessException("could not access property (" + tk + ") in: " + ingressType.getName()); } } catch (InvocationTargetException e) { throw new PropertyAccessException("could not access property", e); } catch (IllegalAccessException e) { throw new PropertyAccessException("could not access property", e); } return rootNode; } private Accessor compileGetChain() { Object curr = ctx; try { if (!MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING) { while (cursor < length) { switch (nextSubToken()) { case BEAN: curr = getBeanProperty(curr, capture()); break; case METH: curr = getMethod(curr, capture()); break; case COL: curr = getCollectionProperty(curr, capture()); break; case WITH: curr = getWithProperty(curr); break; case DONE: break; } first = false; if (curr != null) returnType = curr.getClass(); if (nullSafe && cursor < length) { if (curr == null) return null; addAccessorNode(new NullSafe()); } } } else { while (cursor < length) { switch (nextSubToken()) { case BEAN: curr = getBeanPropertyAO(curr, capture()); break; case METH: curr = getMethod(curr, capture()); break; case COL: curr = getCollectionPropertyAO(curr, capture()); break; case WITH: curr = getWithProperty(curr); break; case DONE: break; } first = false; if (curr != null) returnType = curr.getClass(); if (nullSafe && cursor < length) { if (curr == null) return null; addAccessorNode(new NullSafe()); } } } val = curr; if (pCtx.isStrictTypeEnforcement()) { this.returnType = new PropertyVerifier(this.expr, pCtx).analyze(); } return rootNode; } catch (InvocationTargetException e) { throw new PropertyAccessException(new String(expr) + ": " + e.getTargetException().getMessage(), e); } catch (IllegalAccessException e) { throw new PropertyAccessException(new String(expr) + ": " + e.getMessage(), e); } catch (IndexOutOfBoundsException e) { throw new PropertyAccessException(new String(expr) + ": array index out of bounds.", e); } catch (CompileException e) { throw e; } catch (NullPointerException e) { throw new PropertyAccessException(new String(expr), e); } catch (Exception e) { throw new CompileException(e.getMessage(), e); } } private void addAccessorNode(AccessorNode an) { if (rootNode == null) rootNode = currNode = an; else { currNode = currNode.setNextNode(an); } } private Object getWithProperty(Object ctx) { String root = new String(expr, 0, cursor - 1).trim(); int start = cursor + 1; cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx); WithAccessor wa = new WithAccessor(root, subset(expr, start, cursor++ - start), ingressType, false); addAccessorNode(wa); return wa.getValue(ctx, thisRef, variableFactory); } private Object getBeanPropertyAO(Object ctx, String property) throws Exception { if (GlobalListenerFactory.hasGetListeners()) { notifyGetListeners(ctx, property, variableFactory); addAccessorNode(new Notify(property)); } if (ctx != null && hasPropertyHandler(ctx.getClass())) return propHandler(property, ctx, ctx.getClass()); return getBeanProperty(ctx, property); } private Object getBeanProperty(Object ctx, String property) throws Exception { if ((currType = !first || pCtx == null ? null : pCtx.getVarOrInputTypeOrNull(property)) == Object.class && !pCtx.isStrongTyping()) { currType = null; } if (first) { if ("this".equals(property)) { addAccessorNode(new ThisValueAccessor()); return this.thisRef; } else if (variableFactory != null && variableFactory.isResolveable(property)) { if (variableFactory.isIndexedFactory() && variableFactory.isTarget(property)) { int idx; addAccessorNode(new IndexedVariableAccessor(idx = variableFactory.variableIndexOf(property))); VariableResolver vr = variableFactory.getIndexedVariableResolver(idx); if (vr == null) { variableFactory.setIndexedVariableResolver(idx, variableFactory.getVariableResolver(property)); } return variableFactory.getIndexedVariableResolver(idx).getValue(); } else { addAccessorNode(new VariableAccessor(property)); return variableFactory.getVariableResolver(property).getValue(); } } } //noinspection unchecked Class cls = (ctx instanceof Class ? ((Class) ctx) : ctx != null ? ctx.getClass() : null); if (hasPropertyHandler(cls)) { PropertyHandlerAccessor acc = new PropertyHandlerAccessor(property, cls, getPropertyHandler(cls)); addAccessorNode(acc); return acc.getValue(ctx, thisRef, variableFactory); } Member member = cls != null ? getFieldOrAccessor(cls, property) : null; Object o; if (member instanceof Method) { try { o = ((Method) member).invoke(ctx, EMPTYARG); if (hasNullPropertyHandler()) { addAccessorNode(new GetterAccessorNH((Method) member, getNullPropertyHandler())); if (o == null) o = getNullPropertyHandler().getProperty(member.getName(), ctx, variableFactory); } else { addAccessorNode(new GetterAccessor((Method) member)); } } catch (IllegalAccessException e) { Method iFaceMeth = determineActualTargetMethod((Method) member); if (iFaceMeth == null) throw new PropertyAccessException("could not access field: " + cls.getName() + "." + property); o = iFaceMeth.invoke(ctx, EMPTYARG); if (hasNullPropertyHandler()) { addAccessorNode(new GetterAccessorNH((Method) member, getNullMethodHandler())); if (o == null) o = getNullMethodHandler().getProperty(member.getName(), ctx, variableFactory); } else { addAccessorNode(new GetterAccessor(iFaceMeth)); } } return o; } else if (member != null) { Field f = (Field) member; if ((f.getModifiers() & Modifier.STATIC) != 0) { o = f.get(null); if (hasNullPropertyHandler()) { addAccessorNode(new StaticVarAccessorNH((Field) member, getNullMethodHandler())); if (o == null) o = getNullMethodHandler().getProperty(member.getName(), ctx, variableFactory); } else { addAccessorNode(new StaticVarAccessor((Field) member)); } } else { o = f.get(ctx); if (hasNullPropertyHandler()) { addAccessorNode(new FieldAccessorNH((Field) member, getNullMethodHandler())); if (o == null) o = getNullMethodHandler().getProperty(member.getName(), ctx, variableFactory); } else { addAccessorNode(new FieldAccessor((Field) member)); } } return o; } else if (ctx instanceof Map && (((Map) ctx).containsKey(property) || nullSafe)) { addAccessorNode(new MapAccessor(property)); return ((Map) ctx).get(property); } else if (ctx != null && "length".equals(property) && ctx.getClass().isArray()) { addAccessorNode(new ArrayLength()); return getLength(ctx); } else if (LITERALS.containsKey(property)) { addAccessorNode(new StaticReferenceAccessor(ctx = LITERALS.get(property))); return ctx; } else { Object tryStaticMethodRef = tryStaticAccess(); if (tryStaticMethodRef != null) { if (tryStaticMethodRef instanceof Class) { addAccessorNode(new StaticReferenceAccessor(tryStaticMethodRef)); return tryStaticMethodRef; } else if (tryStaticMethodRef instanceof Field) { addAccessorNode(new StaticVarAccessor((Field) tryStaticMethodRef)); return ((Field) tryStaticMethodRef).get(null); } else { addAccessorNode(new StaticReferenceAccessor(tryStaticMethodRef)); return tryStaticMethodRef; } } else if (ctx instanceof Class) { Class c = (Class) ctx; for (Method m : c.getMethods()) { if (property.equals(m.getName())) { if (MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) { o = m.invoke(null, EMPTY_OBJ_ARR); if (hasNullMethodHandler()) { addAccessorNode(new MethodAccessorNH(m, new ExecutableStatement[0], getNullMethodHandler())); if (o == null) o = getNullMethodHandler().getProperty(m.getName(), ctx, variableFactory); } else { addAccessorNode(new MethodAccessor(m, new ExecutableStatement[0])); } return o; } else { addAccessorNode(new StaticReferenceAccessor(m)); return m; } } } try { Class subClass = findClass(variableFactory, c.getName() + "$" + property, pCtx); addAccessorNode(new StaticReferenceAccessor(subClass)); return subClass; } catch (ClassNotFoundException cnfe) { // fall through. } } else if (MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) { return getMethod(ctx, property); } throw new PropertyAccessException("could not access: " + property + "; in class: " + (ctx == null ? "null" : ctx.getClass().getName())); } } /** * Handle accessing a property embedded in a collections, map, or array * * @param ctx - * @param prop - * @return - * @throws Exception - */ private Object getCollectionProperty(Object ctx, String prop) throws Exception { if (prop.length() > 0) { ctx = getBeanProperty(ctx, prop); } int start = ++cursor; skipWhitespace(); if (cursor == length) throw new CompileException("unterminated '['"); String item; if (scanTo(']')) throw new CompileException("unterminated '['"); item = new String(expr, start, cursor - start); boolean itemSubExpr = true; Object idx = null; try { idx = parseInt(item); itemSubExpr = false; } catch (Exception e) { // not a number; } ExecutableStatement itemStmt = null; if (itemSubExpr) { idx = (itemStmt = (ExecutableStatement) subCompileExpression(item.toCharArray(), pCtx)).getValue(ctx, thisRef, variableFactory); } ++cursor; if (ctx instanceof Map) { if (itemSubExpr) { addAccessorNode(new MapAccessorNest(itemStmt, null)); } else { addAccessorNode(new MapAccessor(parseInt(item))); } return ((Map) ctx).get(idx); } else if (ctx instanceof List) { if (itemSubExpr) { addAccessorNode(new ListAccessorNest(itemStmt, null)); } else { addAccessorNode(new ListAccessor(parseInt(item))); } return ((List) ctx).get((Integer) idx); } else if (ctx.getClass().isArray()) { if (itemSubExpr) { addAccessorNode(new ArrayAccessorNest(itemStmt)); } else { addAccessorNode(new ArrayAccessor(parseInt(item))); } return Array.get(ctx, (Integer) idx); } else if (ctx instanceof CharSequence) { if (itemSubExpr) { addAccessorNode(new IndexedCharSeqAccessorNest(itemStmt)); } else { addAccessorNode(new IndexedCharSeqAccessor(parseInt(item))); } return ((CharSequence) ctx).charAt((Integer) idx); } else { TypeDescriptor tDescr = new TypeDescriptor(expr, 0); if (tDescr.isArray()) { Class cls = getClassReference((Class) ctx, tDescr, variableFactory, pCtx); rootNode = new StaticReferenceAccessor(cls); return cls; } throw new CompileException("illegal use of []: unknown type: " + ctx.getClass().getName()); } } private Object getCollectionPropertyAO(Object ctx, String prop) throws Exception { if (prop.length() > 0) { ctx = getBeanPropertyAO(ctx, prop); } int start = ++cursor; skipWhitespace(); if (cursor == length) throw new CompileException("unterminated '['"); String item; if (scanTo(']')) throw new CompileException("unterminated '['"); item = new String(expr, start, cursor - start); boolean itemSubExpr = true; Object idx = null; try { idx = parseInt(item); itemSubExpr = false; } catch (Exception e) { // not a number; } ExecutableStatement itemStmt = null; if (itemSubExpr) { idx = (itemStmt = (ExecutableStatement) subCompileExpression(item.toCharArray(), pCtx)).getValue(ctx, thisRef, variableFactory); } ++cursor; if (ctx instanceof Map) { if (hasPropertyHandler(Map.class)) { return propHandler(item, ctx, Map.class); } else { if (itemSubExpr) { addAccessorNode(new MapAccessorNest(itemStmt, null)); } else { addAccessorNode(new MapAccessor(parseInt(item))); } return ((Map) ctx).get(idx); } } else if (ctx instanceof List) { if (hasPropertyHandler(List.class)) { return propHandler(item, ctx, List.class); } else { if (itemSubExpr) { addAccessorNode(new ListAccessorNest(itemStmt, null)); } else { addAccessorNode(new ListAccessor(parseInt(item))); } return ((List) ctx).get((Integer) idx); } } else if (ctx.getClass().isArray()) { if (hasPropertyHandler(Array.class)) { return propHandler(item, ctx, Array.class); } else { if (itemSubExpr) { addAccessorNode(new ArrayAccessorNest(itemStmt)); } else { addAccessorNode(new ArrayAccessor(parseInt(item))); } return Array.get(ctx, (Integer) idx); } } else if (ctx instanceof CharSequence) { if (hasPropertyHandler(CharSequence.class)) { return propHandler(item, ctx, CharSequence.class); } else { if (itemSubExpr) { addAccessorNode(new IndexedCharSeqAccessorNest(itemStmt)); } else { addAccessorNode(new IndexedCharSeqAccessor(parseInt(item))); } return ((CharSequence) ctx).charAt((Integer) idx); } } else { TypeDescriptor tDescr = new TypeDescriptor(expr, 0); if (tDescr.isArray()) { Class cls = getClassReference((Class) ctx, tDescr, variableFactory, pCtx); rootNode = new StaticReferenceAccessor(cls); return cls; } throw new CompileException("illegal use of []: unknown type: " + ctx.getClass().getName()); } } /** * Find an appropriate method, execute it, and return it's response. * * @param ctx - * @param name - * @return - * @throws Exception - */ @SuppressWarnings({"unchecked"}) private Object getMethod(Object ctx, String name) throws Exception { int st = cursor; String tk = cursor != length && expr[cursor] == '(' && ((cursor = balancedCapture(expr, cursor, '(')) - st) > 1 ? new String(expr, st + 1, cursor - st - 1) : ""; cursor++; Object[] args; Class[] argTypes; Accessor[] es; if (tk.length() == 0) { args = ParseTools.EMPTY_OBJ_ARR; argTypes = ParseTools.EMPTY_CLS_ARR; es = null; } else { String[] subtokens = parseParameterList(tk.toCharArray(), 0, -1); es = new ExecutableStatement[subtokens.length]; args = new Object[subtokens.length]; argTypes = new Class[subtokens.length]; for (int i = 0; i < subtokens.length; i++) { args[i] = (es[i] = (ExecutableStatement) subCompileExpression(subtokens[i].toCharArray(), pCtx)) .getValue(this.ctx, thisRef, variableFactory); } if (pCtx.isStrictTypeEnforcement()) { for (int i = 0; i < args.length; i++) { argTypes[i] = es[i].getKnownEgressType(); } } else { for (int i = 0; i < args.length; i++) { if (es[i].getKnownEgressType() == Object.class) { argTypes[i] = args[i] == null ? null : args[i].getClass(); } else { argTypes[i] = es[i].getKnownEgressType(); } } } } if (first && variableFactory != null && variableFactory.isResolveable(name)) { Object ptr = variableFactory.getVariableResolver(name).getValue(); if (ptr instanceof Method) { ctx = ((Method) ptr).getDeclaringClass(); name = ((Method) ptr).getName(); } else if (ptr instanceof MethodStub) { ctx = ((MethodStub) ptr).getClassReference(); name = ((MethodStub) ptr).getMethodName(); } else if (ptr instanceof Function) { Function func = (Function) ptr; if (!name.equals(func.getName())) { getBeanProperty(ctx, name); addAccessorNode(new DynamicFunctionAccessor(es)); } else { addAccessorNode(new FunctionAccessor((Function) ptr, es)); } return ((Function) ptr).call(ctx, thisRef, variableFactory, args); } else { throw new OptimizationFailure("attempt to optimize a method call for a reference that does not point to a method: " + name + " (reference is type: " + (ctx != null ? ctx.getClass().getName() : null) + ")"); } first = false; } if (ctx == null) { throw new PropertyAccessException("unable to access property (null parent): " + name); } /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Class cls = currType != null ? currType : (ctx instanceof Class ? (Class) ctx : ctx.getClass()); currType = null; Method m; Class[] parameterTypes = null; /** * If we have not cached the method then we need to go ahead and try to resolve it. */ /** * Try to find an instance method from the class target. */ if ((m = getBestCandidate(argTypes, name, cls, cls.getMethods(), false)) != null) { parameterTypes = m.getParameterTypes(); } if (m == null) { /** * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods. */ if ((m = getBestCandidate(argTypes, name, cls, cls.getClass().getDeclaredMethods(), false)) != null) { parameterTypes = m.getParameterTypes(); } } if (m == null) { StringAppender errorBuild = new StringAppender(); if ("size".equals(name) && args.length == 0 && cls.isArray()) { addAccessorNode(new ArrayLength()); return getLength(ctx); } for (int i = 0; i < args.length; i++) { errorBuild.append(args[i] != null ? args[i].getClass().getName() : null); if (i < args.length - 1) errorBuild.append(", "); } throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]"); } else { if (es != null) { ExecutableStatement cExpr; for (int i = 0; i < es.length; i++) { cExpr = (ExecutableStatement) es[i]; if (cExpr.getKnownIngressType() == null) { cExpr.setKnownIngressType(parameterTypes[i]); cExpr.computeTypeConversionRule(); } if (!cExpr.isConvertableIngressEgress()) { args[i] = convert(args[i], parameterTypes[i]); } } } else { /** * Coerce any types if required. */ for (int i = 0; i < args.length; i++) args[i] = convert(args[i], parameterTypes[i]); } Object o = getWidenedTarget(m).invoke(ctx, args); if (hasNullMethodHandler()) { addAccessorNode(new MethodAccessorNH(getWidenedTarget(m), (ExecutableStatement[]) es, getNullMethodHandler())); if (o == null) o = getNullMethodHandler().getProperty(m.getName(), ctx, variableFactory); } else { addAccessorNode(new MethodAccessor(getWidenedTarget(m), (ExecutableStatement[]) es)); } /** * return the response. */ return o; } } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) throws Exception { return rootNode.getValue(ctx, elCtx, variableFactory); } private Accessor _getAccessor(Object o, Class type) { if (o instanceof List) { Accessor[] a = new Accessor[((List) o).size()]; int i = 0; for (Object item : (List) o) { a[i++] = _getAccessor(item, type); } returnType = List.class; return new ListCreator(a); } else if (o instanceof Map) { Accessor[] k = new Accessor[((Map) o).size()]; Accessor[] v = new Accessor[k.length]; int i = 0; for (Object item : ((Map) o).keySet()) { k[i] = _getAccessor(item, type); // key v[i++] = _getAccessor(((Map) o).get(item), type); // value } returnType = Map.class; return new MapCreator(k, v); } else if (o instanceof Object[]) { Accessor[] a = new Accessor[((Object[]) o).length]; int i = 0; int dim = 0; if (type != null) { String nm = type.getName(); while (nm.charAt(dim) == '[') dim++; } else { type = Object[].class; dim = 1; } try { Class base = getBaseComponentType(type); Class cls = dim > 1 ? findClass(null, repeatChar('[', dim - 1) + "L" + base.getName() + ";", pCtx) : type; for (Object item : (Object[]) o) { expectType(a[i++] = _getAccessor(item, cls), base, true); } return new ArrayCreator(a, getSubComponentType(type)); } catch (ClassNotFoundException e) { throw new RuntimeException("this error should never throw:" + getBaseComponentType(type).getName(), e); } } else { if (returnType == null) returnType = Object.class; if (type.isArray()) { return new ExprValueAccessor((String) o, type, ctx, variableFactory, pCtx); } else { return new ExprValueAccessor((String) o, Object.class, ctx, variableFactory, pCtx); } } } public Accessor optimizeCollection(ParserContext pCtx, Object o, Class type, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory) { this.returnType = type; this.ctx = ctx; this.variableFactory = factory; this.pCtx = pCtx; Accessor root = _getAccessor(o, returnType); if (property != null && property.length > 0) { return new Union(root, property); } else { return root; } } public Accessor optimizeObjectCreation(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory) { this.length = (this.expr = property).length; this.cursor = 0; this.pCtx = pCtx; try { return compileConstructor(property, ctx, factory); } catch (CompileException e) { throw e; } catch (Exception e) { throw new CompileException("could not create constructor: " + e.getMessage(), e); } } private void setRootNode(AccessorNode rootNode) { this.rootNode = this.currNode = rootNode; } private AccessorNode getRootNode() { return rootNode; } public Object getResultOptPass() { return val; } @SuppressWarnings({"WeakerAccess"}) public AccessorNode compileConstructor(char[] expression, Object ctx, VariableResolverFactory vars) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException { String[] cnsRes = captureContructorAndResidual(expression); String[] constructorParms = parseMethodOrConstructor(cnsRes[0].toCharArray()); if (constructorParms != null) { String s = new String(subset(expression, 0, ArrayTools.findFirst('(', expression))); Class cls = ParseTools.findClass(vars, s, pCtx); ExecutableStatement[] cStmts = new ExecutableStatement[constructorParms.length]; for (int i = 0; i < constructorParms.length; i++) { cStmts[i] = (ExecutableStatement) subCompileExpression(constructorParms[i].toCharArray(), pCtx); } Object[] parms = new Object[constructorParms.length]; for (int i = 0; i < constructorParms.length; i++) { parms[i] = cStmts[i].getValue(ctx, vars); } Constructor cns = getBestConstructorCandidate(parms, cls, pCtx.isStrongTyping()); if (cns == null) { StringBuilder error = new StringBuilder(); for (int i = 0; i < parms.length; i++) { error.append(parms[i].getClass().getName()); if (i + 1 < parms.length) error.append(", "); } throw new CompileException("unable to find constructor: " + cls.getName() + "(" + error.toString() + ")"); } for (int i = 0; i < parms.length; i++) { //noinspection unchecked parms[i] = convert(parms[i], cns.getParameterTypes()[i]); } AccessorNode ca = new ConstructorAccessor(cns, cStmts); if (cnsRes.length > 1) { ReflectiveAccessorOptimizer compiledOptimizer = new ReflectiveAccessorOptimizer(pCtx, cnsRes[1].toCharArray(), cns.newInstance(parms), ctx, vars); compiledOptimizer.ingressType = cns.getDeclaringClass(); compiledOptimizer.setRootNode(ca); compiledOptimizer.compileGetChain(); ca = compiledOptimizer.getRootNode(); this.val = compiledOptimizer.getResultOptPass(); } return ca; } else { Constructor cns = Class.forName(new String(expression), true, Thread.currentThread().getContextClassLoader()) .getConstructor(EMPTYCLS); AccessorNode ca = new ConstructorAccessor(cns, null); if (cnsRes.length > 1) { //noinspection NullArgumentToVariableArgMethod ReflectiveAccessorOptimizer compiledOptimizer = new ReflectiveAccessorOptimizer(getCurrentThreadParserContext(), cnsRes[1].toCharArray(), cns.newInstance(null), ctx, vars); compiledOptimizer.setRootNode(ca); compiledOptimizer.compileGetChain(); ca = compiledOptimizer.getRootNode(); this.val = compiledOptimizer.getResultOptPass(); } return ca; } } public Class getEgressType() { return returnType; } public boolean isLiteralOnly() { return literal; } private Object propHandler(String property, Object ctx, Class handler) { PropertyHandler ph = getPropertyHandler(handler); addAccessorNode(new PropertyHandlerAccessor(property, handler, ph)); return ph.getProperty(property, ctx, variableFactory); } public void propHandlerSet(String property, Object ctx, Class handler, Object value) { PropertyHandler ph = getPropertyHandler(handler); addAccessorNode(new PropertyHandlerAccessor(property, handler, ph)); ph.setProperty(property, ctx, variableFactory, value); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/0000755000175000017500000000000011412747043025061 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/ArrayLength.java0000644000175000017500000000270711077457613030162 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.integration.VariableResolverFactory; import static java.lang.reflect.Array.getLength; /** * @author Christopher Brock */ public class ArrayLength extends BaseAccessor { public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (nextNode != null) { return nextNode.getValue(getLength(ctx), elCtx, variableFactory); } else { return getLength(ctx); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } public Class getKnownEgressType() { return Integer.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/ArrayAccessor.java0000644000175000017500000000421711077457613030501 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Array; public class ArrayAccessor implements AccessorNode { private AccessorNode nextNode; private int index; public ArrayAccessor() { } public ArrayAccessor(int index) { this.index = index; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (nextNode != null) { return nextNode.getValue(Array.get(ctx, index), elCtx, vars); } else { return Array.get(ctx, index); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { if (nextNode != null) { return nextNode.setValue(Array.get(ctx, index), elCtx, variableFactory, value); } else { Array.set(ctx, index, value); return value; } } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return Object[].class; } public String toString() { return "Array Accessor -> [" + index + "]"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/FunctionAccessor.java0000644000175000017500000000376611131071777031212 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.ast.Function; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; public class FunctionAccessor extends BaseAccessor { private Function function; private Accessor[] parameters; public FunctionAccessor(Function function, Accessor[] parms) { this.function = function; this.parameters = parms; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { Object[] parms = null; if (parameters != null && parameters.length != 0) { parms = new Object[parameters.length]; for (int i = 0; i < parms.length; i++) { parms[i] = parameters[i].getValue(ctx, elCtx, variableFactory); } } if (nextNode != null) { return nextNode.getValue(function.call(ctx, elCtx, variableFactory, parms), elCtx, variableFactory); } else { return function.call(ctx, elCtx, variableFactory, parms); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { throw new RuntimeException("can't write to function"); } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/MethodAccessor.java0000644000175000017500000001762711223436064030642 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.AccessorNode; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.getBestCandidate; import static org.mvel2.util.ParseTools.getWidenedTarget; import java.lang.reflect.Method; public class MethodAccessor implements AccessorNode { private AccessorNode nextNode; private Method method; private Class[] parameterTypes; private ExecutableStatement[] parms; private int length; private boolean coercionNeeded = false; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (!coercionNeeded) { try { if (nextNode != null) { return nextNode.getValue(method.invoke(ctx, executeAll(elCtx, vars)), elCtx, vars); } else { return method.invoke(ctx, executeAll(elCtx, vars)); } } catch (IllegalArgumentException e) { if (ctx != null && method.getDeclaringClass() != ctx.getClass()) { Method o = getBestCandidate(parameterTypes, method.getName(), ctx.getClass(), ctx.getClass().getMethods(), true); if (o != null) { return executeOverrideTarget(getWidenedTarget(o), ctx, elCtx, vars); } } coercionNeeded = true; return getValue(ctx, elCtx, vars); } catch (Exception e) { throw new CompileException("cannot invoke method: " + method.getName(), e); } } else { try { if (nextNode != null) { return nextNode.getValue(method.invoke(ctx, executeAndCoerce(parameterTypes, elCtx, vars)), elCtx, vars); } else { return method.invoke(ctx, executeAndCoerce(parameterTypes, elCtx, vars)); } } catch (IllegalArgumentException e) { Object[] vs = executeAndCoerce(parameterTypes, elCtx, vars); Method newMeth; if ((newMeth = getWidenedTarget(getBestCandidate(vs, method.getName(), ctx.getClass(), ctx.getClass().getMethods(), false))) != null) { return executeOverrideTarget(newMeth, ctx, elCtx, vars); } else { throw e; } } catch (Exception e) { throw new CompileException("cannot invoke method: " + method.getName(), e); } } } private Object executeOverrideTarget(Method o, Object ctx, Object elCtx, VariableResolverFactory vars) { if (!coercionNeeded) { try { try { if (nextNode != null) { return nextNode.getValue(o.invoke(ctx, executeAll(elCtx, vars)), elCtx, vars); } else { return o.invoke(ctx, executeAll(elCtx, vars)); } } catch (IllegalArgumentException e) { if (coercionNeeded) throw e; coercionNeeded = true; return executeOverrideTarget(o, ctx, elCtx, vars); } } catch (Exception e2) { throw new CompileException("unable to invoke method", e2); } } else { try { if (nextNode != null) { return nextNode.getValue(o.invoke(ctx, executeAndCoerce(o.getParameterTypes(), elCtx, vars)), elCtx, vars); } else { return o.invoke(ctx, executeAndCoerce(o.getParameterTypes(), elCtx, vars)); } } catch (IllegalAccessException e) { throw new CompileException("unable to invoke method (expected target: " + method.getDeclaringClass().getName() + "::" + method.getName() + "; " + "actual target: " + ctx.getClass().getName() + "::" + method.getName() + "; coercionNeeded=" + (coercionNeeded ? "yes" : "no") + ")"); } catch (Exception e2) { throw new CompileException("unable to invoke method (expected target: " + method.getDeclaringClass().getName() + "::" + method.getName() + "; " + "actual target: " + ctx.getClass().getName() + "::" + method.getName() + "; coercionNeeded=" + (coercionNeeded ? "yes" : "no") + ")"); } } } private Object[] executeAll(Object ctx, VariableResolverFactory vars) { if (length == 0) return GetterAccessor.EMPTY; Object[] vals = new Object[length]; for (int i = 0; i < length; i++) { vals[i] = parms[i].getValue(ctx, vars); } return vals; } private Object[] executeAndCoerce(Class[] target, Object elCtx, VariableResolverFactory vars) { Object[] values = new Object[length]; for (int i = 0; i < length; i++) { //noinspection unchecked values[i] = convert(parms[i].getValue(elCtx, vars), target[i]); } return values; } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; this.length = (this.parameterTypes = this.method.getParameterTypes()).length; } public ExecutableStatement[] getParms() { return parms; } public void setParms(ExecutableStatement[] parms) { this.parms = parms; } public MethodAccessor() { } public MethodAccessor(Method method, ExecutableStatement[] parms) { this.method = method; this.length = (this.parameterTypes = this.method.getParameterTypes()).length; this.parms = parms; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { try { return nextNode.setValue(method.invoke(ctx, executeAll(elCtx, variableFactory)), elCtx, variableFactory, value); } catch (IllegalArgumentException e) { if (ctx != null && method.getDeclaringClass() != ctx.getClass()) { Method o = getBestCandidate(parameterTypes, method.getName(), ctx.getClass(), ctx.getClass().getMethods(), true); if (o != null) { return nextNode.setValue(executeOverrideTarget(o, ctx, elCtx, variableFactory), elCtx, variableFactory, value); } } coercionNeeded = true; return setValue(ctx, elCtx, variableFactory, value); } catch (Exception e) { throw new CompileException("cannot invoke method", e); } } public Class getKnownEgressType() { return method.getReturnType(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/IndexedCharSeqAccessor.java0000644000175000017500000000402511123077476032244 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; public class IndexedCharSeqAccessor implements AccessorNode { private AccessorNode nextNode; private int index; public IndexedCharSeqAccessor() { } public IndexedCharSeqAccessor(int index) { this.index = index; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (nextNode != null) { return nextNode.getValue(((String) ctx).charAt(index), elCtx, vars); } else { return ((String) ctx).charAt(index); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return nextNode.setValue(((String) ctx).charAt(index), elCtx, variableFactory, value); } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public String toString() { return "Array Accessor -> [" + index + "]"; } public Class getKnownEgressType() { return Character.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/ConstructorAccessor.java0000644000175000017500000000714011077457613031746 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Constructor; public class ConstructorAccessor extends BaseAccessor { private Constructor constructor; private Class[] parmTypes; private ExecutableStatement[] parms; private int length; private boolean coercionNeeded = false; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { try { if (!coercionNeeded) { try { if (nextNode != null) { return nextNode.getValue(constructor.newInstance(executeAll(elCtx, variableFactory)), elCtx, variableFactory); } else { return constructor.newInstance(executeAll(elCtx, variableFactory)); } } catch (IllegalArgumentException e) { coercionNeeded = true; return getValue(ctx, elCtx, variableFactory); } } else { if (nextNode != null) { return nextNode.getValue(constructor.newInstance(executeAndCoerce(parmTypes, elCtx, variableFactory)), elCtx, variableFactory); } else { return constructor.newInstance(executeAndCoerce(parmTypes, elCtx, variableFactory)); } } } catch (Exception e) { throw new CompileException("cannot construct object", e); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } private Object[] executeAll(Object ctx, VariableResolverFactory vars) { if (length == 0) return GetterAccessor.EMPTY; Object[] vals = new Object[length]; for (int i = 0; i < length; i++) { vals[i] = parms[i].getValue(ctx, vars); } return vals; } private Object[] executeAndCoerce(Class[] target, Object elCtx, VariableResolverFactory vars) { Object[] values = new Object[length]; for (int i = 0; i < length; i++) { //noinspection unchecked values[i] = convert(parms[i].getValue(elCtx, vars), target[i]); } return values; } public ConstructorAccessor(Constructor constructor, ExecutableStatement[] parms) { this.constructor = constructor; this.length = (this.parmTypes = constructor.getParameterTypes()).length; this.parms = parms; } public Class getKnownEgressType() { return constructor.getClass(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/GetterAccessor.java0000644000175000017500000001203511313753100030631 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.MVEL.getProperty; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ReflectionUtil; import static org.mvel2.util.ParseTools.getBestCandidate; import static org.mvel2.util.ReflectionUtil.getPropertyFromAccessor; import java.lang.reflect.Method; public class GetterAccessor implements AccessorNode { private AccessorNode nextNode; private final Method method; public static final Object[] EMPTY = new Object[0]; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { try { if (nextNode != null) { return nextNode.getValue(method.invoke(ctx, EMPTY), elCtx, vars); } else { return method.invoke(ctx, EMPTY); } } catch (IllegalArgumentException e) { if (ctx != null && method.getDeclaringClass() != ctx.getClass()) { Method o = getBestCandidate(EMPTY, method.getName(), ctx.getClass(), ctx.getClass().getMethods(), true); if (o != null) { return executeOverrideTarget(o, ctx, elCtx, vars); } } /** * HACK: Try to access this another way. */ if (nextNode != null) { return nextNode.getValue(getProperty(getPropertyFromAccessor(method.getName()), ctx), elCtx, vars); } else { return getProperty(getPropertyFromAccessor(method.getName()), ctx); } } catch (NullPointerException e) { if (ctx == null) { throw new CompileException("unable to invoke method: " + method.getDeclaringClass().getName() + "." + method.getName() + ": " + "target of method is null", e); } else { throw new CompileException("cannot invoke getter: " + method.getName() + " (see trace)", e); } } catch (Exception e) { throw new CompileException("cannot invoke getter: " + method.getName() + " [declr.class: " + method.getDeclaringClass().getName() + "; act.class: " + (ctx != null ? ctx.getClass().getName() : "null") + "] (see trace)", e); } } public GetterAccessor(Method method) { this.method = method; } public Method getMethod() { return method; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public AccessorNode getNextNode() { return nextNode; } public String toString() { return method.getDeclaringClass().getName() + "." + method.getName(); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory vars, Object value) { try { if (nextNode != null) { return nextNode.setValue(method.invoke(ctx, EMPTY), elCtx, vars, value); } else { throw new CompileException("bad payload"); } } catch (IllegalArgumentException e) { /** * HACK: Try to access this another way. */ if (nextNode != null) { return nextNode.setValue(getProperty(getPropertyFromAccessor(method.getName()), ctx), elCtx, vars, value); } else { return getProperty(getPropertyFromAccessor(method.getName()), ctx); } } catch (CompileException e) { throw e; } catch (Exception e) { throw new CompileException("error " + method.getName() + ": " + e.getClass().getName() + ":" + e.getMessage(), e); } } public Class getKnownEgressType() { return method.getReturnType(); } private Object executeOverrideTarget(Method o, Object ctx, Object elCtx, VariableResolverFactory vars) { try { if (nextNode != null) { return nextNode.getValue(o.invoke(ctx, EMPTY), elCtx, vars); } else { return o.invoke(ctx, EMPTY); } } catch (Exception e2) { throw new CompileException("unable to invoke method", e2); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/VariableAccessor.java0000644000175000017500000000457011077457613031152 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; public class VariableAccessor implements AccessorNode { private AccessorNode nextNode; private String property; public VariableAccessor(String property) { this.property = property; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vrf) { if (vrf == null) throw new CompileException("cannot access property in optimized accessor: " + property); if (nextNode != null) { return nextNode.getValue(vrf.getVariableResolver(property).getValue(), elCtx, vrf); } else { return vrf.getVariableResolver(property).getValue(); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { if (nextNode != null) { return nextNode.setValue(variableFactory.getVariableResolver(property).getValue(), elCtx, variableFactory, value); } else { variableFactory.getVariableResolver(property).setValue(value); } return value; } public Object getProperty() { return property; } public void setProperty(String property) { this.property = property; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/Union.java0000644000175000017500000000533111123077476027023 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import static org.mvel2.compiler.AbstractParser.getCurrentThreadParserContext; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import org.mvel2.optimizers.OptimizerFactory; /** * @author Christopher Brock */ public class Union implements Accessor { private Accessor accessor; private char[] nextExpr; private Accessor nextAccessor; public Union(Accessor accessor, char[] nextAccessor) { this.accessor = accessor; this.nextExpr = nextAccessor; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (nextAccessor == null) { return get(ctx, elCtx, variableFactory); } else { return nextAccessor.getValue(get(ctx, elCtx, variableFactory), elCtx, variableFactory); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return nextAccessor.setValue(get(ctx, elCtx, variableFactory), elCtx, variableFactory, value); } private Object get(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (nextAccessor == null) { Object o = accessor.getValue(ctx, elCtx, variableFactory); AccessorOptimizer ao = OptimizerFactory.getDefaultAccessorCompiler(); Class ingress = accessor.getKnownEgressType(); nextAccessor = ao.optimizeAccessor(getCurrentThreadParserContext(), nextExpr, o, elCtx, variableFactory, false, ingress); return ao.getResultOptPass(); } else { return accessor.getValue(ctx, elCtx, variableFactory); } } public Class getLeftIngressType() { return accessor.getKnownEgressType(); } public Class getKnownEgressType() { return nextAccessor.getKnownEgressType(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/Notify.java0000644000175000017500000000212211121621456027165 0ustar drazzibdrazzibpackage org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.GlobalListenerFactory; public class Notify implements AccessorNode { private String name; private AccessorNode nextNode; public Notify(String name) { this.name = name; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vrf) { GlobalListenerFactory.notifyGetListeners(ctx, name, vrf); return nextNode.getValue(ctx, elCtx, vrf); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { GlobalListenerFactory.notifySetListeners(ctx, name, variableFactory, value); return nextNode.setValue(ctx, elCtx, variableFactory, value); } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/MapAccessorNest.java0000644000175000017500000000616511077457613030776 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.DataConversion; import org.mvel2.compiler.AccessorNode; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; import java.util.Map; /** * @author Christopher Brock */ public class MapAccessorNest implements AccessorNode { private AccessorNode nextNode; private ExecutableStatement property; private Class conversionType; public MapAccessorNest() { } public MapAccessorNest(ExecutableStatement property, Class conversionType) { this.property = property; this.conversionType = conversionType; } public MapAccessorNest(String property, Class conversionType) { this.property = (ExecutableStatement) subCompileExpression(property.toCharArray()); this.conversionType = conversionType; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vrf) { if (nextNode != null) { return nextNode.getValue(((Map) ctx).get(property.getValue(ctx, elCtx, vrf)), elCtx, vrf); } else { return ((Map) ctx).get(property.getValue(ctx, elCtx, vrf)); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory vars, Object value) { if (nextNode != null) { return nextNode.setValue(((Map) ctx).get(property.getValue(ctx, elCtx, vars)), elCtx, vars, value); } else { if (conversionType != null) { ((Map) ctx).put(property.getValue(ctx, elCtx, vars), value = DataConversion.convert(value, conversionType)); } else { ((Map) ctx).put(property.getValue(ctx, elCtx, vars), value); } return value; } } public ExecutableStatement getProperty() { return property; } public void setProperty(ExecutableStatement property) { this.property = property; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public String toString() { return "Map Accessor -> [" + property + "]"; } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/ThisValueAccessor.java0000644000175000017500000000343511123077476031325 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; public class ThisValueAccessor implements AccessorNode { private AccessorNode nextNode; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (nextNode != null) { return this.nextNode.getValue(elCtx, elCtx, vars); } else { return elCtx; } } public ThisValueAccessor() { } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { if (nextNode == null) throw new CompileException("assignment to reserved variable 'this' not permitted"); return this.nextNode.setValue(elCtx, elCtx, variableFactory, value); } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/GetterAccessorNH.java0000644000175000017500000001131511123062273031062 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.MVEL.getProperty; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.PropertyHandler; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.getBestCandidate; import java.lang.reflect.Method; public class GetterAccessorNH implements AccessorNode { private AccessorNode nextNode; private final Method method; private PropertyHandler nullHandler; public static final Object[] EMPTY = new Object[0]; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { try { return nullHandle(method.getName(), method.invoke(ctx, EMPTY), ctx, elCtx, vars); } catch (IllegalArgumentException e) { if (ctx != null && method.getDeclaringClass() != ctx.getClass()) { Method o = getBestCandidate(EMPTY, method.getName(), ctx.getClass(), ctx.getClass().getMethods(), true); if (o != null) { return executeOverrideTarget(o, ctx, elCtx, vars); } } /** * HACK: Try to access this another way. */ return nullHandle(method.getName(), getProperty(method.getName() + "()", ctx), ctx, elCtx, vars); } catch (Exception e) { throw new CompileException("cannot invoke getter: " + method.getName() + " [declr.class: " + method.getDeclaringClass().getName() + "; act.class: " + (ctx != null ? ctx.getClass().getName() : "null") + "]", e); } } public GetterAccessorNH(Method method, PropertyHandler nullHandler) { this.method = method; this.nullHandler = nullHandler; } public Method getMethod() { return method; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public AccessorNode getNextNode() { return nextNode; } public String toString() { return method.getDeclaringClass().getName() + "." + method.getName(); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory vars, Object value) { try { Object v = method.invoke(ctx, EMPTY); if (v == null) v = nullHandler.getProperty(method.getName(), ctx, vars); return nextNode.setValue(v, elCtx, vars, value); } catch (IllegalArgumentException e) { /** * HACK: Try to access this another way. */ Object v = getProperty(method.getName() + "()", ctx); if (v == null) v = nullHandler.getProperty(method.getName(), ctx, vars); return nextNode.setValue(v, elCtx, vars, value); } catch (CompileException e) { throw e; } catch (Exception e) { throw new CompileException("error " + method.getName() + ": " + e.getClass().getName() + ":" + e.getMessage(), e); } } public Class getKnownEgressType() { return method.getReturnType(); } private Object executeOverrideTarget(Method o, Object ctx, Object elCtx, VariableResolverFactory vars) { try { return nullHandle(o.getName(), o.invoke(ctx, EMPTY), ctx, elCtx, vars); } catch (Exception e2) { throw new CompileException("unable to invoke method", e2); } } private Object nullHandle(String name, Object v, Object ctx, Object elCtx, VariableResolverFactory vars) { if (v != null) { if (nextNode != null) { return nextNode.getValue(v, elCtx, vars); } else { return v; } } else { if (nextNode != null) { return nextNode.getValue(nullHandler.getProperty(name, ctx, vars), elCtx, vars); } else { return nullHandler.getProperty(name, ctx, vars); } } } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/ListAccessor.java0000644000175000017500000000423111077457613030332 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import java.util.List; public class ListAccessor implements AccessorNode { private AccessorNode nextNode; private int index; public ListAccessor() { } public ListAccessor(int index) { this.index = index; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (nextNode != null) { return nextNode.getValue(((List) ctx).get(index), elCtx, vars); } else { return ((List) ctx).get(index); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory vars, Object value) { if (nextNode != null) { return nextNode.setValue(((List) ctx).get(index), elCtx, vars, value); } else { //noinspection unchecked ((List) ctx).set(index, value); return value; } } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public String toString() { return "Array Accessor -> [" + index + "]"; } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/BaseAccessor.java0000644000175000017500000000212711077457613030273 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; public abstract class BaseAccessor implements AccessorNode { protected AccessorNode nextNode; public AccessorNode setNextNode(AccessorNode accessorNode) { return this.nextNode = accessorNode; } public AccessorNode getNextNode() { return this.nextNode; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/StaticVarAccessor.java0000644000175000017500000000453111123077476031317 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import org.mvel2.OptimizationFailure; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Field; public class StaticVarAccessor implements AccessorNode { private AccessorNode nextNode; Field field; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { try { if (nextNode != null) { return nextNode.getValue(field.get(null), elCtx, vars); } else { return field.get(null); } } catch (Exception e) { throw new OptimizationFailure("unable to access static field", e); } } public StaticVarAccessor(Field field) { this.field = field; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { try { if (nextNode == null) { field.set(null, value); } else { return nextNode.setValue(field.get(null), elCtx, variableFactory, value); } } catch (Exception e) { throw new CompileException("error accessing static variable", e); } return value; } public Class getKnownEgressType() { return field.getClass(); } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/SetterAccessor.java0000644000175000017500000000532111167064652030663 0ustar drazzibdrazzibpackage org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.util.ParseTools.getBestCandidate; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Method; public class SetterAccessor implements AccessorNode { private AccessorNode nextNode; private final Method method; private Class targetType; private boolean coercionRequired = false; public static final Object[] EMPTY = new Object[0]; public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { try { if (coercionRequired) { return method.invoke(ctx, convert(value, targetType)); } else { return method.invoke(ctx, value); } } catch (IllegalArgumentException e) { if (ctx != null && method.getDeclaringClass() != ctx.getClass()) { Method o = getBestCandidate(EMPTY, method.getName(), ctx.getClass(), ctx.getClass().getMethods(), true); if (o != null) { return executeOverrideTarget(o, ctx, value); } } if (!coercionRequired) { coercionRequired = true; return setValue(ctx, elCtx, variableFactory, value); } throw new CompileException("unable to bind property", e); } catch (Exception e) { System.out.println("ctx=" + ctx); throw new CompileException("error calling method: " + method.getDeclaringClass().getName() + "." + method.getName(), e); } } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { return null; } public SetterAccessor(Method method) { this.method = method; assert method != null; this.targetType = method.getParameterTypes()[0]; } public Method getMethod() { return method; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public AccessorNode getNextNode() { return nextNode; } public String toString() { return method.getDeclaringClass().getName() + "." + method.getName(); } public Class getKnownEgressType() { return method.getReturnType(); } private Object executeOverrideTarget(Method o, Object ctx, Object value) { try { return o.invoke(ctx, convert(value, targetType)); } catch (Exception e2) { throw new CompileException("unable to invoke method", e2); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/ArrayAccessorNest.java0000644000175000017500000000650011077457613031330 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.AccessorNode; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ParseTools; import java.lang.reflect.Array; public class ArrayAccessorNest implements AccessorNode { private AccessorNode nextNode; private ExecutableStatement index; private Class baseComponentType; private boolean requireConversion; public ArrayAccessorNest() { } public ArrayAccessorNest(String index) { this.index = (ExecutableStatement) ParseTools.subCompileExpression(index.toCharArray()); } public ArrayAccessorNest(ExecutableStatement stmt) { this.index = stmt; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (nextNode != null) { return nextNode.getValue(((Object[]) ctx)[(Integer) index.getValue(ctx, elCtx, vars)], elCtx, vars); } else { return ((Object[]) ctx)[(Integer) index.getValue(ctx, elCtx, vars)]; } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory vars, Object value) { if (nextNode != null) { return nextNode.setValue(((Object[]) ctx)[(Integer) index.getValue(ctx, elCtx, vars)], elCtx, vars, value); } else { if (baseComponentType == null) { baseComponentType = ParseTools.getBaseComponentType(ctx.getClass()); requireConversion = baseComponentType != value.getClass() && !baseComponentType.isAssignableFrom(value.getClass()); } if (requireConversion) { Object o = convert(value, baseComponentType); Array.set(ctx, (Integer) index.getValue(ctx, elCtx, vars), o); return o; } else { Array.set(ctx, (Integer) index.getValue(ctx, elCtx, vars), value); return value; } } } public ExecutableStatement getIndex() { return index; } public void setIndex(ExecutableStatement index) { this.index = index; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return baseComponentType; } public String toString() { return "Array Accessor -> [" + index + "]"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/DynamicSetterAccessor.java0000644000175000017500000000427711123077476032201 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Method; @SuppressWarnings({"unchecked"}) public class DynamicSetterAccessor implements AccessorNode { // private AccessorNode nextNode; private final Method method; private Class targetType; public static final Object[] EMPTY = new Object[0]; public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { try { return method.invoke(ctx, convert(value, targetType)); } catch (Exception e) { throw new CompileException("error binding property", e); } } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { return null; } public DynamicSetterAccessor(Method method) { this.method = method; this.targetType = method.getParameterTypes()[0]; } public Method getMethod() { return method; } public AccessorNode setNextNode(AccessorNode nextNode) { return null; } public AccessorNode getNextNode() { return null; } public String toString() { return method.getDeclaringClass().getName() + "." + method.getName(); } public Class getKnownEgressType() { return targetType; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/MapAccessor.java0000644000175000017500000000430511077457613030136 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import java.util.Map; public class MapAccessor implements AccessorNode { private AccessorNode nextNode; private Object property; public MapAccessor() { } public MapAccessor(Object property) { this.property = property; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vrf) { if (nextNode != null) { return nextNode.getValue(((Map) ctx).get(property), elCtx, vrf); } else { return ((Map) ctx).get(property); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory vars, Object value) { if (nextNode != null) { return nextNode.setValue(((Map) ctx).get(property), elCtx, vars, value); } else { //noinspection unchecked ((Map) ctx).put(property, value); return value; } } public Object getProperty() { return property; } public void setProperty(Object property) { this.property = property; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public String toString() { return "Map Accessor -> [" + property + "]"; } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/IndexedVariableAccessor.java0000644000175000017500000000412411077457613032446 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; public class IndexedVariableAccessor implements AccessorNode { private AccessorNode nextNode; private int register; public IndexedVariableAccessor(int register) { this.register = register; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vrf) { if (nextNode != null) { return nextNode.getValue(vrf.getIndexedVariableResolver(register).getValue(), elCtx, vrf); } else { return vrf.getIndexedVariableResolver(register).getValue(); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { if (nextNode != null) { return nextNode.setValue(variableFactory.getIndexedVariableResolver(register).getValue(), elCtx, variableFactory, value); } else { variableFactory.getIndexedVariableResolver(register).setValue(value); return value; } } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return Object.class; } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/FieldAccessorNH.java0000644000175000017500000000615211123077476030671 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.PropertyHandler; import java.lang.reflect.Field; public class FieldAccessorNH implements AccessorNode { private AccessorNode nextNode; private Field field; private boolean coercionRequired = false; private PropertyHandler nullHandler; public FieldAccessorNH(Field field, PropertyHandler handler) { this.field = field; this.nullHandler = handler; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { try { Object v = field.get(ctx); if (v == null) v = nullHandler.getProperty(field.getName(), elCtx, vars); if (nextNode != null) { return nextNode.getValue(v, elCtx, vars); } else { return v; } } catch (Exception e) { throw new CompileException("unable to access field", e); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { try { if (nextNode != null) { return nextNode.setValue(ctx, elCtx, variableFactory, value); } else if (coercionRequired) { field.set(ctx, value = convert(ctx, field.getClass())); return value; } else { field.set(ctx, value); return value; } } catch (IllegalArgumentException e) { if (!coercionRequired) { coercionRequired = true; return setValue(ctx, elCtx, variableFactory, value); } throw new CompileException("unable to bind property", e); } catch (Exception e) { throw new CompileException("unable to access field", e); } } public Field getField() { return field; } public void setField(Field field) { this.field = field; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return field.getClass(); } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/ListAccessorNest.java0000644000175000017500000000603311077457613031166 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.DataConversion; import org.mvel2.compiler.AccessorNode; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; import java.util.List; public class ListAccessorNest implements AccessorNode { private AccessorNode nextNode; private ExecutableStatement index; private Class conversionType; public ListAccessorNest() { } public ListAccessorNest(String index, Class conversionType) { this.index = (ExecutableStatement) subCompileExpression(index.toCharArray()); this.conversionType = conversionType; } public ListAccessorNest(ExecutableStatement index, Class conversionType) { this.index = index; this.conversionType = conversionType; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (nextNode != null) { return nextNode.getValue(((List) ctx).get((Integer) index.getValue(ctx, elCtx, vars)), elCtx, vars); } else { return ((List) ctx).get((Integer) index.getValue(ctx, elCtx, vars)); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory vars, Object value) { //noinspection unchecked if (nextNode != null) { return nextNode.setValue(((List) ctx).get((Integer) index.getValue(ctx, elCtx, vars)), elCtx, vars, value); } else { if (conversionType != null) { ((List) ctx).set((Integer) index.getValue(ctx, elCtx, vars), value = DataConversion.convert(value, conversionType)); } else { ((List) ctx).set((Integer) index.getValue(ctx, elCtx, vars), value); } return value; } } public ExecutableStatement getIndex() { return index; } public void setIndex(ExecutableStatement index) { this.index = index; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public String toString() { return "Array Accessor -> [" + index + "]"; } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/FieldAccessor.java0000644000175000017500000000611011132723576030434 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Field; public class FieldAccessor implements AccessorNode { private AccessorNode nextNode; private Field field; private boolean coercionRequired = false; public FieldAccessor() { } public FieldAccessor(Field field) { this.field = field; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { try { if (nextNode != null) { return nextNode.getValue(field.get(ctx), elCtx, vars); } else { return field.get(ctx); } } catch (Exception e) { throw new CompileException("unable to access field: " + field.getName(), e); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { if (nextNode != null) { try { return nextNode.setValue(field.get(ctx), elCtx, variableFactory, value); } catch (Exception e) { throw new CompileException("unable to access field", e); } } try { if (coercionRequired) { field.set(ctx, value = convert(ctx, field.getClass())); return value; } else { field.set(ctx, value); return value; } } catch (IllegalArgumentException e) { if (!coercionRequired) { coercionRequired = true; return setValue(ctx, elCtx, variableFactory, value); } throw new CompileException("unable to bind property", e); } catch (Exception e) { throw new CompileException("unable to access field", e); } } public Field getField() { return field; } public void setField(Field field) { this.field = field; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return field.getClass(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/StaticVarAccessorNH.java0000644000175000017500000000513111132723576031541 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import org.mvel2.OptimizationFailure; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.PropertyHandler; import java.lang.reflect.Field; public class StaticVarAccessorNH implements AccessorNode { private AccessorNode nextNode; Field field; private PropertyHandler nullHandler; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { try { Object v = field.get(ctx); if (v == null) v = nullHandler.getProperty(field.getName(), elCtx, vars); if (nextNode != null) { return nextNode.getValue(v, elCtx, vars); } else { return v; } } catch (Exception e) { throw new OptimizationFailure("unable to access static field", e); } } public StaticVarAccessorNH(Field field, PropertyHandler handler) { this.field = field; this.nullHandler = handler; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { try { if (nextNode == null) { field.set(null, value); } else { return nextNode.setValue(field.get(null), elCtx, variableFactory, value); } } catch (Exception e) { throw new CompileException("error accessing static variable", e); } return value; } public Class getKnownEgressType() { return field.getClass(); } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/IndexedCharSeqAccessorNest.java0000644000175000017500000000454211123077476033102 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; public class IndexedCharSeqAccessorNest implements AccessorNode { private AccessorNode nextNode; private ExecutableStatement index; public IndexedCharSeqAccessorNest() { } public IndexedCharSeqAccessorNest(ExecutableStatement index) { this.index = index; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (nextNode != null) { return nextNode.getValue(((String) ctx).charAt((Integer) index.getValue(ctx, elCtx, vars)), elCtx, vars); } else { return ((String) ctx).charAt((Integer) index.getValue(ctx, elCtx, vars)); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return nextNode.setValue(((String) ctx).charAt((Integer) index.getValue(ctx, elCtx, variableFactory)), elCtx, variableFactory, value); } public ExecutableStatement getIndex() { return index; } public void setIndex(ExecutableStatement index) { this.index = index; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public String toString() { return "Array Accessor -> [" + index + "]"; } public Class getKnownEgressType() { return Character.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/MethodAccessorNH.java0000644000175000017500000001251511123077476031066 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import static org.mvel2.DataConversion.convert; import org.mvel2.compiler.AccessorNode; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.PropertyHandler; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.getBestCandidate; import java.lang.reflect.Method; public class MethodAccessorNH implements AccessorNode { private AccessorNode nextNode; private Method method; private Class[] parameterTypes; private ExecutableStatement[] parms; private int length; private boolean coercionNeeded = false; private PropertyHandler nullHandler; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (!coercionNeeded) { try { Object v = method.invoke(ctx, executeAll(elCtx, vars)); if (v == null) nullHandler.getProperty(method.getName(), ctx, vars); if (nextNode != null) { return nextNode.getValue(v, elCtx, vars); } else { return v; } } catch (IllegalArgumentException e) { if (ctx != null && method.getDeclaringClass() != ctx.getClass()) { Method o = getBestCandidate(parameterTypes, method.getName(), ctx.getClass(), ctx.getClass().getMethods(), true); if (o != null) { return executeOverrideTarget(o, ctx, elCtx, vars); } } coercionNeeded = true; return getValue(ctx, elCtx, vars); } catch (Exception e) { throw new CompileException("cannot invoke method", e); } } else { try { if (nextNode != null) { return nextNode.getValue(method.invoke(ctx, executeAndCoerce(parameterTypes, elCtx, vars)), elCtx, vars); } else { return method.invoke(ctx, executeAndCoerce(parameterTypes, elCtx, vars)); } } catch (Exception e) { throw new CompileException("cannot invoke method", e); } } } private Object executeOverrideTarget(Method o, Object ctx, Object elCtx, VariableResolverFactory vars) { try { Object v = o.invoke(ctx, executeAll(elCtx, vars)); if (v == null) v = nullHandler.getProperty(o.getName(), ctx, vars); if (nextNode != null) { return nextNode.getValue(v, elCtx, vars); } else { return v; } } catch (Exception e2) { throw new CompileException("unable to invoke method", e2); } } private Object[] executeAll(Object ctx, VariableResolverFactory vars) { if (length == 0) return GetterAccessor.EMPTY; Object[] vals = new Object[length]; for (int i = 0; i < length; i++) { vals[i] = parms[i].getValue(ctx, vars); } return vals; } private Object[] executeAndCoerce(Class[] target, Object elCtx, VariableResolverFactory vars) { Object[] values = new Object[length]; for (int i = 0; i < length; i++) { //noinspection unchecked values[i] = convert(parms[i].getValue(elCtx, vars), target[i]); } return values; } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; this.length = (this.parameterTypes = this.method.getParameterTypes()).length; } public ExecutableStatement[] getParms() { return parms; } public void setParms(ExecutableStatement[] parms) { this.parms = parms; } public MethodAccessorNH() { } public MethodAccessorNH(Method method, ExecutableStatement[] parms, PropertyHandler handler) { this.method = method; this.length = (this.parameterTypes = this.method.getParameterTypes()).length; this.parms = parms; this.nullHandler = handler; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return nextNode.setValue(ctx, elCtx, variableFactory, value); } public Class getKnownEgressType() { return method.getReturnType(); } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/NullSafe.java0000644000175000017500000000163111121621456027432 0ustar drazzibdrazzibpackage org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; public class NullSafe implements AccessorNode { private AccessorNode nextNode; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (ctx == null) return null; return nextNode.getValue(ctx, elCtx, variableFactory); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { if (ctx == null) return null; return nextNode.setValue(ctx, elCtx, variableFactory, value); } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode accessorNode) { return this.nextNode = accessorNode; } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/DynamicFunctionAccessor.java0000644000175000017500000000377511351236755032522 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.ast.Function; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; public class DynamicFunctionAccessor extends BaseAccessor { // private Function function; private Accessor[] parameters; public DynamicFunctionAccessor(Accessor[] parms) { this.parameters = parms; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { Object[] parms = null; Function function = (Function) ctx; if (parameters != null && parameters.length != 0) { parms = new Object[parameters.length]; for (int i = 0; i < parms.length; i++) { parms[i] = parameters[i].getValue(ctx, elCtx, variableFactory); } } if (nextNode != null) { return nextNode.getValue(function.call(ctx, elCtx, variableFactory, parms), elCtx, variableFactory); } else { return function.call(ctx, elCtx, variableFactory, parms); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { throw new RuntimeException("can't write to function"); } public Class getKnownEgressType() { return Object.class; } }mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/StaticReferenceAccessor.java0000644000175000017500000000363211123077476032466 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; public class StaticReferenceAccessor implements AccessorNode { private AccessorNode nextNode; Object literal; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { if (nextNode != null) { return nextNode.getValue(literal, elCtx, vars); } else { return literal; } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return nextNode.setValue(literal, elCtx, variableFactory, value); } public Object getLiteral() { return literal; } public void setLiteral(Object literal) { this.literal = literal; } public StaticReferenceAccessor() { } public StaticReferenceAccessor(Object literal) { this.literal = literal; } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return literal.getClass(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/PropertyHandlerAccessor.java0000644000175000017500000000367211325411717032540 0ustar drazzibdrazzibpackage org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.integration.PropertyHandler; import org.mvel2.integration.VariableResolverFactory; public class PropertyHandlerAccessor extends BaseAccessor { private String propertyName; private PropertyHandler propertyHandler; private Class conversionType; public PropertyHandlerAccessor(String propertyName, Class conversionType, PropertyHandler propertyHandler) { this.propertyName = propertyName; this.conversionType = conversionType; this.propertyHandler = propertyHandler; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (!conversionType.isAssignableFrom(ctx.getClass())) { if (nextNode != null) { return nextNode.getValue(MVEL.getProperty(propertyName, ctx), elCtx, variableFactory); } else { return MVEL.getProperty(propertyName, ctx); } } try { if (nextNode != null) { return nextNode.getValue(propertyHandler.getProperty(propertyName, ctx, variableFactory), elCtx, variableFactory); } else { return propertyHandler.getProperty(propertyName, ctx, variableFactory); } } catch (Exception e) { throw new CompileException("unable to access field", e); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { if (nextNode != null) { return nextNode.setValue(propertyHandler.getProperty(propertyName, ctx, variableFactory), ctx, variableFactory, value); } else { return propertyHandler.setProperty(propertyName, ctx, variableFactory, value); } } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/WithAccessor.java0000644000175000017500000000760511166613027030332 0ustar drazzibdrazzibpackage org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.MVEL; import static org.mvel2.MVEL.executeSetExpression; import org.mvel2.ParserContext; import org.mvel2.ast.WithNode; import static org.mvel2.compiler.AbstractParser.getCurrentThreadParserContext; import org.mvel2.compiler.AccessorNode; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ParseTools; import org.mvel2.util.PropertyTools; import static org.mvel2.util.PropertyTools.getReturnType; import static org.mvel2.util.ParseTools.subCompileExpression; import java.io.Serializable; public class WithAccessor implements AccessorNode { private AccessorNode nextNode; protected String nestParm; protected ExecutableStatement nestedStatement; protected WithNode.ParmValuePair[] withExpressions; public WithAccessor(String property, char[] block, Class ingressType, boolean strict) { ParserContext pCtx = getCurrentThreadParserContext(); pCtx.setBlockSymbols(true); withExpressions = WithNode.compileWithExpressions(block, property, ingressType, pCtx); // withExpressions = new ExecutablePairs[pvp.length]; // // for (int i = 0; i < pvp.length; i++) { // withExpressions[i] = new ExecutablePairs(pvp[i].getParm(), // (ExecutableStatement) subCompileExpression(pvp[i].getValue().toCharArray()), ingressType, pCtx); // } pCtx.setBlockSymbols(false); } public AccessorNode getNextNode() { return this.nextNode; } public AccessorNode setNextNode(AccessorNode accessorNode) { return this.nextNode = accessorNode; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (this.nextNode == null) { return processWith(ctx, elCtx, variableFactory); } else { return this.nextNode.getValue(processWith(ctx, elCtx, variableFactory), elCtx, variableFactory); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return this.nextNode.setValue(processWith(ctx, elCtx, variableFactory), elCtx, variableFactory, value); } public Object processWith(Object ctx, Object thisValue, VariableResolverFactory factory) { for (WithNode.ParmValuePair pvp : withExpressions) { if (pvp.getSetExpression() != null) { executeSetExpression(pvp.getSetExpression(), ctx, factory, pvp.getStatement().getValue(ctx, thisValue, factory)); } else { pvp.getStatement().getValue(ctx, thisValue, factory); } } return ctx; } public static final class ExecutablePairs implements Serializable { private Serializable setExpression; private ExecutableStatement statement; public ExecutablePairs() { } public ExecutablePairs(String parameter, ExecutableStatement statement, Class ingressType, ParserContext pCtx) { if (parameter != null && parameter.length() != 0) { this.setExpression = MVEL.compileSetExpression(parameter, ingressType != null ? getReturnType(ingressType, parameter, pCtx) : Object.class , getCurrentThreadParserContext()); } this.statement = statement; } public Serializable getSetExpression() { return setExpression; } public void setSetExpression(Serializable setExpression) { this.setExpression = setExpression; } public ExecutableStatement getStatement() { return statement; } public void setStatement(ExecutableStatement statement) { this.statement = statement; } } public Class getKnownEgressType() { return Object.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/refl/nodes/DynamicFieldAccessor.java0000644000175000017500000000510311077457613031746 0ustar drazzibdrazzib/** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.CompileException; import org.mvel2.DataConversion; import org.mvel2.compiler.AccessorNode; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Field; @SuppressWarnings({"unchecked"}) public class DynamicFieldAccessor implements AccessorNode { private AccessorNode nextNode; private Field field; private Class targetType; public DynamicFieldAccessor() { } public DynamicFieldAccessor(Field field) { this.field = field; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory vars) { try { if (nextNode != null) { return nextNode.getValue(field.get(ctx), elCtx, vars); } else { return field.get(ctx); } } catch (Exception e) { throw new CompileException("unable to access field", e); } } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { try { if (nextNode != null) { return nextNode.setValue(field.get(ctx), elCtx, variableFactory, value); } else { field.set(ctx, DataConversion.convert(value, targetType)); return value; } } catch (Exception e) { throw new CompileException("unable to access field", e); } } public Field getField() { return field; } public void setField(Field field) { this.field = field; this.targetType = field.getType(); } public AccessorNode getNextNode() { return nextNode; } public AccessorNode setNextNode(AccessorNode nextNode) { return this.nextNode = nextNode; } public Class getKnownEgressType() { return targetType; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/asm/0000755000175000017500000000000011412747042023600 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/asm/ASMAccessorOptimizer.java0000644000175000017500000034616211363352207030465 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.impl.asm; import org.mvel2.*; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import static org.mvel2.MVEL.eval; import static org.mvel2.MVEL.isAdvancedDebugging; import org.mvel2.asm.ClassWriter; import org.mvel2.asm.Label; import org.mvel2.asm.MethodVisitor; import org.mvel2.asm.Opcodes; import static org.mvel2.asm.Opcodes.*; import static org.mvel2.asm.Type.*; import org.mvel2.ast.Function; import org.mvel2.ast.TypeDescriptor; import static org.mvel2.ast.TypeDescriptor.getClassReference; import org.mvel2.ast.WithNode; import org.mvel2.compiler.*; import org.mvel2.integration.GlobalListenerFactory; import static org.mvel2.integration.GlobalListenerFactory.hasGetListeners; import static org.mvel2.integration.GlobalListenerFactory.notifyGetListeners; import org.mvel2.integration.PropertyHandler; import static org.mvel2.integration.PropertyHandlerFactory.*; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AbstractOptimizer; import org.mvel2.optimizers.AccessorOptimizer; import org.mvel2.optimizers.OptimizationNotSupported; import org.mvel2.optimizers.impl.refl.nodes.Union; import static org.mvel2.util.ArrayTools.findFirst; import org.mvel2.util.*; import static org.mvel2.util.ParseTools.*; import static org.mvel2.util.PropertyTools.getFieldOrAccessor; import static org.mvel2.util.PropertyTools.getFieldOrWriteAccessor; import java.io.FileWriter; import java.io.IOException; import static java.lang.String.valueOf; import static java.lang.System.getProperty; import static java.lang.Thread.currentThread; import java.lang.reflect.*; import static java.lang.reflect.Array.getLength; import static java.lang.reflect.Modifier.FINAL; import static java.lang.reflect.Modifier.STATIC; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Implementation of the MVEL Just-in-Time (JIT) compiler for Property Accessors using the ASM bytecode * engineering library. *

*/ @SuppressWarnings({"TypeParameterExplicitlyExtendsObject", "unchecked", "UnusedDeclaration"}) public class ASMAccessorOptimizer extends AbstractOptimizer implements AccessorOptimizer { private static final String MAP_IMPL = "java/util/HashMap"; private static String LIST_IMPL; private static String NAMESPACE; private static final int OPCODES_VERSION; static { final String javaVersion = getProperty("java.version"); if (javaVersion.startsWith("1.4")) OPCODES_VERSION = Opcodes.V1_4; else if (javaVersion.startsWith("1.5")) OPCODES_VERSION = Opcodes.V1_5; else if (javaVersion.startsWith("1.6") || javaVersion.startsWith("1.7")) OPCODES_VERSION = Opcodes.V1_6; else OPCODES_VERSION = Opcodes.V1_2; String defaultNameSapce = getProperty("mvel2.namespace"); if (defaultNameSapce == null) NAMESPACE = "org/mvel2/"; else NAMESPACE = defaultNameSapce; String jitListImpl = getProperty("mvel2.jit.list_impl"); if (jitListImpl == null) LIST_IMPL = NAMESPACE + "util/FastList"; else LIST_IMPL = jitListImpl; } private Object ctx; private Object thisRef; private VariableResolverFactory variableFactory; private static final Object[] EMPTYARG = new Object[0]; private static final Class[] EMPTYCLS = new Class[0]; private boolean first = true; private boolean noinit = false; private boolean deferFinish = false; private boolean literal = false; private boolean propNull = false; private boolean methNull = false; private String className; private ClassWriter cw; private MethodVisitor mv; private Object val; private int stacksize = 1; private int maxlocals = 1; private long time; private ArrayList compiledInputs; private Class ingressType; private Class returnType; private int compileDepth = 0; @SuppressWarnings({"StringBufferField"}) private StringAppender buildLog; public ASMAccessorOptimizer() { //do this to confirm we're running the correct version //otherwise should create a verification error in VM new ClassWriter(ClassWriter.COMPUTE_MAXS); } private ASMAccessorOptimizer(ClassWriter cw, MethodVisitor mv, ArrayList compiledInputs, String className, StringAppender buildLog, int compileDepth) { this.cw = cw; this.mv = mv; this.compiledInputs = compiledInputs; this.className = className; this.buildLog = buildLog; this.compileDepth = compileDepth + 1; noinit = true; deferFinish = true; } /** * Does all the boilerplate for initiating the JIT. */ private void _initJIT() { if (isAdvancedDebugging()) { buildLog = new StringAppender(); } cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); synchronized (Runtime.getRuntime()) { cw.visit(OPCODES_VERSION, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, className = "ASMAccessorImpl_" + valueOf(cw.hashCode()).replaceAll("\\-", "_") + (System.currentTimeMillis() / 10) + ((int) Math.random() * 100), null, "java/lang/Object", new String[]{NAMESPACE + "compiler/Accessor"}); } MethodVisitor m = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); m.visitCode(); m.visitVarInsn(Opcodes.ALOAD, 0); m.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V"); m.visitInsn(RETURN); m.visitMaxs(1, 1); m.visitEnd(); (mv = cw.visitMethod(ACC_PUBLIC, "getValue", "(Ljava/lang/Object;Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;)Ljava/lang/Object;", null, null)).visitCode(); } private void _initJIT2() { if (isAdvancedDebugging()) { buildLog = new StringAppender(); } cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); synchronized (Runtime.getRuntime()) { cw.visit(OPCODES_VERSION, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, className = "ASMAccessorImpl_" + valueOf(cw.hashCode()).replaceAll("\\-", "_") + (System.currentTimeMillis() / 10) + ((int) Math.random() * 100), null, "java/lang/Object", new String[]{NAMESPACE + "compiler/Accessor"}); } MethodVisitor m = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); m.visitCode(); m.visitVarInsn(Opcodes.ALOAD, 0); m.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V"); m.visitInsn(RETURN); m.visitMaxs(1, 1); m.visitEnd(); (mv = cw.visitMethod(ACC_PUBLIC, "setValue", "(Ljava/lang/Object;Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;Ljava/lang/Object;)Ljava/lang/Object;", null, null)).visitCode(); } public Accessor optimizeAccessor(ParserContext pCtx, char[] property, Object staticContext, Object thisRef, VariableResolverFactory factory, boolean root, Class ingressType) { time = System.currentTimeMillis(); if (compiledInputs == null) compiledInputs = new ArrayList(); start = cursor = 0; this.first = true; this.val = null; this.pCtx = pCtx; this.length = property.length; this.expr = property; this.ctx = staticContext; this.thisRef = thisRef; this.variableFactory = factory; this.ingressType = ingressType; if (!noinit) _initJIT(); return compileAccessor(); } public Accessor optimizeSetAccessor(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory, boolean rootThisRef, Object value, Class ingressType) { this.start = this.cursor = 0; this.first = true; this.ingressType = ingressType; compiledInputs = new ArrayList(); this.pCtx = pCtx; this.length = (this.expr = property).length; this.ctx = ctx; this.thisRef = thisRef; this.variableFactory = factory; char[] root = null; PropertyVerifier verifier = new PropertyVerifier(property, this.pCtx = pCtx); int split = findLastUnion(); if (split != -1) { root = subset(property, 0, split++); property = subset(property, split, property.length - split); } AccessorNode rootAccessor = null; _initJIT2(); if (root != null) { this.length = (this.expr = root).length; // run the compiler but don't finish building. deferFinish = true; noinit = true; compileAccessor(); ctx = this.val; } else { assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } try { this.length = (this.expr = property).length; this.cursor = this.start = 0; skipWhitespace(); if (collection) { int start = cursor; whiteSpaceSkip(); if (cursor == length) throw new PropertyAccessException("unterminated '['"); if (scanTo(']')) throw new PropertyAccessException("unterminated '['"); String ex = new String(property, start, cursor - start); assert debug("CHECKCAST " + ctx.getClass().getName()); mv.visitTypeInsn(CHECKCAST, getInternalName(ctx.getClass())); if (ctx instanceof Map) { if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(Map.class)) { propHandlerByteCodePut(ex, ctx, Map.class, value); } else { //noinspection unchecked ((Map) ctx).put(eval(ex, ctx, variableFactory), convert(value, returnType = verifier.analyze())); writeLiteralOrSubexpression(subCompileExpression(ex.toCharArray(), pCtx)); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); if (value != null & returnType != value.getClass()) { dataConversion(returnType); checkcast(returnType); } assert debug("INVOKEINTERFACE Map.put"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); assert debug("POP"); mv.visitInsn(POP); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); } } else if (ctx instanceof List) { if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(List.class)) { propHandlerByteCodePut(ex, ctx, List.class, value); } else { //noinspection unchecked ((List) ctx).set(eval(ex, ctx, variableFactory, Integer.class), convert(value, returnType = verifier.analyze())); writeLiteralOrSubexpression(subCompileExpression(ex.toCharArray(), pCtx)); unwrapPrimitive(int.class); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); if (value != null & !value.getClass().isAssignableFrom(returnType)) { dataConversion(returnType); checkcast(returnType); } assert debug("INVOKEINTERFACE List.set"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "set", "(ILjava/lang/Object;)Ljava/lang/Object;"); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); } } else if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(ctx.getClass())) { propHandlerByteCodePut(ex, ctx, ctx.getClass(), value); } else if (ctx.getClass().isArray()) { if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(Array.class)) { propHandlerByteCodePut(ex, ctx, Array.class, value); } else { Class type = getBaseComponentType(ctx.getClass()); Object idx = eval(ex, ctx, variableFactory); writeLiteralOrSubexpression(subCompileExpression(ex.toCharArray(), pCtx), int.class); if (!(idx instanceof Integer)) { dataConversion(Integer.class); idx = DataConversion.convert(idx, Integer.class); unwrapPrimitive(int.class); } assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); if (!type.equals(value.getClass())) { dataConversion(type); } if (type.isPrimitive()) wrapPrimitive(type); arrayStore(type); //noinspection unchecked Array.set(ctx, (Integer) idx, convert(value, type)); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); } } else { throw new PropertyAccessException("cannot bind to collection property: " + new String(property) + ": not a recognized collection type: " + ctx.getClass()); } deferFinish = false; noinit = false; _finishJIT(); try { deferFinish = false; return _initializeAccessor(); } catch (Exception e) { throw new CompileException("could not generate accessor", e); } } String tk = new String(property); Member member = getFieldOrWriteAccessor(ctx.getClass(), tk, value == null ? null : ingressType); if (GlobalListenerFactory.hasSetListeners()) { mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(tk); mv.visitVarInsn(ALOAD, 3); mv.visitVarInsn(ALOAD, 4); mv.visitMethodInsn(INVOKESTATIC, NAMESPACE + "integration/GlobalListenerFactory", "notifySetListeners", "(Ljava/lang/Object;Ljava/lang/String;L" + NAMESPACE + "integration/VariableResolverFactory;Ljava/lang/Object;)V"); GlobalListenerFactory.notifySetListeners(ctx, tk, variableFactory, value); } if (member instanceof Field) { assert debug("CHECKCAST " + ctx.getClass().getName()); mv.visitTypeInsn(CHECKCAST, getInternalName(ctx.getClass())); Field fld = (Field) member; assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); assert debug("CHECKCAST " + fld.getType().getName()); mv.visitTypeInsn(CHECKCAST, getInternalName(fld.getType())); if (value != null && !fld.getType().isAssignableFrom(value.getClass())) { if (!canConvert(fld.getType(), value.getClass())) { throw new ConversionException("cannot convert type: " + value.getClass() + ": to " + fld.getType()); } dataConversion(fld.getType()); fld.set(ctx, convert(value, fld.getType())); } else { fld.set(ctx, value); } assert debug("PUTFIELD " + getInternalName(fld.getDeclaringClass()) + "." + tk); mv.visitFieldInsn(PUTFIELD, getInternalName(fld.getDeclaringClass()), tk, getDescriptor(fld.getType())); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); } else if (member != null) { assert debug("CHECKCAST " + getInternalName(ctx.getClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(ctx.getClass())); Method meth = (Method) member; assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); Class targetType = meth.getParameterTypes()[0]; if (value != null && !targetType.isAssignableFrom(value.getClass())) { if (!canConvert(targetType, value.getClass())) { throw new ConversionException("cannot convert type: " + value.getClass() + ": to " + meth.getParameterTypes()[0]); } dataConversion(getWrapperClass(targetType)); if (targetType.isPrimitive()) { unwrapPrimitive(targetType); } else checkcast(targetType); meth.invoke(ctx, convert(value, meth.getParameterTypes()[0])); } else { checkcast(targetType); meth.invoke(ctx, value); } assert debug("INVOKEVIRTUAL " + getInternalName(meth.getDeclaringClass()) + "." + meth.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(meth.getDeclaringClass()), meth.getName(), getMethodDescriptor(meth)); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); } else if (ctx instanceof Map) { assert debug("CHECKCAST " + getInternalName(ctx.getClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(ctx.getClass())); assert debug("LDC '" + tk + "'"); mv.visitLdcInsn(tk); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); assert debug("INVOKEVIRTUAL java/util/HashMap.put"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/util/HashMap", "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); //noinspection unchecked ((Map) ctx).put(tk, value); } else { throw new PropertyAccessException("could not access property (" + tk + ") in: " + ingressType.getName()); } } catch (InvocationTargetException e) { throw new PropertyAccessException("could not access property", e); } catch (IllegalAccessException e) { throw new PropertyAccessException("could not access property", e); } try { deferFinish = false; noinit = false; _finishJIT(); return _initializeAccessor(); } catch (Exception e) { throw new CompileException("could not generate accessor", e); } } private void _finishJIT() { if (deferFinish) return; if (returnType != null && returnType.isPrimitive()) { //noinspection unchecked wrapPrimitive(returnType); } if (returnType == void.class) { assert debug("ACONST_NULL"); mv.visitInsn(ACONST_NULL); } assert debug("ARETURN"); mv.visitInsn(ARETURN); assert debug("\n{METHOD STATS (maxstack=" + stacksize + ")}\n"); mv.visitMaxs(stacksize, maxlocals); mv.visitEnd(); mv = cw.visitMethod(ACC_PUBLIC, "getKnownEgressType", "()Ljava/lang/Class;", null, null); mv.visitCode(); mv.visitLdcInsn(org.mvel2.asm.Type.getType(returnType != null ? returnType : Object.class)); mv.visitInsn(ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); if (propNull) { cw.visitField(ACC_PUBLIC, "nullPropertyHandler", "L" + NAMESPACE + "integration/PropertyHandler;", null, null).visitEnd(); } if (methNull) { cw.visitField(ACC_PUBLIC, "nullMethodHandler", "L" + NAMESPACE + "integration/PropertyHandler;", null, null).visitEnd(); } buildInputs(); if (buildLog != null && buildLog.length() != 0 && expr != null) { mv = cw.visitMethod(ACC_PUBLIC, "toString", "()Ljava/lang/String;", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitLdcInsn(buildLog.toString() + "\n\n## { " + new String(expr) + " }"); mv.visitInsn(ARETURN); Label l1 = new Label(); mv.visitLabel(l1); mv.visitMaxs(1, 1); mv.visitEnd(); } cw.visitEnd(); dumpAdvancedDebugging(); // dump advanced debugging if necessary } private Accessor _initializeAccessor() throws Exception { if (deferFinish) return null; /** * Hot load the class we just generated. */ Class cls = loadClass(className, cw.toByteArray()); assert debug("[MVEL JIT Completed Optimization <<" + (expr != null ? new String(expr) : "") + ">>]::" + cls + " (time: " + (System.currentTimeMillis() - time) + "ms)"); Object o; try { if (compiledInputs.size() == 0) { o = cls.newInstance(); } else { Class[] parms = new Class[compiledInputs.size()]; for (int i = 0; i < compiledInputs.size(); i++) { parms[i] = ExecutableStatement.class; } o = cls.getConstructor(parms).newInstance(compiledInputs.toArray(new ExecutableStatement[compiledInputs.size()])); } if (propNull) cls.getField("nullPropertyHandler").set(o, getNullPropertyHandler()); if (methNull) cls.getField("nullMethodHandler").set(o, getNullMethodHandler()); } catch (VerifyError e) { System.out.println("**** COMPILER BUG! REPORT THIS IMMEDIATELY AT http://jira.codehaus.org/browse/mvel2"); System.out.println("Expression: " + (expr == null ? null : new String(expr))); throw e; } return (Accessor) o; } private Accessor compileAccessor() { assert debug("<>"); Object curr = ctx; try { if (!MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING) { while (cursor < length) { switch (nextSubToken()) { case BEAN: curr = getBeanProperty(curr, capture()); break; case METH: curr = getMethod(curr, capture()); break; case COL: curr = getCollectionProperty(curr, capture()); break; case WITH: curr = getWithProperty(curr); break; } // check to see if a null safety is enabled on this property. if (fields == -1) { if (curr == null) { break; } else { fields = 0; } } first = false; if (nullSafe && cursor < length) { assert debug("DUP"); mv.visitInsn(DUP); Label j = new Label(); assert debug("IFNONNULL : jump"); mv.visitJumpInsn(IFNONNULL, j); assert debug("ARETURN"); mv.visitInsn(ARETURN); assert debug("LABEL:jump"); mv.visitLabel(j); } } } else { while (cursor < length) { switch (nextSubToken()) { case BEAN: curr = getBeanPropertyAO(curr, capture()); break; case METH: curr = getMethod(curr, capture()); break; case COL: curr = getCollectionPropertyAO(curr, capture()); break; case WITH: curr = getWithProperty(curr); break; } // check to see if a null safety is enabled on this property. if (fields == -1) { if (curr == null) { break; } else { fields = 0; } } first = false; if (nullSafe && cursor < length) { assert debug("DUP"); mv.visitInsn(DUP); Label j = new Label(); assert debug("IFNONNULL : jump"); mv.visitJumpInsn(IFNONNULL, j); assert debug("ARETURN"); mv.visitInsn(ARETURN); assert debug("LABEL:jump"); mv.visitLabel(j); } } } val = curr; _finishJIT(); return _initializeAccessor(); } catch (InvocationTargetException e) { throw new PropertyAccessException(new String(expr), e); } catch (IllegalAccessException e) { throw new PropertyAccessException(new String(expr), e); } catch (IndexOutOfBoundsException e) { throw new PropertyAccessException(new String(expr), e); } catch (PropertyAccessException e) { throw new CompileException(e.getMessage(), e); } catch (CompileException e) { throw e; } catch (NullPointerException e) { throw new PropertyAccessException(new String(expr), e); } catch (OptimizationNotSupported e) { throw e; } catch (Exception e) { throw new CompileException(e.getMessage(), e); } } private Object getWithProperty(Object ctx) { assert debug("\n ** ENTER -> {with}"); if (first) { assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); first = false; } String root = new String(expr, 0, cursor - 1).trim(); int start = cursor + 1; cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx); this.returnType = ctx != null ? ctx.getClass() : null; for (WithNode.ParmValuePair aPvp : WithNode.compileWithExpressions(subset(expr, start, cursor++ - start), root, ingressType, pCtx)) { assert debug("DUP"); mv.visitInsn(DUP); assert debug("ASTORE " + (5 + compileDepth) + " (withctx)"); mv.visitVarInsn(ASTORE, 5 + compileDepth); aPvp.eval(ctx, variableFactory); if (aPvp.getSetExpression() == null) { addSubstatement(aPvp.getStatement()); } else { compiledInputs.add((ExecutableStatement) aPvp.getSetExpression()); // load set expression assert debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); assert debug("GETFIELD p" + (compiledInputs.size() - 1)); mv.visitFieldInsn(GETFIELD, className, "p" + (compiledInputs.size() - 1), "L" + NAMESPACE + "compiler/ExecutableStatement;"); // ctx assert debug("ALOAD " + (5 + compileDepth) + "(withctx)"); mv.visitVarInsn(ALOAD, (5 + compileDepth)); // elCtx assert debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); // variable factory assert debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); // the value to set. addSubstatement(aPvp.getStatement()); assert debug("INVOKEINTERFACE Accessor.setValue"); mv.visitMethodInsn(INVOKEINTERFACE, NAMESPACE + "compiler/ExecutableStatement", "setValue", "(Ljava/lang/Object;Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;Ljava/lang/Object;)Ljava/lang/Object;"); assert debug("POP"); mv.visitInsn(POP); } } return ctx; } private Object getBeanPropertyAO(Object ctx, String property) throws IllegalAccessException, InvocationTargetException { if (ctx != null && hasPropertyHandler(ctx.getClass())) { return propHandlerByteCode(property, ctx, ctx.getClass()); } return getBeanProperty(ctx, property); } private Object getBeanProperty(Object ctx, String property) throws IllegalAccessException, InvocationTargetException { assert debug("\n ** ENTER -> {bean: " + property + "; ctx=" + ctx + "}"); if ((currType = !first || pCtx == null ? null : pCtx.getVarOrInputTypeOrNull(property)) == Object.class && !pCtx.isStrongTyping()) { currType = null; } if (returnType != null && returnType.isPrimitive()) { //noinspection unchecked wrapPrimitive(returnType); } Class cls = (ctx instanceof Class ? ((Class) ctx) : ctx != null ? ctx.getClass() : null); if (hasPropertyHandler(cls)) { PropertyHandler prop = getPropertyHandler(cls); if (prop instanceof ProducesBytecode) { ((ProducesBytecode) prop).produceBytecodeGet(mv, property, variableFactory); return prop.getProperty(property, ctx, variableFactory); } else { throw new RuntimeException("unable to compile: custom accessor does not support producing bytecode: " + prop.getClass().getName()); } } Member member = cls != null ? getFieldOrAccessor(cls, property) : null; if (member != null && hasGetListeners()) { mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(member.getName()); mv.visitVarInsn(ALOAD, 3); mv.visitMethodInsn(INVOKESTATIC, NAMESPACE + "integration/GlobalListenerFactory", "notifyGetListeners", "(Ljava/lang/Object;Ljava/lang/String;L" + NAMESPACE + "integration/VariableResolverFactory;)V"); notifyGetListeners(ctx, member.getName(), variableFactory); } if (first) { if ("this".equals(property)) { assert debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); return thisRef; } else if (variableFactory != null && variableFactory.isResolveable(property)) { if (variableFactory.isIndexedFactory() && variableFactory.isTarget(property)) { int idx; try { loadVariableByIndex(idx = variableFactory.variableIndexOf(property)); } catch (Exception e) { throw new OptimizationFailure(property); } return variableFactory.getIndexedVariableResolver(idx).getValue(); } else { try { loadVariableByName(property); } catch (Exception e) { throw new OptimizationFailure("critical error in JIT", e); } return variableFactory.getVariableResolver(property).getValue(); } } else { assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } } if (member instanceof Field) { Object o = ((Field) member).get(ctx); if (((member.getModifiers() & STATIC) != 0)) { // Check if the static field reference is a constant and a primitive. if ((member.getModifiers() & FINAL) != 0 && (o instanceof String || ((Field) member).getType().isPrimitive())) { o = ((Field) member).get(null); assert debug("LDC " + valueOf(o)); mv.visitLdcInsn(o); wrapPrimitive(o.getClass()); if (hasNullPropertyHandler()) { if (o == null) { o = getNullPropertyHandler().getProperty(member.getName(), ctx, variableFactory); } writeOutNullHandler(member, 0); } return o; } else { assert debug("GETSTATIC " + getDescriptor(member.getDeclaringClass()) + "." + member.getName() + "::" + getDescriptor(((Field) member).getType())); mv.visitFieldInsn(GETSTATIC, getInternalName(member.getDeclaringClass()), member.getName(), getDescriptor(returnType = ((Field) member).getType())); } } else { assert debug("CHECKCAST " + getInternalName(cls)); mv.visitTypeInsn(CHECKCAST, getInternalName(cls)); assert debug("GETFIELD " + property + ":" + getDescriptor(((Field) member).getType())); mv.visitFieldInsn(GETFIELD, getInternalName(cls), property, getDescriptor(returnType = ((Field) member) .getType())); } returnType = ((Field) member).getType(); if (hasNullPropertyHandler()) { if (o == null) { o = getNullPropertyHandler().getProperty(member.getName(), ctx, variableFactory); } writeOutNullHandler(member, 0); } return o; } else if (member != null) { Object o; if (first) { assert debug("ALOAD 1 (B)"); mv.visitVarInsn(ALOAD, 1); } try { o = ((Method) member).invoke(ctx, EMPTYARG); if (returnType != member.getDeclaringClass()) { assert debug("CHECKCAST " + getInternalName(member.getDeclaringClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(member.getDeclaringClass())); } returnType = ((Method) member).getReturnType(); assert debug("INVOKEVIRTUAL " + member.getName() + ":" + returnType); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(member.getDeclaringClass()), member.getName(), getMethodDescriptor((Method) member)); } catch (IllegalAccessException e) { Method iFaceMeth = determineActualTargetMethod((Method) member); if (iFaceMeth == null) throw new PropertyAccessException("could not access field: " + cls.getName() + "." + property, e); assert debug("CHECKCAST " + getInternalName(iFaceMeth.getDeclaringClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(iFaceMeth.getDeclaringClass())); returnType = iFaceMeth.getReturnType(); assert debug("INVOKEINTERFACE " + member.getName() + ":" + returnType); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(iFaceMeth.getDeclaringClass()), member.getName(), getMethodDescriptor((Method) member)); o = iFaceMeth.invoke(ctx, EMPTYARG); } if (hasNullPropertyHandler()) { if (o == null) o = getNullPropertyHandler().getProperty(member.getName(), ctx, variableFactory); writeOutNullHandler(member, 0); } return o; } else if (ctx instanceof Map && (((Map) ctx).containsKey(property) || nullSafe)) { assert debug("CHECKCAST java/util/Map"); mv.visitTypeInsn(CHECKCAST, "java/util/Map"); assert debug("LDC: \"" + property + "\""); mv.visitLdcInsn(property); assert debug("INVOKEINTERFACE: get"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); return ((Map) ctx).get(property); } else if (first && "this".equals(property)) { assert debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); // load the thisRef value. return this.thisRef; } else if ("length".equals(property) && ctx.getClass().isArray()) { anyArrayCheck(ctx.getClass()); assert debug("ARRAYLENGTH"); mv.visitInsn(ARRAYLENGTH); wrapPrimitive(int.class); return getLength(ctx); } else if (LITERALS.containsKey(property)) { Object lit = LITERALS.get(property); if (lit instanceof Class) { ldcClassConstant((Class) lit); } return lit; } else { Object ts = tryStaticAccess(); if (ts != null) { if (ts instanceof Class) { ldcClassConstant((Class) ts); return ts; } else if (ts instanceof Method) { writeFunctionPointerStub(((Method) ts).getDeclaringClass(), (Method) ts); return ts; } else { Field f = (Field) ts; if ((f.getModifiers() & FINAL) != 0) { Object finalVal = f.get(null); assert debug("LDC " + valueOf(finalVal)); mv.visitLdcInsn(finalVal); wrapPrimitive(finalVal.getClass()); return finalVal; } else { assert debug("GETSTATIC " + getInternalName(f.getDeclaringClass()) + "." + ((Field) ts).getName() + "::" + getDescriptor(f.getType())); mv.visitFieldInsn(GETSTATIC, getInternalName(f.getDeclaringClass()), f.getName(), getDescriptor(returnType = f.getType())); return f.get(null); } } } else if (ctx instanceof Class) { /** * This is our ugly support for function pointers. This works but needs to be re-thought out at some * point. */ Class c = (Class) ctx; for (Method m : c.getMethods()) { if (property.equals(m.getName())) { if (MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) { assert debug("POP"); mv.visitInsn(POP); assert debug("INVOKESTATIC " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); returnType = m.getReturnType(); return m.invoke(null, EMPTY_OBJ_ARR); } else { writeFunctionPointerStub(c, m); return m; } } } try { Class subClass = findClass(variableFactory, c.getName() + "$" + property, pCtx); ldcClassConstant(subClass); return subClass; } catch (ClassNotFoundException cnfe) { // fall through. } } else if (MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) { return getMethod(ctx, property); } throw new PropertyAccessException("could not access: " + property); } } private void writeFunctionPointerStub(Class c, Method m) { ldcClassConstant(c); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getMethods", "()[Ljava/lang/reflect/Method;"); mv.visitVarInsn(ASTORE, 7); mv.visitInsn(ICONST_0); mv.visitVarInsn(ISTORE, 5); mv.visitVarInsn(ALOAD, 7); mv.visitInsn(ARRAYLENGTH); mv.visitVarInsn(ISTORE, 6); Label l1 = new Label(); mv.visitJumpInsn(GOTO, l1); Label l2 = new Label(); mv.visitLabel(l2); mv.visitVarInsn(ALOAD, 7); mv.visitVarInsn(ILOAD, 5); mv.visitInsn(AALOAD); mv.visitVarInsn(ASTORE, 4); Label l3 = new Label(); mv.visitLabel(l3); mv.visitLdcInsn(m.getName()); mv.visitVarInsn(ALOAD, 4); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/reflect/Method", "getName", "()Ljava/lang/String;"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z"); Label l4 = new Label(); mv.visitJumpInsn(IFEQ, l4); Label l5 = new Label(); mv.visitLabel(l5); mv.visitVarInsn(ALOAD, 4); mv.visitInsn(ARETURN); mv.visitLabel(l4); mv.visitIincInsn(5, 1); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 5); mv.visitVarInsn(ILOAD, 6); mv.visitJumpInsn(IF_ICMPLT, l2); Label l6 = new Label(); mv.visitLabel(l6); mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); deferFinish = true; } private Object getCollectionProperty(Object ctx, String prop) throws IllegalAccessException, InvocationTargetException { if (prop.trim().length() > 0) { ctx = getBeanProperty(ctx, prop); first = false; } assert debug("\n ** ENTER -> {collection:<<" + prop + ">>; ctx=" + ctx + "}"); if (first) { assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } int start = ++cursor; skipWhitespace(); if (cursor == length) throw new CompileException("unterminated '['"); if (scanTo(']')) throw new CompileException("unterminated '['"); String tk = new String(expr, start, cursor - start); assert debug("{collection token: [" + tk + "]}"); ExecutableStatement compiled = (ExecutableStatement) subCompileExpression(tk.toCharArray(), pCtx); Object item = compiled.getValue(ctx, variableFactory); ++cursor; if (ctx instanceof Map) { assert debug("CHECKCAST java/util/Map"); mv.visitTypeInsn(CHECKCAST, "java/util/Map"); Class c = writeLiteralOrSubexpression(compiled); if (c != null && c.isPrimitive()) { wrapPrimitive(c); } assert debug("INVOKEINTERFACE: get"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); return ((Map) ctx).get(item); } else if (ctx instanceof List) { assert debug("CHECKCAST java/util/List"); mv.visitTypeInsn(CHECKCAST, "java/util/List"); writeLiteralOrSubexpression(compiled, int.class); assert debug("INVOKEINTERFACE: java/util/List.get"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;"); return ((List) ctx).get(convert(item, Integer.class)); } else if (ctx.getClass().isArray()) { assert debug("CHECKCAST " + getDescriptor(ctx.getClass())); mv.visitTypeInsn(CHECKCAST, getDescriptor(ctx.getClass())); writeLiteralOrSubexpression(compiled, int.class, item.getClass()); Class cls = getBaseComponentType(ctx.getClass()); if (cls.isPrimitive()) { if (cls == int.class) { assert debug("IALOAD"); mv.visitInsn(IALOAD); } else if (cls == char.class) { assert debug("CALOAD"); mv.visitInsn(CALOAD); } else if (cls == boolean.class) { assert debug("BALOAD"); mv.visitInsn(BALOAD); } else if (cls == double.class) { assert debug("DALOAD"); mv.visitInsn(DALOAD); } else if (cls == float.class) { assert debug("FALOAD"); mv.visitInsn(FALOAD); } else if (cls == short.class) { assert debug("SALOAD"); mv.visitInsn(SALOAD); } else if (cls == long.class) { assert debug("LALOAD"); mv.visitInsn(LALOAD); } else if (cls == byte.class) { assert debug("BALOAD"); mv.visitInsn(BALOAD); } wrapPrimitive(cls); } else { assert debug("AALOAD"); mv.visitInsn(AALOAD); } return Array.get(ctx, convert(item, Integer.class)); } else if (ctx instanceof CharSequence) { assert debug("CHECKCAST java/lang/CharSequence"); mv.visitTypeInsn(CHECKCAST, "java/lang/CharSequence"); if (item instanceof Integer) { intPush((Integer) item); assert debug("INVOKEINTERFACE java/lang/CharSequence.charAt"); mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/CharSequence", "charAt", "(I)C"); wrapPrimitive(char.class); return ((CharSequence) ctx).charAt((Integer) item); } else { writeLiteralOrSubexpression(compiled, Integer.class); unwrapPrimitive(int.class); assert debug("INVOKEINTERFACE java/lang/CharSequence.charAt"); mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/CharSequence", "charAt", "(I)C"); wrapPrimitive(char.class); return ((CharSequence) ctx).charAt(convert(item, Integer.class)); } } else { TypeDescriptor tDescr = new TypeDescriptor(expr, 0); if (tDescr.isArray()) { try { Class cls = getClassReference((Class) ctx, tDescr, variableFactory, pCtx); // rootNode = new StaticReferenceAccessor(cls); ldcClassConstant(cls); return cls; } catch (Exception e) { //fall through } } throw new CompileException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName())); } } private Object getCollectionPropertyAO(Object ctx, String prop) throws IllegalAccessException, InvocationTargetException { if (prop.length() > 0) { ctx = getBeanProperty(ctx, prop); first = false; } assert debug("\n ** ENTER -> {collection:<<" + prop + ">>; ctx=" + ctx + "}"); int start = ++cursor; skipWhitespace(); if (cursor == length) throw new CompileException("unterminated '['"); if (scanTo(']')) throw new CompileException("unterminated '['"); String tk = new String(expr, start, cursor - start); assert debug("{collection token:<<" + tk + ">>}"); ExecutableStatement compiled = (ExecutableStatement) subCompileExpression(tk.toCharArray()); Object item = compiled.getValue(ctx, variableFactory); ++cursor; if (ctx instanceof Map) { if (hasPropertyHandler(Map.class)) { return propHandlerByteCode(tk, ctx, Map.class); } else { if (first) { assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } assert debug("CHECKCAST java/util/Map"); mv.visitTypeInsn(CHECKCAST, "java/util/Map"); Class c = writeLiteralOrSubexpression(compiled); if (c != null && c.isPrimitive()) { wrapPrimitive(c); } assert debug("INVOKEINTERFACE: Map.get"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;"); } return ((Map) ctx).get(item); } else if (ctx instanceof List) { if (hasPropertyHandler(List.class)) { return propHandlerByteCode(tk, ctx, List.class); } else { if (first) { assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } assert debug("CHECKCAST java/util/List"); mv.visitTypeInsn(CHECKCAST, "java/util/List"); writeLiteralOrSubexpression(compiled, int.class); assert debug("INVOKEINTERFACE: java/util/List.get"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;"); return ((List) ctx).get(convert(item, Integer.class)); } } else if (ctx.getClass().isArray()) { if (hasPropertyHandler(Array.class)) { return propHandlerByteCode(tk, ctx, Array.class); } else { if (first) { assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } assert debug("CHECKCAST " + getDescriptor(ctx.getClass())); mv.visitTypeInsn(CHECKCAST, getDescriptor(ctx.getClass())); writeLiteralOrSubexpression(compiled, int.class, item.getClass()); Class cls = getBaseComponentType(ctx.getClass()); if (cls.isPrimitive()) { if (cls == int.class) { assert debug("IALOAD"); mv.visitInsn(IALOAD); } else if (cls == char.class) { assert debug("CALOAD"); mv.visitInsn(CALOAD); } else if (cls == boolean.class) { assert debug("BALOAD"); mv.visitInsn(BALOAD); } else if (cls == double.class) { assert debug("DALOAD"); mv.visitInsn(DALOAD); } else if (cls == float.class) { assert debug("FALOAD"); mv.visitInsn(FALOAD); } else if (cls == short.class) { assert debug("SALOAD"); mv.visitInsn(SALOAD); } else if (cls == long.class) { assert debug("LALOAD"); mv.visitInsn(LALOAD); } else if (cls == byte.class) { assert debug("BALOAD"); mv.visitInsn(BALOAD); } wrapPrimitive(cls); } else { assert debug("AALOAD"); mv.visitInsn(AALOAD); } return Array.get(ctx, convert(item, Integer.class)); } } else if (ctx instanceof CharSequence) { if (hasPropertyHandler(CharSequence.class)) { return propHandlerByteCode(tk, ctx, CharSequence.class); } else { if (first) { assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); } assert debug("CHECKCAST java/lang/CharSequence"); mv.visitTypeInsn(CHECKCAST, "java/lang/CharSequence"); if (item instanceof Integer) { intPush((Integer) item); assert debug("INVOKEINTERFACE java/lang/CharSequence.charAt"); mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/CharSequence", "charAt", "(I)C"); wrapPrimitive(char.class); return ((CharSequence) ctx).charAt((Integer) item); } else { writeLiteralOrSubexpression(compiled, Integer.class); unwrapPrimitive(int.class); assert debug("INVOKEINTERFACE java/lang/CharSequence.charAt"); mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/CharSequence", "charAt", "(I)C"); wrapPrimitive(char.class); return ((CharSequence) ctx).charAt(convert(item, Integer.class)); } } } else { TypeDescriptor tDescr = new TypeDescriptor(expr, 0); if (tDescr.isArray()) { try { Class cls = getClassReference((Class) ctx, tDescr, variableFactory, pCtx); // rootNode = new StaticReferenceAccessor(cls); ldcClassConstant(cls); return cls; } catch (Exception e) { //fall through } } throw new CompileException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName())); } } @SuppressWarnings({"unchecked"}) private Object getMethod(Object ctx, String name) throws IllegalAccessException, InvocationTargetException { assert debug("\n ** {method: " + name + "}"); int st = cursor; String tk = cursor != length && expr[cursor] == '(' && ((cursor = balancedCapture(expr, cursor, '(')) - st) > 1 ? new String(expr, st + 1, cursor - st - 1) : ""; cursor++; Object[] preConvArgs; Object[] args; Class[] argTypes; ExecutableStatement[] es; if (tk.length() == 0) { args = preConvArgs = ParseTools.EMPTY_OBJ_ARR; argTypes = ParseTools.EMPTY_CLS_ARR; es = null; } else { String[] subtokens = parseParameterList(tk.toCharArray(), 0, -1); es = new ExecutableStatement[subtokens.length]; args = new Object[subtokens.length]; argTypes = new Class[subtokens.length]; preConvArgs = new Object[es.length]; for (int i = 0; i < subtokens.length; i++) { assert debug("subtoken[" + i + "] { " + subtokens[i] + " }"); preConvArgs[i] = args[i] = (es[i] = (ExecutableStatement) subCompileExpression(subtokens[i].toCharArray(), pCtx)) .getValue(this.ctx, this.thisRef, variableFactory); } if (pCtx.isStrictTypeEnforcement()) { for (int i = 0; i < args.length; i++) { argTypes[i] = es[i].getKnownEgressType(); } } else { for (int i = 0; i < args.length; i++) { if (es[i].getKnownEgressType() == Object.class) { argTypes[i] = args[i] == null ? null : args[i].getClass(); } else { argTypes[i] = es[i].getKnownEgressType(); } } } } if (first && variableFactory != null && variableFactory.isResolveable(name)) { Object ptr = variableFactory.getVariableResolver(name).getValue(); if (ptr instanceof Method) { ctx = ((Method) ptr).getDeclaringClass(); name = ((Method) ptr).getName(); } else if (ptr instanceof MethodStub) { ctx = ((MethodStub) ptr).getClassReference(); name = ((MethodStub) ptr).getMethodName(); } else if (ptr instanceof Function) { if (es != null && es.length != 0) { compiledInputs.addAll(Arrays.asList(es)); intPush(es.length); assert debug("ANEWARRAY [" + es.length + "]"); mv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); assert debug("ASTORE 4"); mv.visitVarInsn(ASTORE, 4); for (int i = 0; i < es.length; i++) { assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); intPush(i); loadField(i); assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); assert debug("ALOAD 3"); mv.visitIntInsn(ALOAD, 3); assert debug("INVOKEINTERFACE ExecutableStatement.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, NAMESPACE + "compiler/ExecutableStatement", "getValue", "(Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;)Ljava/lang/Object;"); assert debug("AASTORE"); mv.visitInsn(AASTORE); } } else { assert debug("ACONST_NULL"); mv.visitInsn(ACONST_NULL); assert debug("CHECKCAST java/lang/Object"); mv.visitTypeInsn(CHECKCAST, "[Ljava/lang/Object;"); assert debug("ASTORE 4"); mv.visitVarInsn(ASTORE, 4); } if (variableFactory.isIndexedFactory() && variableFactory.isTarget(name)) { loadVariableByIndex(variableFactory.variableIndexOf(name)); } else { loadVariableByName(name); } checkcast(Function.class); assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); assert debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); assert debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); assert debug("ALOAD 4"); mv.visitVarInsn(ALOAD, 4); assert debug("INVOKEVIRTUAL Function.call"); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(Function.class), "call", "(Ljava/lang/Object;Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;[Ljava/lang/Object;)Ljava/lang/Object;"); return ((Function) ptr).call(ctx, thisRef, variableFactory, args); } else { throw new OptimizationFailure("attempt to optimize a method call for a reference that does not point to a method: " + name + " (reference is type: " + (ctx != null ? ctx.getClass().getName() : null) + ")"); } first = false; } else if (returnType != null && returnType.isPrimitive()) { //noinspection unchecked wrapPrimitive(returnType); } int inputsOffset = compiledInputs.size(); if (es != null) { for (ExecutableStatement e : es) { if (e instanceof ExecutableLiteral) { continue; } compiledInputs.add(e); } } if (first) { assert debug("ALOAD 1 (D) "); mv.visitVarInsn(ALOAD, 1); } /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Class cls = currType != null ? currType : (ctx instanceof Class ? (Class) ctx : ctx.getClass()); currType = null; Method m; Class[] parameterTypes = null; /** * Try to find an instance method from the class target. */ if ((m = getBestCandidate(argTypes, name, cls, cls.getMethods(), false)) != null) { parameterTypes = m.getParameterTypes(); } if (m == null) { /** * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods. */ if ((m = getBestCandidate(argTypes, name, cls, cls.getClass().getDeclaredMethods(), false)) != null) { parameterTypes = m.getParameterTypes(); } } if (m == null) { StringAppender errorBuild = new StringAppender(); if (parameterTypes != null) { for (int i = 0; i < args.length; i++) { errorBuild.append(parameterTypes[i] != null ? parameterTypes[i].getClass().getName() : null); if (i < args.length - 1) errorBuild.append(", "); } } if ("size".equals(name) && args.length == 0 && cls.isArray()) { anyArrayCheck(cls); assert debug("ARRAYLENGTH"); mv.visitInsn(ARRAYLENGTH); wrapPrimitive(int.class); return getLength(ctx); } throw new CompileException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]"); } else { m = getWidenedTarget(m); if (es != null) { ExecutableStatement cExpr; for (int i = 0; i < es.length; i++) { if ((cExpr = es[i]).getKnownIngressType() == null) { cExpr.setKnownIngressType(parameterTypes[i]); cExpr.computeTypeConversionRule(); } if (!cExpr.isConvertableIngressEgress()) { args[i] = convert(args[i], parameterTypes[i]); } } } else { /** * Coerce any types if required. */ for (int i = 0; i < args.length; i++) { args[i] = convert(args[i], parameterTypes[i]); } } if (m.getParameterTypes().length == 0) { if ((m.getModifiers() & STATIC) != 0) { assert debug("INVOKESTATIC " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { assert debug("CHECKCAST " + getInternalName(m.getDeclaringClass())); mv.visitTypeInsn(CHECKCAST, getInternalName(m.getDeclaringClass())); if (m.getDeclaringClass().isInterface()) { assert debug("INVOKEINTERFACE " + m.getName()); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { assert debug("INVOKEVIRTUAL " + m.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } } returnType = m.getReturnType(); stacksize++; } else { if ((m.getModifiers() & STATIC) == 0) { assert debug("CHECKCAST " + getInternalName(cls)); mv.visitTypeInsn(CHECKCAST, getInternalName(cls)); } for (int i = 0; i < es.length; i++) { if (es[i] instanceof ExecutableLiteral) { ExecutableLiteral literal = (ExecutableLiteral) es[i]; if (literal.getLiteral() == null) { assert debug("ICONST_NULL"); mv.visitInsn(ACONST_NULL); continue; } else if (parameterTypes[i] == int.class && literal.intOptimized()) { intPush(literal.getInteger32()); continue; } else if (parameterTypes[i] == int.class && preConvArgs[i] instanceof Integer) { intPush((Integer) preConvArgs[i]); continue; } else if (parameterTypes[i] == boolean.class) { boolean bool = DataConversion.convert(literal.getLiteral(), Boolean.class); assert debug(bool ? "ICONST_1" : "ICONST_0"); mv.visitInsn(bool ? ICONST_1 : ICONST_0); continue; } else { Object lit = literal.getLiteral(); if (parameterTypes[i] == Object.class) { if (isPrimitiveWrapper(lit.getClass())) { if (lit.getClass() == Integer.class) { intPush((Integer) lit); } else { assert debug("LDC " + lit); mv.visitLdcInsn(lit); } wrapPrimitive(lit.getClass()); } else if (lit instanceof String) { mv.visitLdcInsn(lit); checkcast(Object.class); } continue; } else if (canConvert(parameterTypes[i], lit.getClass())) { Object c = convert(lit, parameterTypes[i]); if (c instanceof Class) { ldcClassConstant((Class) c); } else { assert debug("LDC " + lit + " (" + lit.getClass().getName() + ")"); mv.visitLdcInsn(convert(lit, parameterTypes[i])); if (isPrimitiveWrapper(parameterTypes[i])) { wrapPrimitive(lit.getClass()); } } continue; } } } assert debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); assert debug("GETFIELD p" + inputsOffset); mv.visitFieldInsn(GETFIELD, className, "p" + inputsOffset, "L" + NAMESPACE + "compiler/ExecutableStatement;"); inputsOffset++; assert debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); assert debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); assert debug("INVOKEINTERFACE ExecutableStatement.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(ExecutableStatement.class), "getValue", "(Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;)Ljava/lang/Object;"); if (parameterTypes[i].isPrimitive()) { if (preConvArgs[i] == null || (parameterTypes[i] != String.class && !parameterTypes[i].isAssignableFrom(preConvArgs[i].getClass()))) { ldcClassConstant(getWrapperClass(parameterTypes[i])); assert debug("INVOKESTATIC DataConversion.convert"); mv.visitMethodInsn(INVOKESTATIC, NAMESPACE + "DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;"); } unwrapPrimitive(parameterTypes[i]); } else if (preConvArgs[i] == null || (parameterTypes[i] != String.class && !parameterTypes[i].isAssignableFrom(preConvArgs[i].getClass()))) { ldcClassConstant(parameterTypes[i]); assert debug("INVOKESTATIC DataConversion.convert"); mv.visitMethodInsn(INVOKESTATIC, NAMESPACE + "DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;"); assert debug("CHECKCAST " + getInternalName(parameterTypes[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(parameterTypes[i])); } else if (parameterTypes[i] == String.class) { assert debug("<<>"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;"); } else { assert debug("<<>>"); assert debug("<<>>"); assert debug("CHECKCAST " + getInternalName(parameterTypes[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(parameterTypes[i])); } } if ((m.getModifiers() & STATIC) != 0) { assert debug("INVOKESTATIC: " + m.getName()); mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { if (m.getDeclaringClass().isInterface() && (m.getDeclaringClass() != cls || (ctx != null && ctx.getClass() != m.getDeclaringClass()))) { assert debug("INVOKEINTERFACE: " + getInternalName(m.getDeclaringClass()) + "." + m.getName()); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m)); } else { assert debug("INVOKEVIRTUAL: " + getInternalName(cls) + "." + m.getName()); mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(cls), m.getName(), getMethodDescriptor(m)); } } returnType = m.getReturnType(); stacksize++; } Object o = m.invoke(ctx, args); if (hasNullMethodHandler()) { writeOutNullHandler(m, 1); if (o == null) o = getNullMethodHandler().getProperty(m.getName(), ctx, variableFactory); } return o; } } private void dataConversion(Class target) { if (target.equals(Object.class)) return; ldcClassConstant(target); assert debug("INVOKESTATIC " + NAMESPACE + "DataConversion.convert"); mv.visitMethodInsn(INVOKESTATIC, NAMESPACE + "DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;"); } private static MVELClassLoader classLoader; public static void setMVELClassLoader(MVELClassLoader cl) { classLoader = cl; } public static MVELClassLoader getMVELClassLoader() { return classLoader; } public void init() { try { classLoader = new JITClassLoader(currentThread().getContextClassLoader()); } catch (Exception e) { throw new RuntimeException(e); } } private java.lang.Class loadClass(String className, byte[] b) throws Exception { /** * This must be synchronized. Two classes cannot be simultaneously deployed in the JVM. */ return classLoader.defineClassX(className, b, 0, b.length); } private boolean debug(String instruction) { if (buildLog != null) { buildLog.append(instruction).append("\n"); } return true; } @SuppressWarnings({"SameReturnValue"}) public String getName() { return "ASM"; } public Object getResultOptPass() { return val; } private Class getWrapperClass(Class cls) { if (cls == boolean.class) { return Boolean.class; } else if (cls == int.class) { return Integer.class; } else if (cls == float.class) { return Float.class; } else if (cls == double.class) { return Double.class; } else if (cls == short.class) { return Short.class; } else if (cls == long.class) { return Long.class; } else if (cls == byte.class) { return Byte.class; } else if (cls == char.class) { return Character.class; } return cls; } private void unwrapPrimitive(Class cls) { if (cls == boolean.class) { assert debug("CHECKCAST java/lang/Boolean"); mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean"); assert debug("INVOKEVIRTUAL java/lang/Boolean.booleanValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"); } else if (cls == int.class) { assert debug("CHECKCAST java/lang/Integer"); mv.visitTypeInsn(CHECKCAST, "java/lang/Integer"); assert debug("INVOKEVIRTUAL java/lang/Integer.intValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I"); } else if (cls == float.class) { assert debug("CHECKCAST java/lang/Float"); mv.visitTypeInsn(CHECKCAST, "java/lang/Float"); assert debug("INVOKEVIRTUAL java/lang/Float.floatValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F"); } else if (cls == double.class) { assert debug("CHECKCAST java/lang/Double"); mv.visitTypeInsn(CHECKCAST, "java/lang/Double"); assert debug("INVOKEVIRTUAL java/lang/Double.doubleValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D"); } else if (cls == short.class) { assert debug("CHECKCAST java/lang/Short"); mv.visitTypeInsn(CHECKCAST, "java/lang/Short"); assert debug("INVOKEVIRTUAL java/lang/Short.shortValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S"); } else if (cls == long.class) { assert debug("CHECKCAST java/lang/Long"); mv.visitTypeInsn(CHECKCAST, "java/lang/Long"); assert debug("INVOKEVIRTUAL java/lang/Long.longValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J"); } else if (cls == byte.class) { assert debug("CHECKCAST java/lang/Byte"); mv.visitTypeInsn(CHECKCAST, "java/lang/Byte"); assert debug("INVOKEVIRTUAL java/lang/Byte.byteValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B"); } else if (cls == char.class) { assert debug("CHECKCAST java/lang/Character"); mv.visitTypeInsn(CHECKCAST, "java/lang/Character"); assert debug("INVOKEVIRTUAL java/lang/Character.charValue"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C"); } } private void wrapPrimitive(Class cls) { if (OPCODES_VERSION == Opcodes.V1_4) { /** * JAVA 1.4 SUCKS! DIE 1.4 DIE!!! */ debug("** Using 1.4 Bytecode **"); if (cls == boolean.class || cls == Boolean.class) { debug("NEW java/lang/Boolean"); mv.visitTypeInsn(NEW, "java/lang/Boolean"); debug("DUP X1"); mv.visitInsn(DUP_X1); debug("SWAP"); mv.visitInsn(SWAP); debug("INVOKESPECIAL java/lang/Boolean.::(Z)V"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Boolean", "", "(Z)V"); } else if (cls == int.class || cls == Integer.class) { debug("NEW java/lang/Integer"); mv.visitTypeInsn(NEW, "java/lang/Integer"); debug("DUP X1"); mv.visitInsn(DUP_X1); debug("SWAP"); mv.visitInsn(SWAP); debug("INVOKESPECIAL java/lang/Integer.::(I)V"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Integer", "", "(I)V"); } else if (cls == float.class || cls == Float.class) { debug("NEW java/lang/Float"); mv.visitTypeInsn(NEW, "java/lang/Float"); debug("DUP X1"); mv.visitInsn(DUP_X1); debug("SWAP"); mv.visitInsn(SWAP); debug("INVOKESPECIAL java/lang/Float.::(F)V"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Float", "", "(F)V"); } else if (cls == double.class || cls == Double.class) { debug("NEW java/lang/Double"); mv.visitTypeInsn(NEW, "java/lang/Double"); debug("DUP X2"); mv.visitInsn(DUP_X2); debug("DUP X2"); mv.visitInsn(DUP_X2); debug("POP"); mv.visitInsn(POP); debug("INVOKESPECIAL java/lang/Double.::(D)V"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Double", "", "(D)V"); } else if (cls == short.class || cls == Short.class) { debug("NEW java/lang/Short"); mv.visitTypeInsn(NEW, "java/lang/Short"); debug("DUP X1"); mv.visitInsn(DUP_X1); debug("SWAP"); mv.visitInsn(SWAP); debug("INVOKESPECIAL java/lang/Short.::(S)V"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Short", "", "(S)V"); } else if (cls == long.class || cls == Long.class) { debug("NEW java/lang/Long"); mv.visitTypeInsn(NEW, "java/lang/Long"); debug("DUP X1"); mv.visitInsn(DUP_X1); debug("SWAP"); mv.visitInsn(SWAP); debug("INVOKESPECIAL java/lang/Long.::(L)V"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Float", "", "(L)V"); } else if (cls == byte.class || cls == Byte.class) { debug("NEW java/lang/Byte"); mv.visitTypeInsn(NEW, "java/lang/Byte"); debug("DUP X1"); mv.visitInsn(DUP_X1); debug("SWAP"); mv.visitInsn(SWAP); debug("INVOKESPECIAL java/lang/Byte.::(B)V"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Byte", "", "(B)V"); } else if (cls == char.class || cls == Character.class) { debug("NEW java/lang/Character"); mv.visitTypeInsn(NEW, "java/lang/Character"); debug("DUP X1"); mv.visitInsn(DUP_X1); debug("SWAP"); mv.visitInsn(SWAP); debug("INVOKESPECIAL java/lang/Character.::(C)V"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Character", "", "(C)V"); } } else { if (cls == boolean.class || cls == Boolean.class) { debug("INVOKESTATIC java/lang/Boolean.valueOf"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); } else if (cls == int.class || cls == Integer.class) { debug("INVOKESTATIC java/lang/Integer.valueOf"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } else if (cls == float.class || cls == Float.class) { debug("INVOKESTATIC java/lang/Float.valueOf"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); } else if (cls == double.class || cls == Double.class) { debug("INVOKESTATIC java/lang/Double.valueOf"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); } else if (cls == short.class || cls == Short.class) { debug("INVOKESTATIC java/lang/Short.valueOf"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); } else if (cls == long.class || cls == Long.class) { debug("INVOKESTATIC java/lang/Long.valueOf"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); } else if (cls == byte.class || cls == Byte.class) { debug("INVOKESTATIC java/lang/Byte.valueOf"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); } else if (cls == char.class || cls == Character.class) { debug("INVOKESTATIC java/lang/Character.valueOf"); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); } } } private void anyArrayCheck(Class cls) { if (cls == boolean[].class) { assert debug("CHECKCAST [Z"); mv.visitTypeInsn(CHECKCAST, "[Z"); } else if (cls == int[].class) { assert debug("CHECKCAST [I"); mv.visitTypeInsn(CHECKCAST, "[I"); } else if (cls == float[].class) { assert debug("CHECKCAST [F"); mv.visitTypeInsn(CHECKCAST, "[F"); } else if (cls == double[].class) { assert debug("CHECKCAST [D"); mv.visitTypeInsn(CHECKCAST, "[D"); } else if (cls == short[].class) { assert debug("CHECKCAST [S"); mv.visitTypeInsn(CHECKCAST, "[S"); } else if (cls == long[].class) { assert debug("CHECKCAST [J"); mv.visitTypeInsn(CHECKCAST, "[J"); } else if (cls == byte[].class) { assert debug("CHECKCAST [B"); mv.visitTypeInsn(CHECKCAST, "[B"); } else if (cls == char[].class) { assert debug("CHECKCAST [C"); mv.visitTypeInsn(CHECKCAST, "[C"); } else { assert debug("CHECKCAST [Ljava/lang/Object;"); mv.visitTypeInsn(CHECKCAST, "[Ljava/lang/Object;"); } } private void writeOutLiteralWrapped(Object lit) { if (lit instanceof Integer) { intPush((Integer) lit); wrapPrimitive(int.class); return; } assert debug("LDC " + lit); if (lit instanceof String) { mv.visitLdcInsn(lit); } else if (lit instanceof Long) { mv.visitLdcInsn(lit); wrapPrimitive(long.class); } else if (lit instanceof Float) { mv.visitLdcInsn(lit); wrapPrimitive(float.class); } else if (lit instanceof Double) { mv.visitLdcInsn(lit); wrapPrimitive(double.class); } else if (lit instanceof Short) { mv.visitLdcInsn(lit); wrapPrimitive(short.class); } else if (lit instanceof Character) { mv.visitLdcInsn(lit); wrapPrimitive(char.class); } else if (lit instanceof Boolean) { mv.visitLdcInsn(lit); wrapPrimitive(boolean.class); } else if (lit instanceof Byte) { mv.visitLdcInsn(lit); wrapPrimitive(byte.class); } } public void arrayStore(Class cls) { if (cls.isPrimitive()) { if (cls == int.class) { assert debug("IASTORE"); mv.visitInsn(IASTORE); } else if (cls == char.class) { assert debug("CASTORE"); mv.visitInsn(CASTORE); } else if (cls == boolean.class) { assert debug("BASTORE"); mv.visitInsn(BASTORE); } else if (cls == double.class) { assert debug("DASTORE"); mv.visitInsn(DASTORE); } else if (cls == float.class) { assert debug("FASTORE"); mv.visitInsn(FASTORE); } else if (cls == short.class) { assert debug("SASTORE"); mv.visitInsn(SASTORE); } else if (cls == long.class) { assert debug("LASTORE"); mv.visitInsn(LASTORE); } else if (cls == byte.class) { assert debug("BASTORE"); mv.visitInsn(BASTORE); } } else { assert debug("AASTORE"); mv.visitInsn(AASTORE); } } public void wrapRuntimeConverstion(Class toType) { ldcClassConstant(getWrapperClass(toType)); assert debug("INVOKESTATIC DataConversion.convert"); mv.visitMethodInsn(INVOKESTATIC, "" + NAMESPACE + "DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;"); } private Object addSubstatement(ExecutableStatement stmt) { if (stmt instanceof ExecutableAccessor) { ExecutableAccessor ea = (ExecutableAccessor) stmt; if (ea.getNode().isIdentifier() && !ea.getNode().isDeepProperty()) { loadVariableByName(ea.getNode().getName()); return null; } } compiledInputs.add(stmt); assert debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); assert debug("GETFIELD p" + (compiledInputs.size() - 1)); mv.visitFieldInsn(GETFIELD, className, "p" + (compiledInputs.size() - 1), "L" + NAMESPACE + "compiler/ExecutableStatement;"); assert debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); assert debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); assert debug("INVOKEINTERFACE ExecutableStatement.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(ExecutableStatement.class), "getValue", "(Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;)Ljava/lang/Object;"); return null; } private void loadVariableByName(String name) { assert debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); assert debug("LDC \"" + name + "\""); mv.visitLdcInsn(name); assert debug("INVOKEINTERFACE " + NAMESPACE + "integration/VariableResolverFactory.getVariableResolver"); mv.visitMethodInsn(INVOKEINTERFACE, "" + NAMESPACE + "integration/VariableResolverFactory", "getVariableResolver", "(Ljava/lang/String;)L" + NAMESPACE + "integration/VariableResolver;"); assert debug("INVOKEINTERFACE " + NAMESPACE + "integration/VariableResolver.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, "" + NAMESPACE + "integration/VariableResolver", "getValue", "()Ljava/lang/Object;"); returnType = Object.class; } private void loadVariableByIndex(int pos) { assert debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); assert debug("PUSH IDX VAL =" + pos); intPush(pos); assert debug("INVOKEINTERFACE " + NAMESPACE + "integration/VariableResolverFactory.getIndexedVariableResolver"); mv.visitMethodInsn(INVOKEINTERFACE, "" + NAMESPACE + "integration/VariableResolverFactory", "getIndexedVariableResolver", "(I)L" + NAMESPACE + "integration/VariableResolver;"); assert debug("INVOKEINTERFACE " + NAMESPACE + "integration/VariableResolver.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, "" + NAMESPACE + "integration/VariableResolver", "getValue", "()Ljava/lang/Object;"); returnType = Object.class; } private void loadField(int number) { assert debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); assert debug("GETFIELD p" + number); mv.visitFieldInsn(GETFIELD, className, "p" + number, "L" + NAMESPACE + "compiler/ExecutableStatement;"); } private void ldcClassConstant(Class cls) { if (OPCODES_VERSION == Opcodes.V1_4) { assert debug("LDC \"" + cls.getName() + "\""); mv.visitLdcInsn(cls.getName()); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); Label l4 = new Label(); mv.visitJumpInsn(GOTO, l4); mv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError"); mv.visitInsn(DUP_X1); mv.visitInsn(SWAP); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Throwable", "getMessage", "()Ljava/lang/String;"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "", "(Ljava/lang/String;)V"); mv.visitInsn(ATHROW); mv.visitLabel(l4); } else { assert debug("LDC " + getType(cls)); mv.visitLdcInsn(getType(cls)); } } private void buildInputs() { if (compiledInputs.size() == 0) return; assert debug("\n{SETTING UP MEMBERS...}\n"); StringAppender constSig = new StringAppender("("); int size = compiledInputs.size(); for (int i = 0; i < size; i++) { assert debug("ACC_PRIVATE p" + i); cw.visitField(ACC_PRIVATE, "p" + i, "L" + NAMESPACE + "compiler/ExecutableStatement;", null, null).visitEnd(); constSig.append("L" + NAMESPACE + "compiler/ExecutableStatement;"); } constSig.append(")V"); assert debug("\n{CREATING INJECTION CONSTRUCTOR}\n"); MethodVisitor cv = cw.visitMethod(ACC_PUBLIC, "", constSig.toString(), null, null); cv.visitCode(); assert debug("ALOAD 0"); cv.visitVarInsn(ALOAD, 0); assert debug("INVOKESPECIAL java/lang/Object."); cv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V"); for (int i = 0; i < size; i++) { assert debug("ALOAD 0"); cv.visitVarInsn(ALOAD, 0); assert debug("ALOAD " + (i + 1)); cv.visitVarInsn(ALOAD, i + 1); assert debug("PUTFIELD p" + i); cv.visitFieldInsn(PUTFIELD, className, "p" + i, "L" + NAMESPACE + "compiler/ExecutableStatement;"); } assert debug("RETURN"); cv.visitInsn(RETURN); cv.visitMaxs(0, 0); cv.visitEnd(); assert debug("}"); } private static final int ARRAY = 0; private static final int LIST = 1; private static final int MAP = 2; private static final int VAL = 3; private int _getAccessor(Object o, Class type) { if (o instanceof List) { assert debug("NEW " + LIST_IMPL); mv.visitTypeInsn(NEW, LIST_IMPL); assert debug("DUP"); mv.visitInsn(DUP); assert debug("DUP"); mv.visitInsn(DUP); intPush(((List) o).size()); assert debug("INVOKESPECIAL " + LIST_IMPL + "."); mv.visitMethodInsn(INVOKESPECIAL, LIST_IMPL, "", "(I)V"); for (Object item : (List) o) { if (_getAccessor(item, type) != VAL) { assert debug("POP"); mv.visitInsn(POP); } assert debug("INVOKEINTERFACE java/util/List.add"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z"); assert debug("POP"); mv.visitInsn(POP); assert debug("DUP"); mv.visitInsn(DUP); } returnType = List.class; return LIST; } else if (o instanceof Map) { assert debug("NEW " + MAP_IMPL); mv.visitTypeInsn(NEW, MAP_IMPL); assert debug("DUP"); mv.visitInsn(DUP); assert debug("DUP"); mv.visitInsn(DUP); intPush(((Map) o).size()); assert debug("INVOKESPECIAL " + MAP_IMPL + "."); mv.visitMethodInsn(INVOKESPECIAL, MAP_IMPL, "", "(I)V"); for (Object item : ((Map) o).keySet()) { mv.visitTypeInsn(CHECKCAST, "java/util/Map"); if (_getAccessor(item, type) != VAL) { assert debug("POP"); mv.visitInsn(POP); } if (_getAccessor(((Map) o).get(item), type) != VAL) { assert debug("POP"); mv.visitInsn(POP); } assert debug("INVOKEINTERFACE java/util/Map.put"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); assert debug("POP"); mv.visitInsn(POP); assert debug("DUP"); mv.visitInsn(DUP); } returnType = Map.class; return MAP; } else if (o instanceof Object[]) { Accessor[] a = new Accessor[((Object[]) o).length]; int i = 0; int dim = 0; if (type != null) { String nm = type.getName(); while (nm.charAt(dim) == '[') dim++; } else { type = Object[].class; dim = 1; } try { intPush(((Object[]) o).length); assert debug("ANEWARRAY " + getInternalName(getSubComponentType(type)) + " (" + ((Object[]) o).length + ")"); mv.visitTypeInsn(ANEWARRAY, getInternalName(getSubComponentType(type))); Class cls = dim > 1 ? findClass(null, repeatChar('[', dim - 1) + "L" + getBaseComponentType(type).getName() + ";", pCtx) : type; assert debug("DUP"); mv.visitInsn(DUP); for (Object item : (Object[]) o) { intPush(i); if (_getAccessor(item, cls) != VAL) { assert debug("POP"); mv.visitInsn(POP); } assert debug("AASTORE (" + o.hashCode() + ")"); mv.visitInsn(AASTORE); assert debug("DUP"); mv.visitInsn(DUP); i++; } } catch (ClassNotFoundException e) { throw new RuntimeException("this error should never throw:" + getBaseComponentType(type).getName(), e); } return ARRAY; } else { if (type.isArray()) { writeLiteralOrSubexpression(subCompileExpression(((String) o).toCharArray(), pCtx), getSubComponentType(type)); } else { writeLiteralOrSubexpression(subCompileExpression(((String) o).toCharArray(), pCtx)); } return VAL; } } private Class writeLiteralOrSubexpression(Object stmt) { return writeLiteralOrSubexpression(stmt, null, null); } private Class writeLiteralOrSubexpression(Object stmt, Class desiredTarget) { return writeLiteralOrSubexpression(stmt, desiredTarget, null); } private Class writeLiteralOrSubexpression(Object stmt, Class desiredTarget, Class knownIngressType) { if (stmt instanceof ExecutableLiteral) { Class type = ((ExecutableLiteral) stmt).getLiteral().getClass(); assert debug("*** type:" + type + ";desired:" + desiredTarget); if (type == Integer.class && desiredTarget == int.class) { intPush(((ExecutableLiteral) stmt).getInteger32()); type = int.class; } else if (desiredTarget != null && desiredTarget != type) { assert debug("*** Converting because desiredType(" + desiredTarget.getClass() + ") is not: " + type); if (!DataConversion.canConvert(type, desiredTarget)) { throw new CompileException("was expecting type: " + desiredTarget.getName() + "; but found type: " + type.getName()); } writeOutLiteralWrapped(convert(((ExecutableLiteral) stmt).getLiteral(), desiredTarget)); } else { writeOutLiteralWrapped(((ExecutableLiteral) stmt).getLiteral()); } return type; } else { literal = false; addSubstatement((ExecutableStatement) stmt); Class type; if (knownIngressType == null) { type = ((ExecutableStatement) stmt).getKnownEgressType(); } else { type = knownIngressType; } if (desiredTarget != null && type != desiredTarget) { if (desiredTarget.isPrimitive()) { if (type == null) throw new OptimizationFailure("cannot optimize expression: " + new String(expr) + ": cannot determine ingress type for primitive output"); checkcast(type); unwrapPrimitive(desiredTarget); } } return type; } } private void addPrintOut(String text) { mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn(text); mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); } public Accessor optimizeCollection(ParserContext pCtx, Object o, Class type, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory) { this.cursor = 0; this.returnType = type; if (property != null) this.length = (this.expr = property).length; this.compiledInputs = new ArrayList(); this.ctx = ctx; this.thisRef = thisRef; this.variableFactory = factory; _initJIT(); literal = true; _getAccessor(o, type); _finishJIT(); try { Accessor compiledAccessor = _initializeAccessor(); if (property != null && property.length > 0) { return new Union(compiledAccessor, property); } else { return compiledAccessor; } } catch (Exception e) { throw new OptimizationFailure("could not optimize collection", e); } } private void checkcast(Class cls) { assert debug("CHECKCAST " + getInternalName(cls)); mv.visitTypeInsn(CHECKCAST, getInternalName(cls)); } private void intPush(int index) { if (index < 6) { switch (index) { case 0: assert debug("ICONST_0"); mv.visitInsn(ICONST_0); break; case 1: assert debug("ICONST_1"); mv.visitInsn(ICONST_1); break; case 2: assert debug("ICONST_2"); mv.visitInsn(ICONST_2); break; case 3: assert debug("ICONST_3"); mv.visitInsn(ICONST_3); break; case 4: assert debug("ICONST_4"); mv.visitInsn(ICONST_4); break; case 5: assert debug("ICONST_5"); mv.visitInsn(ICONST_5); break; } } else if (index > -127 && index < 128) { assert debug("BIPUSH " + index); mv.visitIntInsn(BIPUSH, index); } else if (index > Short.MAX_VALUE) { assert debug("LDC " + index); mv.visitLdcInsn(index); } else { assert debug("SIPUSH " + index); mv.visitIntInsn(SIPUSH, index); } } public Accessor optimizeObjectCreation(ParserContext pCtx, char[] property, Object ctx, Object thisRef, VariableResolverFactory factory) { _initJIT(); compiledInputs = new ArrayList(); this.length = (this.expr = property).length; this.ctx = ctx; this.thisRef = thisRef; this.variableFactory = factory; this.pCtx = pCtx; String[] cnsRes = captureContructorAndResidual(property); String[] constructorParms = parseMethodOrConstructor(cnsRes[0].toCharArray()); try { if (constructorParms != null) { for (String constructorParm : constructorParms) { compiledInputs.add((ExecutableStatement) subCompileExpression(constructorParm.toCharArray(), pCtx)); } Class cls = findClass(factory, new String(subset(property, 0, findFirst('(', property))), pCtx); assert debug("NEW " + getInternalName(cls)); mv.visitTypeInsn(NEW, getInternalName(cls)); assert debug("DUP"); mv.visitInsn(DUP); Object[] parms = new Object[constructorParms.length]; int i = 0; for (ExecutableStatement es : compiledInputs) { parms[i++] = es.getValue(ctx, factory); } Constructor cns = getBestConstructorCandidate(parms, cls, pCtx.isStrongTyping()); if (cns == null) { StringBuilder error = new StringBuilder(); for (int x = 0; x < parms.length; x++) { error.append(parms[x].getClass().getName()); if (x + 1 < parms.length) error.append(", "); } throw new CompileException("unable to find constructor: " + cls.getName() + "(" + error.toString() + ")"); } this.returnType = cns.getDeclaringClass(); Class tg; for (i = 0; i < constructorParms.length; i++) { assert debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); assert debug("GETFIELD p" + i); mv.visitFieldInsn(GETFIELD, className, "p" + i, "L" + NAMESPACE + "compiler/ExecutableStatement;"); assert debug("ALOAD 2"); mv.visitVarInsn(ALOAD, 2); assert debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); assert debug("INVOKEINTERFACE " + NAMESPACE + "compiler/ExecutableStatement.getValue"); mv.visitMethodInsn(INVOKEINTERFACE, "" + NAMESPACE + "compiler/ExecutableStatement", "getValue", "(Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;)Ljava/lang/Object;"); tg = cns.getParameterTypes()[i].isPrimitive() ? getWrapperClass(cns.getParameterTypes()[i]) : cns.getParameterTypes()[i]; if (parms[i] != null && !parms[i].getClass().isAssignableFrom(cns.getParameterTypes()[i])) { ldcClassConstant(tg); assert debug("INVOKESTATIC " + NAMESPACE + "DataConversion.convert"); mv.visitMethodInsn(INVOKESTATIC, "" + NAMESPACE + "DataConversion", "convert", "(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;"); if (cns.getParameterTypes()[i].isPrimitive()) { unwrapPrimitive(cns.getParameterTypes()[i]); } else { assert debug("CHECKCAST " + getInternalName(tg)); mv.visitTypeInsn(CHECKCAST, getInternalName(tg)); } } else { assert debug("CHECKCAST " + getInternalName(cns.getParameterTypes()[i])); mv.visitTypeInsn(CHECKCAST, getInternalName(cns.getParameterTypes()[i])); } } assert debug("INVOKESPECIAL " + getInternalName(cls) + ". : " + getConstructorDescriptor(cns)); mv.visitMethodInsn(INVOKESPECIAL, getInternalName(cls), "", getConstructorDescriptor(cns)); _finishJIT(); Accessor acc = _initializeAccessor(); if (cnsRes.length > 1 && cnsRes[1] != null && !cnsRes[1].trim().equals("")) { return new Union(acc, cnsRes[1].toCharArray()); } return acc; } else { Class cls = findClass(factory, new String(property), pCtx); assert debug("NEW " + getInternalName(cls)); mv.visitTypeInsn(NEW, getInternalName(cls)); assert debug("DUP"); mv.visitInsn(DUP); Constructor cns = cls.getConstructor(EMPTYCLS); assert debug("INVOKESPECIAL "); mv.visitMethodInsn(INVOKESPECIAL, getInternalName(cls), "", getConstructorDescriptor(cns)); _finishJIT(); Accessor acc = _initializeAccessor(); if (cnsRes.length > 1 && cnsRes[1] != null && !cnsRes[1].trim().equals("")) { return new Union(acc, cnsRes[1].toCharArray()); } return acc; } } catch (ClassNotFoundException e) { throw new CompileException("class or class reference not found: " + new String(property)); } catch (Exception e) { throw new OptimizationFailure("could not optimize construtor: " + new String(property), e); } } public Class getEgressType() { return returnType; } private void dumpAdvancedDebugging() { if (buildLog == null) return; System.out.println("JIT Compiler Dump for: <<" + (expr == null ? null : new String(expr)) + ">>\n-------------------------------\n"); System.out.println(buildLog.toString()); System.out.println("\n\n"); if (MVEL.isFileDebugging()) { try { FileWriter writer = ParseTools.getDebugFileWriter(); writer.write(buildLog.toString()); writer.flush(); writer.close(); } catch (IOException e) { //empty } } } private Object propHandlerByteCode(String property, Object ctx, Class handler) { PropertyHandler ph = getPropertyHandler(handler); if (ph instanceof ProducesBytecode) { assert debug("<<3rd-Party Code Generation>>"); ((ProducesBytecode) ph).produceBytecodeGet(mv, property, variableFactory); return ph.getProperty(property, ctx, variableFactory); } else { throw new RuntimeException("unable to compile: custom accessor does not support producing bytecode: " + ph.getClass().getName()); } } private void propHandlerByteCodePut(String property, Object ctx, Class handler, Object value) { PropertyHandler ph = getPropertyHandler(handler); if (ph instanceof ProducesBytecode) { assert debug("<<3rd-Party Code Generation>>"); ((ProducesBytecode) ph).produceBytecodePut(mv, property, variableFactory); ph.setProperty(property, ctx, variableFactory, value); } else { throw new RuntimeException("unable to compile: custom accessor does not support producing bytecode: " + ph.getClass().getName()); } } private void writeOutNullHandler(Member member, int type) { assert debug("DUP"); mv.visitInsn(DUP); Label j = new Label(); assert debug("IFNONNULL : jump"); mv.visitJumpInsn(IFNONNULL, j); assert debug("POP"); mv.visitInsn(POP); assert debug("ALOAD 0"); mv.visitVarInsn(ALOAD, 0); if (type == 0) { this.propNull = true; assert debug("GETFIELD 'nullPropertyHandler'"); mv.visitFieldInsn(GETFIELD, className, "nullPropertyHandler", "L" + NAMESPACE + "integration/PropertyHandler;"); } else { this.methNull = true; assert debug("GETFIELD 'nullMethodHandler'"); mv.visitFieldInsn(GETFIELD, className, "nullMethodHandler", "L" + NAMESPACE + "integration/PropertyHandler;"); } assert debug("LDC '" + member.getName() + "'"); mv.visitLdcInsn(member.getName()); assert debug("ALOAD 1"); mv.visitVarInsn(ALOAD, 1); assert debug("ALOAD 3"); mv.visitVarInsn(ALOAD, 3); assert debug("INVOKEINTERFACE PropertyHandler.getProperty"); mv.visitMethodInsn(INVOKEINTERFACE, NAMESPACE + "integration/PropertyHandler", "getProperty", "(Ljava/lang/String;Ljava/lang/Object;L" + NAMESPACE + "integration/VariableResolverFactory;)Ljava/lang/Object;"); assert debug("LABEL:jump"); mv.visitLabel(j); } public boolean isLiteralOnly() { return literal; } } mvel-2.0.18.orig/src/main/java/org/mvel2/optimizers/impl/asm/ProducesBytecode.java0000644000175000017500000000510611077457613027721 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.optimizers.impl.asm; import org.mvel2.asm.MethodVisitor; import org.mvel2.integration.VariableResolverFactory; /** * A {@link org.mvel2.integration.PropertyHandler} that implements this class advertises the to the * {@link ASMAccessorOptimizer} that it is able to generate bytecode for it's custom resolvers.
*
* The two methods defined by this interface (one for get, and one for set accessors) are passed an * ASM MethodVistor object. It is to be assumed by the implementor that the JIT has already produced * the necessary bytecode up until this point. The implementor most only implement the necessary bytecode * instructions to retrieve the property, leaving the resultant value on the stack. DO NOT implement * bytecode that calls a return instruction such as ARETURN. This will be done automatically by the JIT.
*
* See the following example:
*


 *   public void produceBytecodeGet(MethodVisitor mv, String propertyName, VariableResolverFactory variableResolverFactory) {
 * mv.visitTypeInsn(CHECKCAST, "org/mvel/tests/main/res/SampleBean");
 * mv.visitLdcInsn(propertyName);
 * mv.visitMethodInsn(INVOKEVIRTUAL, "org/mvel/tests/main/res/SampleBean", "getProperty", "(Ljava/lang/String;)Ljava/lang/Object;");
 * }
 * 

* This example (correctly) presumes that the property of interest exists on the stack, and simply performs the necessary * CHECKCAST, and call to the needed method in the accessor to translate the property call.
*
* This is taken from a working example which you can examine in the MVEL unit tests. * The class is: org.mvel.tests.main.res.SampleBeanAccessor */ public interface ProducesBytecode { public void produceBytecodeGet(MethodVisitor mv, String propertyName, VariableResolverFactory factory); public void produceBytecodePut(MethodVisitor mv, String propertyName, VariableResolverFactory factory); } mvel-2.0.18.orig/src/main/java/org/mvel2/debug/0000755000175000017500000000000011412747041020737 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/debug/Debugger.java0000644000175000017500000000174011077457613023342 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.debug; public interface Debugger { public static int CONTINUE = 0; public static int STEP = 1; public static int STEP_OVER = STEP; /** * When a breakpoint is recached, * * @param frame * @return continuation command */ public int onBreak(Frame frame); }mvel-2.0.18.orig/src/main/java/org/mvel2/debug/DebugTools.java0000644000175000017500000003251011165737230023656 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.debug; import org.mvel2.Operator; import static org.mvel2.Operator.ADD; import static org.mvel2.Operator.SUB; import org.mvel2.ast.*; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExecutableAccessor; import org.mvel2.compiler.ExecutableLiteral; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ASTIterator; import org.mvel2.util.ASTLinkedList; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * @author Christopher Brock */ public class DebugTools { public static String decompile(Serializable expr) { if (expr instanceof CompiledExpression) return decompile((CompiledExpression) expr); else if (expr instanceof ExecutableAccessor) return "CANNOT DECOMPILE OPTIMIZED STATEMENT (Run with -Dmvel.optimizer=false)"; else if (expr instanceof ExecutableLiteral) { return "LITERAL: " + ((ExecutableLiteral) expr).getValue(null, null); } else return "NOT A KNOWN PAYLOAD: " + expr.getClass().getName(); } public static String decompile(CompiledExpression cExp) { return decompile(cExp, false, new DecompileContext()); } private static final class DecompileContext { public int node = 0; } private static String decompile(CompiledExpression cExp, boolean nest, DecompileContext context) { ASTIterator iter = new ASTLinkedList(cExp.getFirstNode()); ASTNode tk; StringBuffer sbuf = new StringBuffer(); if (!nest) { sbuf.append("Expression Decompile\n-------------\n"); } while (iter.hasMoreNodes()) { sbuf.append("(").append(context.node++).append(") "); if ((tk = iter.nextNode()) instanceof NestedStatement && ((NestedStatement) tk).getNestedStatement() instanceof CompiledExpression) { //noinspection StringConcatenationInsideStringBufferAppend sbuf.append("NEST [" + tk.getClass().getSimpleName() + "]: { " + tk.getName() + " }\n"); sbuf.append(decompile((CompiledExpression) ((NestedStatement) tk).getNestedStatement(), true, context)); } if (tk instanceof Substatement && ((Substatement) tk).getStatement() instanceof CompiledExpression) { //noinspection StringConcatenationInsideStringBufferAppend sbuf.append("NEST [" + tk.getClass().getSimpleName() + "]: { " + tk.getName() + " }\n"); sbuf.append(decompile((CompiledExpression) ((Substatement) tk).getStatement(), true, context)); } // else if (tk instanceof Function) { // sbuf.append("FUNCTION [" + tk.getName() + "]: ") // .append(decompile((CompiledExpression) ((Function)tk).getCompiledBlock(), true, context)); // } else if (tk.isDebuggingSymbol()) { //noinspection StringConcatenationInsideStringBufferAppend sbuf.append("DEBUG_SYMBOL :: " + tk.toString()); } else if (tk.isLiteral()) { sbuf.append("LITERAL :: ").append(tk.getLiteralValue()).append("'"); } else if (tk.isOperator()) { sbuf.append("OPERATOR [").append(getOperatorName(tk.getOperator())).append("]: ") .append(tk.getName()); if (tk.isOperator(Operator.END_OF_STMT)) sbuf.append("\n"); } else if (tk.isIdentifier()) { sbuf.append("REFERENCE :: ").append(tk.getClass().getSimpleName()).append(":").append(tk.getName()); } else if (tk instanceof BinaryOperation) { BinaryOperation bo = (BinaryOperation) tk; sbuf.append("OPERATION [" + getOperatorName(bo.getOperation()) + "] {").append(bo.getLeft().getName()) .append("} {").append(bo.getRight().getName()).append("}"); } else { //noinspection StringConcatenationInsideStringBufferAppend sbuf.append("NODE [" + tk.getClass().getSimpleName() + "] :: " + tk.getName()); } sbuf.append("\n"); } sbuf.append("==END=="); return sbuf.toString(); } public static String getOperatorSymbol(int operator) { switch (operator) { case ADD: return "+"; case SUB: return "-"; case Operator.ASSIGN: return "="; case Operator.ASSIGN_ADD: return "=+"; case Operator.ASSIGN_STR_APPEND: return "=+"; case Operator.ASSIGN_SUB: return "="; case Operator.BW_AND: return "&"; case Operator.BW_OR: return "|"; case Operator.BW_SHIFT_LEFT: return "<<"; case Operator.BW_SHIFT_RIGHT: return ">>"; case Operator.BW_USHIFT_LEFT: return "<<<"; case Operator.BW_USHIFT_RIGHT: return ">>>"; case Operator.BW_XOR: return "^"; case Operator.CONTAINS: return "contains"; case Operator.CONVERTABLE_TO: return "convertable_to"; case Operator.DEC: return "--"; case Operator.DEC_ASSIGN: return "++"; case Operator.DIV: return "/"; case Operator.DO: return "do"; case Operator.ELSE: return "else"; case Operator.END_OF_STMT: return ";"; case Operator.EQUAL: return "=="; case Operator.FOR: return "for"; case Operator.FOREACH: return "foreach"; case Operator.FUNCTION: return "function"; case Operator.GETHAN: return ">="; case Operator.GTHAN: return ">"; case Operator.IF: return "if"; case Operator.INC: return "++"; case Operator.INC_ASSIGN: return "++"; case Operator.INSTANCEOF: return "instanceof"; case Operator.LETHAN: return "<="; case Operator.LTHAN: return "<"; case Operator.MOD: return "%"; case Operator.MULT: return "*"; case Operator.NEQUAL: return "!="; case Operator.NEW: return "new"; case Operator.AND: return "&&"; case Operator.OR: return "||"; case Operator.POWER: return "**"; case Operator.PROJECTION: return "PROJECT"; case Operator.REGEX: return "REGEX"; case Operator.RETURN: return "RETURN"; case Operator.SIMILARITY: return "SIMILARITY"; case Operator.SOUNDEX: return "SOUNDEX"; case Operator.STR_APPEND: return "+"; case Operator.SWITCH: return "SWITCH"; case Operator.TERNARY: return "TERNARY_IF"; case Operator.TERNARY_ELSE: return "TERNARY_ELSE"; case Operator.WHILE: return "while"; case Operator.CHOR: return "or"; } return "UNKNOWN_OPERATOR"; } public static String getOperatorName(int operator) { switch (operator) { case ADD: return "ADD"; case SUB: return "SUBTRACT"; case Operator.ASSIGN: return "ASSIGN"; case Operator.ASSIGN_ADD: return "ASSIGN_ADD"; case Operator.ASSIGN_STR_APPEND: return "ASSIGN_STR_APPEND"; case Operator.ASSIGN_SUB: return "ASSIGN_SUB"; case Operator.BW_AND: return "BIT_AND"; case Operator.BW_OR: return "BIT_OR"; case Operator.BW_SHIFT_LEFT: return "BIT_SHIFT_LEFT"; case Operator.BW_SHIFT_RIGHT: return "BIT_SHIFT_RIGHT"; case Operator.BW_USHIFT_LEFT: return "BIT_UNSIGNED_SHIFT_LEFT"; case Operator.BW_USHIFT_RIGHT: return "BIT_UNSIGNED_SHIFT_RIGHT"; case Operator.BW_XOR: return "BIT_XOR"; case Operator.CONTAINS: return "CONTAINS"; case Operator.CONVERTABLE_TO: return "CONVERTABLE_TO"; case Operator.DEC: return "DECREMENT"; case Operator.DEC_ASSIGN: return "DECREMENT_ASSIGN"; case Operator.DIV: return "DIVIDE"; case Operator.DO: return "DO"; case Operator.ELSE: return "ELSE"; case Operator.END_OF_STMT: return "END_OF_STATEMENT"; case Operator.EQUAL: return "EQUAL"; case Operator.FOR: return "FOR"; case Operator.FOREACH: return "FOREACH"; case Operator.FUNCTION: return "FUNCTION"; case Operator.GETHAN: return "GREATER_THAN_OR_EQUAL"; case Operator.GTHAN: return "GREATHER_THAN"; case Operator.IF: return "IF"; case Operator.INC: return "INCREMENT"; case Operator.INC_ASSIGN: return "INCREMENT_ASSIGN"; case Operator.INSTANCEOF: return "INSTANCEOF"; case Operator.LETHAN: return "LESS_THAN_OR_EQUAL"; case Operator.LTHAN: return "LESS_THAN"; case Operator.MOD: return "MODULUS"; case Operator.MULT: return "MULTIPLY"; case Operator.NEQUAL: return "NOT_EQUAL"; case Operator.NEW: return "NEW_OBJECT"; case Operator.AND: return "AND"; case Operator.OR: return "OR"; case Operator.POWER: return "POWER_OF"; case Operator.PROJECTION: return "PROJECT"; case Operator.REGEX: return "REGEX"; case Operator.RETURN: return "RETURN"; case Operator.SIMILARITY: return "SIMILARITY"; case Operator.SOUNDEX: return "SOUNDEX"; case Operator.STR_APPEND: return "STR_APPEND"; case Operator.SWITCH: return "SWITCH"; case Operator.TERNARY: return "TERNARY_IF"; case Operator.TERNARY_ELSE: return "TERNARY_ELSE"; case Operator.WHILE: return "WHILE"; case Operator.CHOR: return "CHAINED_OR"; } return "UNKNOWN_OPERATOR"; } public static Class determineType(String name, CompiledExpression compiledExpression) { ASTIterator iter = new ASTLinkedList(compiledExpression.getFirstNode()); ASTNode node; while (iter.hasMoreNodes()) { if (name.equals((node = iter.nextNode()).getName()) && node.isAssignment()) { return node.getEgressType(); } } return null; } public static Map getAllVariableResolvers(VariableResolverFactory rootFactory) { Map allVariableResolvers = new HashMap(); VariableResolverFactory vrf = rootFactory; do { for (String var : vrf.getKnownVariables()) { allVariableResolvers.put(var, vrf.getVariableResolver(var)); } } while ((vrf = vrf.getNextFactory()) != null); return allVariableResolvers; } } mvel-2.0.18.orig/src/main/java/org/mvel2/debug/DebuggerContext.java0000644000175000017500000000624611077457613024715 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.debug; import org.mvel2.ast.LineLabel; import org.mvel2.compiler.CompiledExpression; import org.mvel2.integration.VariableResolverFactory; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class DebuggerContext { private Map> breakpoints; private Debugger debugger; private int debuggerState = 0; public DebuggerContext() { breakpoints = new HashMap>(); } public Map> getBreakpoints() { return breakpoints; } public void setBreakpoints(Map> breakpoints) { this.breakpoints = breakpoints; } public Debugger getDebugger() { return debugger; } public void setDebugger(Debugger debugger) { this.debugger = debugger; } public int getDebuggerState() { return debuggerState; } public void setDebuggerState(int debuggerState) { this.debuggerState = debuggerState; } // utility methods public void registerBreakpoint(String sourceFile, int lineNumber) { if (!breakpoints.containsKey(sourceFile)) breakpoints.put(sourceFile, new HashSet()); breakpoints.get(sourceFile).add(lineNumber); } public void removeBreakpoint(String sourceFile, int lineNumber) { if (!breakpoints.containsKey(sourceFile)) return; breakpoints.get(sourceFile).remove(lineNumber); } public void clearAllBreakpoints() { breakpoints.clear(); } public boolean hasBreakpoints() { return breakpoints.size() != 0; } public boolean hasBreakpoint(LineLabel label) { return breakpoints.containsKey(label.getSourceFile()) && breakpoints.get(label.getSourceFile()). contains(label.getLineNumber()); } public boolean hasBreakpoint(String sourceFile, int lineNumber) { return breakpoints.containsKey(sourceFile) && breakpoints.get(sourceFile).contains(lineNumber); } public boolean hasDebugger() { return debugger != null; } public int checkBreak(LineLabel label, VariableResolverFactory factory, CompiledExpression expression) { if (debuggerState == Debugger.STEP || hasBreakpoint(label)) { if (debugger == null) throw new RuntimeException("no debugger registered to handle breakpoint"); return debuggerState = debugger.onBreak(new Frame(label, factory, expression.getParserContext())); } return 0; } } mvel-2.0.18.orig/src/main/java/org/mvel2/debug/Frame.java0000644000175000017500000000322611154053737022644 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.debug; import org.mvel2.ParserContext; import org.mvel2.ast.LineLabel; import org.mvel2.integration.VariableResolverFactory; public class Frame { private LineLabel label; private VariableResolverFactory factory; private ParserContext parserContext; public Frame(LineLabel label, VariableResolverFactory factory, ParserContext pCtx) { this.label = label; this.factory = factory; this.parserContext = pCtx; } public String getSourceName() { return label.getSourceFile(); } public int getLineNumber() { return label.getLineNumber(); } public VariableResolverFactory getFactory() { return factory; } public void setFactory(VariableResolverFactory factory) { this.factory = factory; } public ParserContext getParserContext() { return parserContext; } public void setParserContext(ParserContext parserContext) { this.parserContext = parserContext; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ConversionException.java0000644000175000017500000000207411077457613024535 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; public class ConversionException extends PropertyAccessException { public ConversionException() { super(); } public ConversionException(String message) { super(message); } public ConversionException(String message, Throwable cause) { super(message, cause); } public ConversionException(Throwable cause) { super(cause); } } mvel-2.0.18.orig/src/main/java/org/mvel2/MVELRuntime.java0000644000175000017500000002174211223434233022625 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import static org.mvel2.Operator.*; import org.mvel2.ast.ASTNode; import org.mvel2.ast.LineLabel; import org.mvel2.compiler.CompiledExpression; import org.mvel2.debug.Debugger; import org.mvel2.debug.DebuggerContext; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.ImmutableDefaultFactory; import org.mvel2.util.ExecutionStack; import static org.mvel2.util.PropertyTools.isEmpty; /** * This class contains the runtime for running compiled MVEL expressions. */ @SuppressWarnings({"CaughtExceptionImmediatelyRethrown"}) public class MVELRuntime { public static final ImmutableDefaultFactory IMMUTABLE_DEFAULT_FACTORY = new ImmutableDefaultFactory(); private static ThreadLocal debuggerContext; /** * Main interpreter. * * @param debugger Run in debug mode * @param expression The compiled expression object * @param ctx The root context object * @param variableFactory The variable factory to be injected * @return The resultant value * @see org.mvel2.MVEL */ public static Object execute(boolean debugger, final CompiledExpression expression, final Object ctx, VariableResolverFactory variableFactory) { Object v1, v2; ExecutionStack stk = new ExecutionStack(); ASTNode tk = expression.getFirstNode(); Integer operator; if (tk == null) return null; try { do { if (tk.fields == -1) { /** * This may seem silly and redundant, however, when an MVEL script recurses into a block * or substatement, a new runtime loop is entered. Since the debugger state is not * passed through the AST, it is not possible to forward the state directly. So when we * encounter a debugging symbol, we check the thread local to see if there is are registered * breakpoints. If we find them, we assume that we are debugging. * * The consequence of this of course, is that it's not ideal to compile expressions with * debugging symbols which you plan to use in a production enviroment. */ if (debugger || (debugger = hasDebuggerContext())) { try { debuggerContext.get().checkBreak((LineLabel) tk, variableFactory, expression); } catch (NullPointerException e) { // do nothing for now. this isn't as calus as it seems. } } continue; } else if (stk.isEmpty()) { stk.push(tk.getReducedValueAccelerated(ctx, ctx, variableFactory)); } switch (operator = tk.getOperator()) { case NOOP: continue; case TERNARY: if (!stk.popBoolean()) { //noinspection StatementWithEmptyBody while (tk.nextASTNode != null && !(tk = tk.nextASTNode).isOperator(TERNARY_ELSE)) ; } stk.clear(); continue; case TERNARY_ELSE: return stk.pop(); case END_OF_STMT: /** * If the program doesn't end here then we wipe anything off the stack that remains. * Althought it may seem like intuitive stack optimizations could be leveraged by * leaving hanging values on the stack, trust me it's not a good idea. */ if (tk.nextASTNode != null) { stk.clear(); } continue; } stk.push(tk.nextASTNode.getReducedValueAccelerated(ctx, ctx, variableFactory), operator); try { while (stk.isReduceable()) { if ((Integer) stk.peek() == CHOR) { stk.pop(); v1 = stk.pop(); v2 = stk.pop(); if (!isEmpty(v2) || !isEmpty(v1)) { stk.clear(); stk.push(!isEmpty(v2) ? v2 : v1); } else stk.push(null); } else { stk.op(); } } } catch (ClassCastException e) { throw new CompileException("syntax error or incomptable types", e); } catch (CompileException e) { throw e; } catch (Exception e) { throw new CompileException("failed to compile sub expression", e); } } while ((tk = tk.nextASTNode) != null); return stk.peek(); } catch (NullPointerException e) { if (tk != null && tk.isOperator() && tk.nextASTNode != null) { throw new CompileException("incomplete statement: " + tk.getName() + " (possible use of reserved keyword as identifier: " + tk.getName() + ")"); } else { throw e; } } } /** * Register a debugger breakpoint. * * @param source - the source file the breakpoint is registered in * @param line - the line number of the breakpoint */ public static void registerBreakpoint(String source, int line) { ensureDebuggerContext(); debuggerContext.get().registerBreakpoint(source, line); } /** * Remove a specific breakpoint. * * @param source - the source file the breakpoint is registered in * @param line - the line number of the breakpoint to be removed */ public static void removeBreakpoint(String source, int line) { if (hasDebuggerContext()) { debuggerContext.get().removeBreakpoint(source, line); } } /** * Tests whether or not a debugger context exist. * * @return boolean */ private static boolean hasDebuggerContext() { return debuggerContext != null && debuggerContext.get() != null; } /** * Ensures that debugger context exists. */ private static void ensureDebuggerContext() { if (debuggerContext == null) debuggerContext = new ThreadLocal(); if (debuggerContext.get() == null) debuggerContext.set(new DebuggerContext()); } /** * Reset all the currently registered breakpoints. */ public static void clearAllBreakpoints() { if (hasDebuggerContext()) { debuggerContext.get().clearAllBreakpoints(); } } /** * Tests whether or not breakpoints have been declared. * * @return boolean */ public static boolean hasBreakpoints() { return hasDebuggerContext() && debuggerContext.get().hasBreakpoints(); } /** * Sets the Debugger instance to handle breakpoints. A debugger may only be registered once per thread. * Calling this method more than once will result in the second and subsequent calls to simply fail silently. * To re-register the Debugger, you must call {@link #resetDebugger} * * @param debugger - debugger instance */ public static void setThreadDebugger(Debugger debugger) { ensureDebuggerContext(); debuggerContext.get().setDebugger(debugger); } /** * Reset all information registered in the debugger, including the actual attached Debugger and registered * breakpoints. */ public static void resetDebugger() { debuggerContext = null; } } mvel-2.0.18.orig/src/main/java/org/mvel2/DataConversion.java0000644000175000017500000001022711124346473023441 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import org.mvel2.conversion.*; import org.mvel2.util.FastList; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; /** * The DataConversion factory is where all of MVEL's type converters are registered with the runtime. * * @author Mike Brock * @see ConversionHandler */ public class DataConversion { private static final Map CONVERTERS = new HashMap(38 * 2, 0.5f); static { ConversionHandler ch; CONVERTERS.put(Integer.class, ch = new IntegerCH()); CONVERTERS.put(int.class, ch); CONVERTERS.put(Short.class, ch = new ShortCH()); CONVERTERS.put(short.class, ch); CONVERTERS.put(Long.class, ch = new LongCH()); CONVERTERS.put(long.class, ch); CONVERTERS.put(Character.class, ch = new CharCH()); CONVERTERS.put(char.class, ch); CONVERTERS.put(Byte.class, ch = new ByteCH()); CONVERTERS.put(byte.class, ch); CONVERTERS.put(Float.class, ch = new FloatCH()); CONVERTERS.put(float.class, ch); CONVERTERS.put(Double.class, ch = new DoubleCH()); CONVERTERS.put(double.class, ch); CONVERTERS.put(Boolean.class, ch = new BooleanCH()); CONVERTERS.put(boolean.class, ch); CONVERTERS.put(String.class, new StringCH()); CONVERTERS.put(Object.class, new ObjectCH()); CONVERTERS.put(char[].class, ch = new CharArrayCH()); CONVERTERS.put(Character[].class, ch); CONVERTERS.put(String[].class, new StringArrayCH()); CONVERTERS.put(Integer[].class, new IntArrayCH()); CONVERTERS.put(int[].class, new PrimArrayHandler(int[].class)); CONVERTERS.put(long[].class, new PrimArrayHandler(long[].class)); CONVERTERS.put(double[].class, new PrimArrayHandler(double[].class)); CONVERTERS.put(float[].class, new PrimArrayHandler(float[].class)); CONVERTERS.put(short[].class, new PrimArrayHandler(short[].class)); CONVERTERS.put(boolean[].class, new PrimArrayHandler(boolean[].class)); CONVERTERS.put(BigDecimal.class, new BigDecimalCH()); CONVERTERS.put(BigInteger.class, new BigIntegerCH()); CONVERTERS.put(List.class, ch = new ListCH()); CONVERTERS.put(FastList.class, ch); CONVERTERS.put(ArrayList.class, ch); CONVERTERS.put(LinkedList.class, ch); CONVERTERS.put(Set.class, ch = new SetCH()); CONVERTERS.put(HashSet.class, ch); CONVERTERS.put(LinkedHashSet.class, ch); CONVERTERS.put(TreeSet.class, ch); } public static boolean canConvert(Class toType, Class convertFrom) { return (CONVERTERS.containsKey(toType) && CONVERTERS.get(toType).canConvertFrom(convertFrom)) || toType.isAssignableFrom(convertFrom); } public static T convert(Object in, Class toType) { if (in == null) return null; if (toType == in.getClass() || toType.isAssignableFrom(in.getClass())) { return (T) in; } return (T) CONVERTERS.get(toType).convertFrom(in); } /** * Register a new {@link ConversionHandler} with the factory. * * @param type - Target type represented by the conversion handler. * @param handler - An instance of the handler. */ public static void addConversionHandler(Class type, ConversionHandler handler) { CONVERTERS.put(type, handler); } } mvel-2.0.18.orig/src/main/java/org/mvel2/MVELInterpretedRuntime.java0000644000175000017500000003036711355143606025045 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import static org.mvel2.Operator.*; import org.mvel2.ast.ASTNode; import org.mvel2.ast.Substatement; import org.mvel2.compiler.AbstractParser; import org.mvel2.compiler.BlankLiteral; import org.mvel2.compiler.EndWithValue; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.util.ExecutionStack; import static org.mvel2.util.ParseTools.findClassImportResolverFactory; import java.util.Map; /** * The MVEL interpreted runtime, used for fast parse and execution of scripts. */ @SuppressWarnings({"CaughtExceptionImmediatelyRethrown"}) public class MVELInterpretedRuntime extends AbstractParser { public Object parse() { try { stk = new ExecutionStack(); dStack = new ExecutionStack(); cursor = 0; return parseAndExecuteInterpreted(); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); throw new ParseException("unexpected end of statement", expr, length); } catch (NullPointerException e) { e.printStackTrace(); if (cursor >= length) { throw new ParseException("unexpected end of statement", expr, length); } else { throw e; } } catch (EndWithValue end) { return end.getValue(); } finally { if (parserContext != null) contextControl(REMOVE, null, null); } } private Object holdOverRegister; /** * Main interpreter loop. * * @return value */ private Object parseAndExecuteInterpreted() { ASTNode tk = null; int operator; lastWasIdentifier = false; try { while ((tk = nextToken()) != null) { holdOverRegister = null; if (lastWasIdentifier && lastNode.isDiscard()) { stk.discard(); } /** * If we are at the beginning of a statement, then we immediately push the first token * onto the stack. */ if (stk.isEmpty()) { stk.push(tk.getReducedValue(ctx, ctx, variableFactory)); /** * If this is a substatement, we need to move the result into the d-stack to preserve * proper execution order. */ if (tk instanceof Substatement && (tk = nextToken()) != null) { if (isArithmeticOperator(operator = tk.getOperator())) { stk.push(nextToken().getReducedValue(ctx, ctx, variableFactory), operator); if (procBooleanOperator(arithmeticFunctionReduction(operator)) == -1) return stk.peek(); else continue; } } else { continue; } } switch (procBooleanOperator(operator = tk.getOperator())) { case OP_TERMINATE: return stk.peek(); case OP_RESET_FRAME: continue; case OP_OVERFLOW: if (!tk.isOperator()) { if (!(stk.peek() instanceof Class)) { throw new CompileException("unexpected token: " + tk.getName()); } variableFactory.createVariable(tk.getName(), null, (Class) stk.peek()); } continue; } stk.push(nextToken().getReducedValue(ctx, ctx, variableFactory), operator); switch ((operator = arithmeticFunctionReduction(operator))) { case OP_TERMINATE: return stk.peek(); case OP_RESET_FRAME: continue; } if (procBooleanOperator(operator) == -1) return stk.peek(); } if (holdOverRegister != null) { return holdOverRegister; } } catch (CompileException e) { e.setExpr(expr); e.setLineNumber(line + e.getLineNumber()); e.setCursor(cursor); throw e; } catch (NullPointerException e) { if (tk != null && tk.isOperator()) { CompileException ce = new CompileException("incomplete statement: " + tk.getName() + " (possible use of reserved keyword as identifier: " + tk.getName() + ")", e); ce.setExpr(expr); ce.setLineNumber(line); ce.setCursor(cursor); throw ce; } else { throw e; } } return stk.peek(); } private int procBooleanOperator(int operator) { switch (operator) { case NOOP: return -2; case AND: reduceRight(); if (!stk.peekBoolean()) { if (unwindStatement(operator)) { return -1; } else { stk.clear(); return 0; } } else { stk.discard(); return 0; } case OR: reduceRight(); if (stk.peekBoolean()) { if (unwindStatement(operator)) { return -1; } else { stk.clear(); return 0; } } else { stk.discard(); return 0; } case CHOR: if (!BlankLiteral.INSTANCE.equals(stk.peek())) { return -1; } break; case TERNARY: if (!stk.popBoolean()) { stk.clear(); ASTNode tk; while ((tk = nextToken()) != null && !tk.isOperator(Operator.TERNARY_ELSE)) { //nothing } } return 0; case TERNARY_ELSE: captureToEOS(); return 0; case END_OF_STMT: /** * Assignments are a special scenario for dealing with the stack. Assignments are basically like * held-over failures that basically kickstart the parser when an assignment operator is is * encountered. The originating token is captured, and the the parser is told to march on. The * resultant value on the stack is then used to populate the target variable. * * The other scenario in which we don't want to wipe the stack, is when we hit the end of the * statement, because that top stack value is the value we want back from the parser. */ if (hasMore()) { holdOverRegister = stk.pop(); stk.clear(); } return 0; } return 1; } /** * This method peforms the equivilent of an XSWAP operation to flip the operator * over to the top of the stack, and loads the stored values on the d-stack onto * the main program stack. */ private void reduceRight() { if (dStack.isEmpty()) return; Object o = stk.pop(); stk.push(dStack.pop()); stk.push(o); stk.push(dStack.pop()); reduce(); } private boolean hasMore() { return cursor <= length; } /** * This method is called to unwind the current statement without any reduction or further parsing. * * @param operator - * @return - */ private boolean unwindStatement(int operator) { ASTNode tk; switch (operator) { case AND: while ((tk = nextToken()) != null && !tk.isOperator(Operator.END_OF_STMT) && !tk.isOperator(Operator.OR)) { //nothing } break; default: while ((tk = nextToken()) != null && !tk.isOperator(Operator.END_OF_STMT)) { //nothing } } return tk == null; } public MVELInterpretedRuntime setExpressionArray(char[] expressionArray) { this.length = (this.expr = expressionArray).length; return this; } MVELInterpretedRuntime(char[] expression, Object ctx, Map variables) { this.expr = expression; this.length = expr.length; this.ctx = ctx; this.variableFactory = new MapVariableResolverFactory(variables); } MVELInterpretedRuntime(char[] expression, Object ctx) { this.expr = expression; this.length = expr.length; this.ctx = ctx; this.variableFactory = MVELRuntime.IMMUTABLE_DEFAULT_FACTORY; } MVELInterpretedRuntime(String expression) { setExpression(expression); this.variableFactory = MVELRuntime.IMMUTABLE_DEFAULT_FACTORY; } MVELInterpretedRuntime(char[] expression) { this.length = (this.expr = expression).length; } public MVELInterpretedRuntime(char[] expr, Object ctx, VariableResolverFactory resolverFactory) { this.length = (this.expr = expr).length; this.ctx = ctx; this.variableFactory = resolverFactory; } MVELInterpretedRuntime(char[] expr, Object ctx, VariableResolverFactory resolverFactory, boolean returnBigDecimal) { this.length = (this.expr = expr).length; this.ctx = ctx; this.variableFactory = resolverFactory; } MVELInterpretedRuntime(Object ctx, Map variables) { this.ctx = ctx; this.variableFactory = new MapVariableResolverFactory(variables); } public MVELInterpretedRuntime(String expression, Object ctx, VariableResolverFactory resolverFactory) { setExpression(expression); this.ctx = ctx; this.variableFactory = resolverFactory; } MVELInterpretedRuntime(String expression, Object ctx, VariableResolverFactory resolverFactory, boolean returnBigDecimal) { setExpression(expression); this.ctx = ctx; this.variableFactory = resolverFactory; } MVELInterpretedRuntime(String expression, VariableResolverFactory resolverFactory) { setExpression(expression); this.variableFactory = resolverFactory; } MVELInterpretedRuntime(String expression, Object ctx) { setExpression(expression); this.ctx = ctx; } protected boolean hasImport(String name) { if (pCtx == null) pCtx = getParserContext(); if (pCtx.hasImport(name)) { return true; } else { VariableResolverFactory vrf = findClassImportResolverFactory(variableFactory); return vrf != null && vrf.isResolveable(name); } } protected Class getImport(String name) { if (pCtx == null) pCtx = getParserContext(); if (pCtx.hasImport(name)) return pCtx.getImport(name); return (Class) findClassImportResolverFactory(variableFactory).getVariableResolver(name).getValue(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ErrorDetail.java0000644000175000017500000000363011077457613022744 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 MVFLEX/Valhalla Project and the Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; public class ErrorDetail { private int row; private int col; private boolean critical; private String message; public ErrorDetail(String message, boolean critical) { this.message = message; this.critical = critical; } public ErrorDetail(int row, int col, boolean critical, String message) { this.row = row; this.col = col; this.critical = critical; this.message = message; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public int getCol() { return col; } public void setCol(int col) { this.col = col; } public boolean isCritical() { return critical; } public void setCritical(boolean critical) { this.critical = critical; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String toString() { if (critical) { return "(" + row + "," + col + ") " + message; } else { return "(" + row + "," + col + ") WARNING: " + message; } } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/0000755000175000017500000000000011412747045021467 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/compiler/BlankLiteral.java0000644000175000017500000000316411342137100024665 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import static java.lang.reflect.Array.getLength; import static org.mvel2.util.ParseTools.isNumeric; import java.io.Serializable; import static java.lang.String.valueOf; import java.lang.reflect.Array; import java.util.Collection; public class BlankLiteral implements Serializable { public static final BlankLiteral INSTANCE = new BlankLiteral(); public BlankLiteral() { } public boolean equals(Object obj) { if (obj == null || "".equals(valueOf(obj))) { return true; } else if (isNumeric(obj)) { return "0".equals(valueOf(obj)); } else if (obj instanceof Collection) { return ((Collection) obj).size() == 0; } else if (obj.getClass().isArray()) { return getLength(obj) == 0; } return false; } public String toString() { return ""; } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/EndWithValue.java0000644000175000017500000000173711077457613024707 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; /** * @author Christopher Brock */ public class EndWithValue extends RuntimeException { private Object value; public EndWithValue(Object value) { this.value = value; } public Object getValue() { return value; } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/CompiledExpression.java0000644000175000017500000001357311224677601026160 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import static org.mvel2.MVELRuntime.execute; import org.mvel2.ParserContext; import org.mvel2.ast.ASTNode; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.ClassImportResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import static org.mvel2.optimizers.OptimizerFactory.setThreadAccessorOptimizer; import org.mvel2.util.ASTLinkedList; import org.mvel2.util.StringAppender; import java.io.Serializable; public class CompiledExpression implements Serializable, ExecutableStatement { private ASTNode firstNode; private Class knownEgressType; private Class knownIngressType; private boolean convertableIngressEgress; private boolean optimized = false; private boolean importInjectionRequired = false; private boolean literalOnly; private Class accessorOptimizer; private String sourceName; private ParserContext parserContext; public CompiledExpression(ASTLinkedList astMap, String sourceName, Class egressType, ParserContext ctx, boolean literalOnly) { this.firstNode = astMap.firstNode(); this.sourceName = sourceName; this.knownEgressType = astMap.isSingleNode() ? astMap.firstNonSymbol().getEgressType() : egressType; this.literalOnly = literalOnly; setParserContext(ctx); } public ASTNode getFirstNode() { return firstNode; } public boolean isSingleNode() { return firstNode != null && firstNode.nextASTNode == null; } public Class getKnownEgressType() { return knownEgressType; } public void setKnownEgressType(Class knownEgressType) { this.knownEgressType = knownEgressType; } public Class getKnownIngressType() { return knownIngressType; } public void setKnownIngressType(Class knownIngressType) { this.knownIngressType = knownIngressType; } public boolean isConvertableIngressEgress() { return convertableIngressEgress; } public void setConvertableIngressEgress(boolean convertableIngressEgress) { this.convertableIngressEgress = convertableIngressEgress; } public void computeTypeConversionRule() { if (knownIngressType != null && knownEgressType != null) { convertableIngressEgress = knownIngressType.isAssignableFrom(knownEgressType); } } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (!optimized) setupOptimizers(); return getValue(ctx, variableFactory); } public Object getValue(Object staticContext, VariableResolverFactory factory) { if (!optimized) setupOptimizers(); if (importInjectionRequired) { return execute(false, this, staticContext, new ClassImportResolverFactory(parserContext.getParserConfiguration(), factory)); } else { return execute(false, this, staticContext, factory); } } public Object getDirectValue(Object staticContext, VariableResolverFactory factory) { if (importInjectionRequired) { return execute(false, this, staticContext, new ClassImportResolverFactory(parserContext.getParserConfiguration(), factory)); } else { return execute(false, this, staticContext, factory); } } private void setupOptimizers() { if (accessorOptimizer != null) setThreadAccessorOptimizer(accessorOptimizer); optimized = true; } public boolean isOptimized() { return optimized; } public void setOptimized(boolean optimized) { this.optimized = optimized; } public Class getAccessorOptimizer() { return accessorOptimizer; } public void setAccessorOptimizer(Class accessorOptimizer) { this.accessorOptimizer = accessorOptimizer; } public String getSourceName() { return sourceName; } public void setSourceName(String sourceName) { this.sourceName = sourceName; } public boolean intOptimized() { return false; } public ParserContext getParserContext() { return parserContext; } public void setParserContext(ParserContext parserContext) { if ((this.parserContext = parserContext) != null) { this.importInjectionRequired = parserContext.getImports() != null && parserContext.getImports().size() != 0; } } public boolean isImportInjectionRequired() { return importInjectionRequired; } public void setImportInjectionRequired(boolean importInjectionRequired) { this.importInjectionRequired = importInjectionRequired; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } public boolean isLiteralOnly() { return literalOnly; } public String toString() { StringAppender appender = new StringAppender(); ASTNode node = firstNode; while (node != null) { appender.append(node.toString()).append(";\n"); node = node.nextASTNode; } return appender.toString(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/ExecutableAccessor.java0000644000175000017500000000473311274355331026104 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.ast.ASTNode; import org.mvel2.integration.VariableResolverFactory; public class ExecutableAccessor implements ExecutableStatement { private ASTNode node; private Class ingress; private Class egress; private boolean convertable; public ExecutableAccessor(ASTNode node, Class egress) { this.node = node; this.egress = egress; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { return node.getReducedValueAccelerated(ctx, elCtx, variableFactory); } public Object getValue(Object staticContext, VariableResolverFactory factory) { return node.getReducedValueAccelerated(staticContext, staticContext, factory); } public void setKnownIngressType(Class type) { this.ingress = type; } public void setKnownEgressType(Class type) { this.egress = type; } public Class getKnownIngressType() { return ingress; } public Class getKnownEgressType() { return egress; } public boolean isConvertableIngressEgress() { return convertable; } public void computeTypeConversionRule() { if (ingress != null && egress != null) { convertable = ingress.isAssignableFrom(egress); } } public boolean intOptimized() { return false; } public ASTNode getNode() { return node; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } public boolean isLiteralOnly() { return false; } @Override public String toString() { return node.toString(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/ExpressionCompiler.java0000644000175000017500000004721711355143606026176 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.*; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import static org.mvel2.Operator.PTABLE; import org.mvel2.ast.*; import static org.mvel2.ast.ASTNode.COMPILE_IMMEDIATE; import org.mvel2.util.*; import static org.mvel2.ast.ASTNode.OPT_SUBTR; import static org.mvel2.util.CompilerTools.finalizePayload; import static org.mvel2.util.CompilerTools.signNumber; import static org.mvel2.util.ParseTools.subCompileExpression; import static org.mvel2.util.ParseTools.unboxPrimitive; /** * This is the main MVEL compiler. */ public class ExpressionCompiler extends AbstractParser { private Class returnType; private boolean verifyOnly = false; private boolean verifying = true; private boolean secondPassOptimization = false; public CompiledExpression compile() { return compile(contextControl(GET_OR_CREATE, null, this)); } @Deprecated /** * @deprecated use {@link org.mvel2.MVEL#compileExpression(String, org.mvel2.ParserContext)} instead. * @param ctx * @return compile payload. */ public CompiledExpression compile(ParserContext ctx) { try { this.debugSymbols = (this.pCtx = ctx).isDebugSymbols(); newContext(ctx); return _compile(); } finally { //noinspection ThrowFromFinallyBlock removeContext(); if (pCtx.isFatalError()) { contextControl(REMOVE, null, null); StringAppender err = new StringAppender(); for (ErrorDetail e : pCtx.getErrorList()) { err.append("\n - ").append("(").append(e.getRow()).append(",").append(e.getCol()).append(")") .append(" ").append(e.getMessage()); } //noinspection ThrowFromFinallyBlock throw new CompileException("Failed to compile: " + pCtx.getErrorList().size() + " compilation error(s): " + err.toString(), pCtx.getErrorList()); } } } /** * Initiate an in-context compile. This method should really only be called by the internal API. * * @return compiled expression object */ public CompiledExpression _compile() { ASTNode tk; ASTNode tkOp; ASTNode tkOp2; ASTNode tkLA; ASTNode tkLA2; int op, lastOp = -1; ASTLinkedList astBuild = new ASTLinkedList(); stk = new ExecutionStack(); dStack = new ExecutionStack(); compileMode = true; boolean firstLA; if (pCtx == null) pCtx = getParserContext(); try { if (verifying) { pCtx.initializeTables(); } fields |= COMPILE_IMMEDIATE; while ((tk = nextToken()) != null) { /** * If this is a debug symbol, just add it and continue. */ if (tk.fields == -1) { astBuild.addTokenNode(tk); continue; } /** * Record the type of the current node.. */ returnType = tk.getEgressType(); if (tk instanceof Substatement) { ExpressionCompiler subCompiler = new ExpressionCompiler(tk.getNameAsArray(), pCtx); tk.setAccessor(subCompiler._compile()); returnType = subCompiler.getReturnType(); } /** * This kludge of code is to handle compile-time literal reduction. We need to avoid * reducing for certain literals like, 'this', ternary and ternary else. */ if (!verifyOnly && tk.isLiteral()) { if (literalOnly == -1) literalOnly = 1; if ((tkOp = nextTokenSkipSymbols()) != null && tkOp.isOperator() && !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) { /** * If the next token is ALSO a literal, then we have a candidate for a compile-time literal * reduction. */ if ((tkLA = nextTokenSkipSymbols()) != null && tkLA.isLiteral() && tkOp.getOperator() < 34 && ((lastOp == -1 || (lastOp < PTABLE.length && PTABLE[lastOp] < PTABLE[tkOp.getOperator()])))) { stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), op = tkOp.getOperator()); /** * Reduce the token now. */ if (isArithmeticOperator(op)) { if (!compileReduce(op, astBuild)) continue; } else { reduce(); } firstLA = true; /** * Now we need to check to see if this is a continuing reduction. */ while ((tkOp2 = nextTokenSkipSymbols()) != null) { if (isBooleanOperator(tkOp2.getOperator())) { astBuild.addTokenNode(new LiteralNode(stk.pop()), verify(pCtx, tkOp2)); break; } else if ((tkLA2 = nextTokenSkipSymbols()) != null) { if (tkLA2.isLiteral()) { stk.push(tkLA2.getLiteralValue(), op = tkOp2.getOperator()); if (isArithmeticOperator(op)) { compileReduce(op, astBuild); } else { reduce(); } } else { /** * A reducable line of literals has ended. We must now terminate here and * leave the rest to be determined at runtime. */ if (!stk.isEmpty()) { astBuild.addTokenNode(new LiteralNode(getStackValueResult())); } astBuild.addTokenNode(new OperatorNode(tkOp2.getOperator()), verify(pCtx, tkLA2)); break; } firstLA = false; literalOnly = 0; } else { if (firstLA) { /** * There are more tokens, but we can't reduce anymore. So * we create a reduced token for what we've got. */ astBuild.addTokenNode(new LiteralNode(getStackValueResult())); } else { /** * We have reduced additional tokens, but we can't reduce * anymore. */ astBuild.addTokenNode(new LiteralNode(getStackValueResult()), tkOp2); if (tkLA2 != null) astBuild.addTokenNode(verify(pCtx, tkLA2)); } break; } } /** * If there are no more tokens left to parse, we check to see if * we've been doing any reducing, and if so we create the token * now. */ if (!stk.isEmpty()) astBuild.addTokenNode(new LiteralNode(getStackValueResult())); continue; } else { astBuild.addTokenNode(verify(pCtx, tk), verify(pCtx, tkOp)); if (tkLA != null) astBuild.addTokenNode(verify(pCtx, tkLA)); continue; } } else if (tkOp != null && !tkOp.isOperator() && !(tk.getLiteralValue() instanceof Class)) { throw new CompileException("unexpected token: " + tkOp.getName()); } else { literalOnly = 0; astBuild.addTokenNode(verify(pCtx, tk)); if (tkOp != null) astBuild.addTokenNode(verify(pCtx, tkOp)); continue; } } else { if (tk.isOperator()) { lastOp = tk.getOperator(); } else { literalOnly = 0; } } astBuild.addTokenNode(verify(pCtx, tk)); } astBuild.finish(); if (verifying && !verifyOnly) { pCtx.processTables(); } if (!stk.isEmpty()) { throw new CompileException("COMPILE ERROR: non-empty stack after compile."); } if (!verifyOnly) { return new CompiledExpression(finalizePayload(astBuild, secondPassOptimization, pCtx), pCtx.getSourceFile(), returnType, pCtx, literalOnly == 1); } else { return null; } } catch (NullPointerException e) { throw new CompileException("not a statement, or badly formed structure", e); } catch (CompileException e) { e.setExpr(expr); e.setLineNumber(pCtx.getLineCount()); e.setCursor(cursor); e.setColumn(cursor - pCtx.getLineOffset()); throw e; } catch (Throwable e) { parserContext.set(null); if (e instanceof RuntimeException) throw (RuntimeException) e; else { throw new CompileException(e.getMessage(), e); } } } private Object getStackValueResult() { return (fields & OPT_SUBTR) == 0 ? stk.pop() : signNumber(stk.pop()); } private boolean compileReduce(int opCode, ASTLinkedList astBuild) { switch (arithmeticFunctionReduction(opCode)) { case -1: /** * The reduction failed because we encountered a non-literal, * so we must now back out and cleanup. */ stk.xswap_op(); astBuild.addTokenNode(new LiteralNode(stk.pop())); astBuild.addTokenNode( (OperatorNode) splitAccumulator.pop(), verify(pCtx, (ASTNode) splitAccumulator.pop()) ); return false; case -2: /** * Back out completely, pull everything back off the stack and add the instructions * to the output payload as they are. */ LiteralNode rightValue = new LiteralNode(stk.pop()); OperatorNode operator = new OperatorNode((Integer) stk.pop()); astBuild.addTokenNode(new LiteralNode(stk.pop()), operator); astBuild.addTokenNode(rightValue, (OperatorNode) splitAccumulator.pop()); astBuild.addTokenNode(verify(pCtx, (ASTNode) splitAccumulator.pop())); } return true; } private static boolean isBooleanOperator(int operator) { return operator == Operator.AND || operator == Operator.OR || operator == Operator.TERNARY || operator == Operator.TERNARY_ELSE; } protected ASTNode verify(ParserContext pCtx, ASTNode tk) { if (tk.isOperator() && (tk.getOperator().equals(Operator.AND) || tk.getOperator().equals(Operator.OR))) { secondPassOptimization = true; } if (tk.isDiscard() || tk.isOperator()) { return tk; } else if (tk.isLiteral()) { /** * Convert literal values from the default ASTNode to the more-efficient LiteralNode. */ if ((fields & COMPILE_IMMEDIATE) != 0 && tk.getClass() == ASTNode.class) { return new LiteralNode(tk.getLiteralValue()); } else { return tk; } } if (verifying) { if (tk.isIdentifier()) { PropertyVerifier propVerifier = new PropertyVerifier(tk.getNameAsArray(), pCtx); if (tk instanceof Union) { propVerifier.setCtx(((Union) tk).getLeftEgressType()); tk.setEgressType(returnType = propVerifier.analyze()); } else { tk.setEgressType(returnType = propVerifier.analyze()); if (propVerifier.isClassLiteral()) { return new LiteralNode(returnType); } if (propVerifier.isResolvedExternally()) { pCtx.addInput(tk.getAbsoluteName(), propVerifier.isDeepProperty() ? Object.class : returnType); } } } else if (tk.isAssignment()) { Assignment a = (Assignment) tk; if (a.getAssignmentVar() != null) { PropertyVerifier propVerifier = new PropertyVerifier(a.getAssignmentVar(), pCtx); tk.setEgressType(returnType = propVerifier.analyze()); if (!a.isNewDeclaration() && propVerifier.isResolvedExternally()) { pCtx.addInput(tk.getAbsoluteName(), returnType); } ExecutableStatement c = (ExecutableStatement) subCompileExpression(a.getExpression(), pCtx); if (pCtx.isStrictTypeEnforcement()) { /** * If we're using strict type enforcement, we need to see if this coercion can be done now, * or fail epicly. */ if (!returnType.isAssignableFrom(c.getKnownEgressType()) && c.isLiteralOnly()) { if (canConvert(c.getKnownEgressType(), returnType)) { /** * We convert the literal to the proper type. */ try { a.setValueStatement(new ExecutableLiteral(convert(c.getValue(null, null), returnType))); return tk; } catch (Exception e) { // fall through. } } else if (returnType.isPrimitive() && unboxPrimitive(c.getKnownEgressType()).equals(returnType)) { /** * We ignore boxed primitive cases, since MVEL does not recognize primitives. */ return tk; } throw new CompileException( "cannot assign type " + c.getKnownEgressType().getName() + " to " + returnType.getName()); } } } } else if (tk instanceof NewObjectNode) { // this is a bit of a hack for now. NewObjectNode n = (NewObjectNode) tk; String[] parms = ParseTools.parseMethodOrConstructor(tk.getNameAsArray()); if (parms != null) { for (String p : parms) { MVEL.analyze(p, pCtx); } } } returnType = tk.getEgressType(); } if (!tk.isLiteral() && tk.getClass() == ASTNode.class && (tk.getFields() & ASTNode.ARRAY_TYPE_LITERAL) == 0) { if (pCtx.isStrongTyping()) tk.strongTyping(); tk.storePctx(); tk.storeInLiteralRegister(pCtx); } return tk; } public ExpressionCompiler(String expression) { setExpression(expression); } public ExpressionCompiler(String expression, boolean verifying) { setExpression(expression); this.verifying = verifying; } public ExpressionCompiler(char[] expression) { setExpression(expression); } public ExpressionCompiler(String expression, ParserContext ctx) { setExpression(expression); contextControl(SET, ctx, this); } public ExpressionCompiler(char[] expression, ParserContext ctx) { setExpression(expression); contextControl(SET, ctx, this); } public boolean isVerifying() { return verifying; } public void setVerifying(boolean verifying) { this.verifying = verifying; } public boolean isVerifyOnly() { return verifyOnly; } public void setVerifyOnly(boolean verifyOnly) { this.verifyOnly = verifyOnly; } public Class getReturnType() { return returnType; } public void setReturnType(Class returnType) { this.returnType = returnType; } public String getExpression() { return new String(expr); } public ParserContext getParserContextState() { return pCtx; } public void removeParserContext() { removeContext(); } public boolean isLiteralOnly() { return literalOnly == 1; } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/ExecutableStatement.java0000644000175000017500000000250111077457613026304 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.integration.VariableResolverFactory; import java.io.Serializable; public interface ExecutableStatement extends Accessor, Serializable, Cloneable { public Object getValue(Object staticContext, VariableResolverFactory factory); public void setKnownIngressType(Class type); public void setKnownEgressType(Class type); public Class getKnownIngressType(); public Class getKnownEgressType(); public boolean isConvertableIngressEgress(); public void computeTypeConversionRule(); public boolean intOptimized(); public boolean isLiteralOnly(); } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/ExecutableAccessorSafe.java0000644000175000017500000000500711253550035026671 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.ast.ASTNode; import org.mvel2.ast.Safe; import org.mvel2.integration.VariableResolverFactory; public class ExecutableAccessorSafe implements ExecutableStatement, Safe { private ASTNode node; private Class ingress; private Class egress; private boolean convertable; public ExecutableAccessorSafe(ASTNode node) { this.node = node; } public ExecutableAccessorSafe(ASTNode node, Class returnType) { this.node = node; this.egress = returnType; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { return node.getReducedValueAccelerated(ctx, elCtx, variableFactory); } public Object getValue(Object staticContext, VariableResolverFactory factory) { return node.getReducedValueAccelerated(staticContext, staticContext, factory); } public void setKnownIngressType(Class type) { this.ingress = type; } public void setKnownEgressType(Class type) { this.egress = type; } public Class getKnownIngressType() { return ingress; } public Class getKnownEgressType() { return egress; } public boolean isConvertableIngressEgress() { return convertable; } public void computeTypeConversionRule() { if (ingress != null && egress != null) { convertable = ingress.isAssignableFrom(egress); } } public boolean intOptimized() { return false; } public ASTNode getNode() { return node; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } public boolean isLiteralOnly() { return false; } }mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/Accessor.java0000644000175000017500000000204511077457613024103 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.integration.VariableResolverFactory; public interface Accessor { public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory); public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value); public Class getKnownEgressType(); } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/AbstractParser.java0000644000175000017500000032444211367363624025271 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.CompileException; import org.mvel2.ErrorDetail; import org.mvel2.Operator; import static org.mvel2.Operator.*; import org.mvel2.ParserContext; import org.mvel2.ast.*; import static org.mvel2.ast.TypeDescriptor.getClassReference; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ArrayTools.findFirst; import static org.mvel2.util.ArrayTools.isLiteralOnly; import org.mvel2.util.ExecutionStack; import org.mvel2.util.FunctionParser; import static org.mvel2.util.ParseTools.*; import static org.mvel2.util.PropertyTools.isEmpty; import org.mvel2.util.ProtoParser; import org.mvel2.util.Soundex; import java.io.Serializable; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.lang.Double.parseDouble; import static java.lang.Runtime.getRuntime; import static java.lang.System.getProperty; import static java.lang.Thread.currentThread; import java.util.HashMap; import java.util.WeakHashMap; /** * This is the core parser that the subparsers extend. * * @author Christopher Brock */ public class AbstractParser implements Serializable { protected char[] expr; protected int cursor; protected int start; protected int length; protected int fields; protected static final int OP_OVERFLOW = -2; protected static final int OP_TERMINATE = -1; protected static final int OP_RESET_FRAME = 0; protected static final int OP_CONTINUE = 1; protected boolean greedy = true; protected boolean lastWasIdentifier = false; protected boolean lastWasLineLabel = false; protected boolean lastWasComment = false; protected boolean compileMode = false; protected int literalOnly = -1; protected int lastLineStart = 0; protected int line = 0; protected ASTNode lastNode; private static final WeakHashMap EX_PRECACHE = new WeakHashMap(15); public static HashMap LITERALS; public static HashMap OPERATORS; protected ExecutionStack stk; protected ExecutionStack splitAccumulator = new ExecutionStack(); protected static ThreadLocal parserContext; protected ParserContext pCtx; protected ExecutionStack dStack; protected Object ctx; protected VariableResolverFactory variableFactory; protected boolean debugSymbols = false; static { setupParser(); } /** * This method is internally called by the static initializer for AbstractParser in order to setup the parser. * The static initialization populates the operator and literal tables for the parser. In some situations, like * OSGi, it may be necessary to utilize this manually. */ public static void setupParser() { if (LITERALS == null || LITERALS.isEmpty()) { LITERALS = new HashMap(); OPERATORS = new HashMap(); LITERALS.put("true", TRUE); LITERALS.put("false", FALSE); LITERALS.put("null", null); LITERALS.put("nil", null); LITERALS.put("empty", BlankLiteral.INSTANCE); /** * Add System and all the class wrappers from the JCL. */ LITERALS.put("System", System.class); LITERALS.put("String", String.class); LITERALS.put("CharSequence", CharSequence.class); LITERALS.put("Integer", Integer.class); LITERALS.put("int", Integer.class); LITERALS.put("Long", Long.class); LITERALS.put("long", Long.class); LITERALS.put("Boolean", Boolean.class); LITERALS.put("boolean", Boolean.class); LITERALS.put("Short", Short.class); LITERALS.put("short", Short.class); LITERALS.put("Character", Character.class); LITERALS.put("char", Character.class); LITERALS.put("Double", Double.class); LITERALS.put("double", Double.class); LITERALS.put("Float", Float.class); LITERALS.put("float", Float.class); LITERALS.put("Byte", Byte.class); LITERALS.put("byte", Byte.class); LITERALS.put("Math", Math.class); LITERALS.put("Void", Void.class); LITERALS.put("Object", Object.class); LITERALS.put("Number", Number.class); LITERALS.put("Class", Class.class); LITERALS.put("ClassLoader", ClassLoader.class); LITERALS.put("Runtime", Runtime.class); LITERALS.put("Thread", Thread.class); LITERALS.put("Compiler", Compiler.class); LITERALS.put("StringBuffer", StringBuffer.class); LITERALS.put("ThreadLocal", ThreadLocal.class); LITERALS.put("SecurityManager", SecurityManager.class); LITERALS.put("StrictMath", StrictMath.class); LITERALS.put("Array", java.lang.reflect.Array.class); if (parseDouble(getProperty("java.version").substring(0, 3)) >= 1.5) { try { LITERALS.put("StringBuilder", currentThread().getContextClassLoader().loadClass("java.lang.StringBuilder")); } catch (Exception e) { throw new RuntimeException("cannot resolve a built-in literal", e); } } setLanguageLevel(Boolean.getBoolean("mvel.future.lang.support") ? 6 : 5); } } protected ASTNode nextTokenSkipSymbols() { ASTNode n = nextToken(); if (n != null && n.getFields() == -1) n = nextToken(); return n; } /** * Retrieve the next token in the expression. * * @return - */ protected ASTNode nextToken() { try { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (!splitAccumulator.isEmpty()) { lastNode = (ASTNode) splitAccumulator.pop(); if (cursor >= length && lastNode instanceof EndOfStatement) { return nextToken(); } else { return lastNode; } } else if (cursor >= length) { return null; } int brace, idx; start = cursor; char[] tmp; String name; /** * Because of parser recursion for sub-expression parsing, we sometimes need to remain * certain field states. We do not reset for assignments, boolean mode, list creation or * a capture only mode. */ boolean capture = false, union = false; if ((fields & ASTNode.COMPILE_IMMEDIATE) != 0 && pCtx == null) { debugSymbols = (pCtx = getParserContext()).isDebugSymbols(); } if (debugSymbols) { if (!lastWasLineLabel) { if (pCtx.getSourceFile() == null) { throw new CompileException("unable to produce debugging symbols: source name must be provided."); } line = pCtx.getLineCount(); skipWhitespace(); if (!pCtx.isKnownLine(pCtx.getSourceFile(), pCtx.setLineCount(line)) && !pCtx.isBlockSymbols()) { lastWasLineLabel = true; pCtx.setLineAndOffset(line, cursor); return lastNode = pCtx.setLastLineLabel(new LineLabel(pCtx.getSourceFile(), line)); } } else { lastWasComment = lastWasLineLabel = false; } } /** * Skip any whitespace currently under the starting point. */ skipWhitespace(); /** * From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for * trouble unless you really know what you're doing. */ start = cursor; Mainloop: while (cursor != length) { if (isIdentifierPart(expr[cursor])) { capture = true; cursor++; while (cursor != length && isIdentifierPart(expr[cursor])) cursor++; } /** * If the current character under the cursor is a valid * part of an identifier, we keep capturing. */ if (capture) { String t; if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) { switch (OPERATORS.get(t)) { case NEW: if (!isIdentifierPart(expr[start = cursor = trimRight(cursor)])) { throw new CompileException("unexpected character (expected identifier): " + expr[cursor], expr, cursor); } /** * Capture the beginning part of the token. */ do { captureToNextTokenJunction(); skipWhitespace(); } while (cursor < length && expr[cursor] == '['); /** * If it's not a dimentioned array, continue capturing if necessary. */ if (cursor < length && !lastNonWhite(']')) captureToEOT(); TypeDescriptor descr = new TypeDescriptor(subArray(start, cursor), fields); if (pCtx == null) pCtx = getParserContext(); if (pCtx.hasProtoImport(descr.getClassName())) { return lastNode = new NewPrototypeNode(descr); } lastNode = new NewObjectNode(descr, fields, pCtx); skipWhitespace(); if (cursor != length && expr[cursor] == '{') { if (!((NewObjectNode) lastNode).getTypeDescr().isUndimensionedArray()) { throw new CompileException( "conflicting syntax: dimensioned array with initializer block", expr, cursor); } start = cursor; Class egressType = lastNode.getEgressType(); if (egressType == null) { try { egressType = getClassReference(pCtx, descr); } catch (ClassNotFoundException e) { throw new CompileException("could not instantiate class", e); } } cursor = balancedCaptureWithLineAccounting(expr, cursor, expr[cursor], pCtx) + 1; if (tokenContinues()) { lastNode = new InlineCollectionNode(expr, start, start = cursor, fields, egressType, pCtx); captureToEOT(); return lastNode = new Union(expr, start + 1, cursor, fields, lastNode); } else { return lastNode = new InlineCollectionNode(expr, start, cursor, fields, egressType, pCtx); } } else if (((NewObjectNode) lastNode).getTypeDescr().isUndimensionedArray()) { throw new CompileException("array initializer expected", expr, cursor); } return lastNode; case ASSERT: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new AssertNode(subArray(start, cursor--), fields, pCtx); case RETURN: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new ReturnNode(subArray(start, cursor), fields, pCtx); case IF: return captureCodeBlock(ASTNode.BLOCK_IF); case ELSE: throw new CompileException("else without if", cursor); case FOREACH: return captureCodeBlock(ASTNode.BLOCK_FOREACH); case WHILE: return captureCodeBlock(ASTNode.BLOCK_WHILE); case UNTIL: return captureCodeBlock(ASTNode.BLOCK_UNTIL); case FOR: return captureCodeBlock(ASTNode.BLOCK_FOR); case WITH: return captureCodeBlock(ASTNode.BLOCK_WITH); case DO: return captureCodeBlock(ASTNode.BLOCK_DO); case PROTO: return captureCodeBlock(PROTO); case ISDEF: start = cursor = trimRight(cursor); captureToNextTokenJunction(); return lastNode = new IsDef(subArray(start, cursor)); case IMPORT: start = cursor = trimRight(cursor); captureToEOS(); ImportNode importNode = new ImportNode(subArray(start, cursor)); if (pCtx == null) pCtx = getParserContext(); if (importNode.isPackageImport()) { pCtx.addPackageImport(importNode.getPackageImport()); } else { pCtx.addImport(importNode.getImportClass().getSimpleName(), importNode.getImportClass()); } return lastNode = importNode; case IMPORT_STATIC: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new StaticImportNode(subArray(start, cursor)); case FUNCTION: lastNode = captureCodeBlock(FUNCTION); start = cursor + 1; return lastNode; case UNTYPED_VAR: int end; start = cursor + 1; while (true) { captureToEOT(); end = cursor; skipWhitespace(); if (cursor != length && expr[cursor] == '=') { if (end == (cursor = start)) throw new CompileException("illegal use of reserved word: var"); continue Mainloop; } else { name = new String(subArray(start, end)); if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { splitAccumulator.add(lastNode = new IndexedDeclTypedVarNode(idx, Object.class)); } else { splitAccumulator.add(lastNode = new DeclTypedVarNode(name, Object.class, fields, pCtx)); } } if (cursor == length || expr[cursor] != ',') break; else { cursor++; skipWhitespace(); start = cursor; } } return (ASTNode) splitAccumulator.pop(); } } skipWhitespace(); /** * If we *were* capturing a token, and we just hit a non-identifier * character, we stop and figure out what to do. */ if (cursor != length && expr[cursor] == '(') { cursor = balancedCaptureWithLineAccounting(expr, cursor, '(', pCtx) + 1; } /** * If we encounter any of the following cases, we are still dealing with * a contiguous token. */ CaptureLoop: while (cursor != length) { switch (expr[cursor]) { case '.': union = true; cursor++; skipWhitespace(); continue; case '?': if (lookToLast() == '.') { union = true; cursor++; continue; } else { break CaptureLoop; } case '+': switch (lookAhead()) { case '+': name = new String(subArray(start, trimLeft(cursor))); if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { lastNode = new IndexedPostFixIncNode(idx); } else { lastNode = new PostFixIncNode(name); } cursor += 2; expectEOS(); return lastNode; case '=': name = createStringTrimmed(expr, start, cursor - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, ADD, name, pCtx); } else if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedAssignmentNode(subArray(start, cursor), fields, ADD, name, idx, pCtx); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), ADD, fields, pCtx); } } if (isDigit(lookAhead()) && cursor > 1 && (expr[cursor - 1] == 'E' || expr[cursor - 1] == 'e') && isDigit(expr[cursor - 2])) { cursor++; // capture = true; continue Mainloop; } break CaptureLoop; case '-': switch (lookAhead()) { case '-': name = new String(subArray(start, trimLeft(cursor))); if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { lastNode = new IndexedPostFixDecNode(idx); } else { lastNode = new PostFixDecNode(name); } cursor += 2; expectEOS(); return lastNode; case '=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, SUB, t, pCtx); } else if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), SUB, idx, fields, pCtx); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), SUB, fields, pCtx); } } if (isDigit(lookAhead()) && cursor > 1 && (expr[cursor - 1] == 'E' || expr[cursor - 1] == 'e') && isDigit(expr[cursor - 2])) { cursor++; capture = true; continue Mainloop; } break CaptureLoop; /** * Exit immediately for any of these cases. */ case '!': case ',': case '"': case '\'': case ';': case ':': break CaptureLoop; case '\u00AB': // special compact code for recursive parses case '\u00BB': case '\u00AC': case '&': case '^': case '|': case '*': case '/': case '%': char op = expr[cursor]; if (lookAhead() == '=') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, opLookup(op), t, pCtx); } else if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), opLookup(op), idx, fields, pCtx); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), opLookup(op), fields, pCtx); } } break CaptureLoop; case '<': if ((lookAhead() == '<' && lookAhead(2) == '=')) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 3; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, BW_SHIFT_LEFT, t, pCtx); } else if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), BW_SHIFT_LEFT, idx, fields, pCtx); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), BW_SHIFT_LEFT, fields, pCtx); } } break CaptureLoop; case '>': if (lookAhead() == '>') { if (lookAhead(2) == '=') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 3; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, BW_SHIFT_RIGHT, t, pCtx); } else if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), BW_SHIFT_RIGHT, idx, fields, pCtx); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), BW_SHIFT_RIGHT, fields, pCtx); } } else if ((lookAhead(2) == '>' && lookAhead(3) == '=')) { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 4; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, BW_USHIFT_RIGHT, t, pCtx); } else if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), BW_USHIFT_RIGHT, idx, fields, pCtx); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), BW_USHIFT_RIGHT, fields, pCtx); } } } break CaptureLoop; case '(': cursor = balancedCaptureWithLineAccounting(expr, cursor, '(', pCtx) + 1; continue; case '[': cursor = balancedCaptureWithLineAccounting(expr, cursor, '[', pCtx) + 1; continue; case '{': if (!union) break CaptureLoop; cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx) + 1; continue; case '~': if (lookAhead() == '=') { tmp = subArray(start, trimLeft(cursor)); start = cursor += 2; captureToEOT(); return lastNode = new RegExMatch(tmp, fields, subArray(start, cursor), pCtx); } break CaptureLoop; case '=': if (lookAhead() == '+') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOS(); if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), ADD, idx, fields, pCtx); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), ADD, fields, pCtx); } } else if (lookAhead() == '-') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOS(); if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), SUB, idx, fields, pCtx); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), SUB, fields, pCtx); } } if (greedy && lookAhead() != '=') { cursor++; if (union) { captureToEOS(); return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields | ASTNode.ASSIGN, pCtx); } else if (lastWasIdentifier) { return procTypedNode(false); } else if (pCtx != null && ((idx = pCtx.variableIndexOf(t)) != -1 || (pCtx.isIndexAllocation()))) { captureToEOS(); IndexedAssignmentNode ian = new IndexedAssignmentNode(subArray(start, cursor), ASTNode.ASSIGN, idx, pCtx); if (idx == -1) { pCtx.addIndexedVariable(t = ian.getAssignmentVar()); ian.setRegister(pCtx.variableIndexOf(t)); } return lastNode = ian; } else { captureToEOS(); return lastNode = new AssignmentNode(subArray(start, cursor), fields | ASTNode.ASSIGN, pCtx); } } break CaptureLoop; default: if (cursor != length) { if (isIdentifierPart(expr[cursor])) { if (!union) { break CaptureLoop; } cursor++; while (cursor != length && isIdentifierPart(expr[cursor])) cursor++; } else if ((cursor + 1) != length && isIdentifierPart(expr[cursor + 1])) { break CaptureLoop; } else { cursor++; } } else { break CaptureLoop; } } } /** * Produce the token. */ trimWhitespace(); return createPropertyToken(start, cursor); } else { switch (expr[cursor]) { case '.': { cursor++; if (isDigit(expr[cursor])) { capture = true; continue; } expectNextChar_IW('{'); return lastNode = new ThisWithNode(subArray(start, cursor - 1), subArray(cursor + 1, (cursor = balancedCaptureWithLineAccounting(expr, start = cursor, '{', pCtx) + 1) - 1), fields, pCtx); } case '@': { start++; captureToEOT(); if (pCtx == null || (pCtx.getInterceptors() == null || !pCtx.getInterceptors(). containsKey(name = new String(expr, start, cursor - start)))) { throw new CompileException("reference to undefined interceptor: " + new String(expr, start, cursor - start), expr, cursor); } return lastNode = new InterceptorWrapper(pCtx.getInterceptors().get(name), nextToken()); } case '=': return createOperator(expr, start, (cursor += 2)); case '-': if (lookAhead() == '-') { cursor += 2; skipWhitespace(); start = cursor; captureIdentifier(); name = new String(subArray(start, cursor)); if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedPreFixDecNode(idx); } else { return lastNode = new PreFixDecNode(name); } } else if ((cursor == 0 || (lastNode != null && (lastNode instanceof BooleanNode || lastNode.isOperator()))) && !isDigit(lookAhead())) { captureToEOT(); return new Sign(expr, start, cursor, fields, pCtx); } else if ((cursor != 0 && !isWhitespace(expr[cursor - 1]) && ( !(lastNode != null && (lastNode instanceof BooleanNode || lastNode.isOperator())))) || !isDigit(lookAhead())) { return createOperator(expr, start, cursor++ + 1); } else if ((cursor - 1) != 0 || (!isDigit(expr[cursor - 1])) && isDigit(lookAhead())) { cursor++; break; } else { throw new CompileException("not a statement", expr, cursor); } case '+': if (lookAhead() == '+') { cursor += 2; skipWhitespace(); start = cursor; captureIdentifier(); name = new String(subArray(start, cursor)); if (pCtx != null && (idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedPreFixIncNode(idx); } else { return lastNode = new PreFixIncNode(name); } } return createOperator(expr, start, cursor++ + 1); case '*': if (lookAhead() == '*') { cursor++; } return createOperator(expr, start, cursor++ + 1); case ';': cursor++; lastWasIdentifier = false; return lastNode = new EndOfStatement(); case '#': case '/': case '?': case ':': case '^': case '%': { return createOperator(expr, start, cursor++ + 1); } case '(': { cursor++; boolean singleToken = true; boolean lastWS = false; skipWhitespace(); for (brace = 1; cursor != length && brace != 0; cursor++) { switch (expr[cursor]) { case '(': brace++; break; case ')': brace--; break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('"', expr, cursor, length); break; case 'i': if (brace == 1 && lookAhead() == 'n' && isWhitespace(lookAhead(2))) { for (int level = brace; cursor != length; cursor++) { switch (expr[cursor]) { case '(': brace++; break; case ')': if (--brace < level) { cursor++; if (tokenContinues()) { lastNode = new Fold(subset(expr, trimRight(start + 1), cursor - start - 2), fields, pCtx); if (expr[start = cursor] == '.') start++; captureToEOT(); return lastNode = new Union(expr, trimRight(start), cursor, fields, lastNode); } else { return lastNode = new Fold(subset(expr, trimRight(start + 1), cursor - start - 2), fields, pCtx); } } break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('\"', expr, cursor, length); break; } } throw new CompileException("unterminated projection; closing parathesis required", expr, cursor); } break; default: /** * Check to see if we should disqualify this current token as a potential * type-cast candidate. */ if (lastWS) { if (expr[cursor] != '.') { switch (expr[cursor]) { case '[': case ']': break; default: if (!(isIdentifierPart(expr[cursor]) || expr[cursor] == '.')) { singleToken = false; } } } } else if (isWhitespace(expr[cursor]) || cursor == 1) { lastWS = true; skipWhitespace(); cursor--; } } } if (brace != 0) { throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } tmp = null; if (singleToken) { int st; TypeDescriptor tDescr = new TypeDescriptor( tmp = subset(expr, st = trimRight(start + 1), trimLeft(cursor - 1) - st), fields); Class cls; try { if (tDescr.isClass() && (cls = getClassReference(pCtx, tDescr)) != null) { start = cursor; captureToEOS(); return lastNode = new TypeCast(subset(expr, start, cursor - start), cls, fields, pCtx); } } catch (ClassNotFoundException e) { // fallthrough } } if (tmp != null) { return handleUnion(handleSubstatement(new Substatement(tmp, fields, pCtx))); } else { return handleUnion( handleSubstatement( new Substatement( subset(expr, start = trimRight(start + 1), trimLeft(cursor - 1) - start), fields, pCtx))); } } case '}': case ']': case ')': { throw new CompileException("unbalanced braces", expr, cursor); } case '>': { if (expr[cursor + 1] == '>') { if (expr[cursor += 2] == '>') cursor++; return createOperator(expr, start, cursor); } else if (expr[cursor + 1] == '=') { return createOperator(expr, start, cursor += 2); } else { return createOperator(expr, start, ++cursor); } } case '<': { if (expr[++cursor] == '<') { if (expr[++cursor] == '<') cursor++; return createOperator(expr, start, cursor); } else if (expr[cursor] == '=') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '\'': case '"': lastNode = new LiteralNode(handleStringEscapes(subset(expr, start + 1, (cursor = captureStringLiteral(expr[cursor], expr, cursor, length)) - start - 1)) , String.class); cursor++; if (tokenContinues()) { return lastNode = handleUnion(lastNode); } return lastNode; case '&': { if (expr[cursor++ + 1] == '&') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '|': { if (expr[cursor++ + 1] == '|') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '~': if ((cursor++ - 1 != 0 || !isIdentifierPart(lookBehind())) && isDigit(expr[cursor])) { start = cursor; captureToEOT(); return lastNode = new Invert(subset(expr, start, cursor - start), fields, pCtx); } else if (expr[cursor] == '(') { start = cursor--; captureToEOT(); return lastNode = new Invert(subset(expr, start, cursor - start), fields, pCtx); } else { if (expr[cursor] == '=') cursor++; return createOperator(expr, start, cursor); } case '!': { ++cursor; if (isNextIdentifier()) { if (lastNode != null && !lastNode.isOperator()) { throw new CompileException("unexpected operator '!'", expr, cursor); } start = cursor; captureToEOT(); if ("new".equals(name = new String(expr, start, cursor - start)) || "isdef".equals(name)) { captureToEOT(); return lastNode = new Negation(subset(expr, start, cursor - start), fields, pCtx); } else { return lastNode = new Negation(name.toCharArray(), fields, pCtx); } } else if (expr[cursor] == '(') { start = cursor--; captureToEOT(); return lastNode = new Negation(subset(expr, start, cursor - start), fields, pCtx); } else if (expr[cursor] != '=') throw new CompileException("unexpected operator '!'", expr, cursor, null); else { return createOperator(expr, start, ++cursor); } } case '[': case '{': cursor = balancedCaptureWithLineAccounting(expr, cursor, expr[cursor], pCtx) + 1; if (tokenContinues()) { lastNode = new InlineCollectionNode(expr, start, start = cursor, fields, pCtx); captureToEOT(); if (expr[start] == '.') start++; return lastNode = new Union(expr, start, cursor, fields, lastNode); } else { return lastNode = new InlineCollectionNode(expr, start, cursor, fields, pCtx); } default: cursor++; } } } if (start == cursor) return null; else return createPropertyToken(start, cursor); } catch (NumberFormatException e) { CompileException c = new CompileException("badly formatted number: " + e.getMessage(), expr, cursor, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } catch (StringIndexOutOfBoundsException e) { CompileException c = new CompileException("unexpected end of statement", expr, cursor, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } catch (ArrayIndexOutOfBoundsException e) { CompileException c = new CompileException("unexpected end of statement", expr, cursor, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } catch (CompileException e) { e.setExpr(expr); e.setLineNumber(pCtx == null ? 1 : pCtx.getLineCount()); e.setCursor(cursor); e.setColumn(cursor - (pCtx == null ? 0 : pCtx.getLineOffset())); throw e; } } public ASTNode handleSubstatement(Substatement stmt) { if (stmt.getStatement() != null && stmt.getStatement().isLiteralOnly()) { return new LiteralNode(stmt.getStatement().getValue(null, null, null)); } else { return stmt; } } /** * Handle a union between a closed statement and a residual property chain. * @param node * @return */ protected ASTNode handleUnion(ASTNode node) { if (cursor != length) { skipWhitespace(); int union = -1; switch (expr[cursor]) { case '.': union = cursor + 1; break; case '[': union = cursor; } if (union != -1) { captureToEOT(); return lastNode = new Union(expr, union, cursor, fields, node); } } return lastNode = node; } /** * Create an operator node. * @param expr * @param start * @param end * @return */ private ASTNode createOperator(final char[] expr, final int start, final int end) { lastWasIdentifier = false; return lastNode = new OperatorNode(OPERATORS.get(new String(expr, start, end - start))); } /** * Create a copy of an array based on a sub-range. Works faster than System.arrayCopy() for arrays shorter than * 1000 elements in most cases, so the parser uses this internally. * @param start * @param end * @return */ private char[] subArray(final int start, final int end) { if (start >= end) return new char[0]; char[] newA = new char[end - start]; for (int i = 0; i != newA.length; i++) { newA[i] = expr[i + start]; } return newA; } /** * Generate a property token * @param start * @param end * @return */ private ASTNode createPropertyToken(int start, int end) { String tmp; if (isLiteralOnly(expr, start, end)) { if (pCtx != null && pCtx.hasImports()) { char[] _subset = subset(expr, start, cursor - start); int offset; if ((offset = findFirst('.', _subset)) != -1) { String iStr = new String(_subset, 0, offset); if (pCtx.hasImport(iStr)) { lastWasIdentifier = true; return lastNode = new LiteralDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields, pCtx.getImport(iStr)); } } else { if (pCtx.hasImport(tmp = new String(_subset))) { lastWasIdentifier = true; return lastNode = new LiteralNode(pCtx.getStaticOrClassImport(tmp)); } } } if (LITERALS.containsKey(tmp = new String(expr, start, end - start))) { lastWasIdentifier = true; return lastNode = new LiteralNode(LITERALS.get(tmp)); } else if (OPERATORS.containsKey(tmp)) { lastWasIdentifier = false; return lastNode = new OperatorNode(OPERATORS.get(tmp)); } else if (lastWasIdentifier) { return procTypedNode(true); } } lastWasIdentifier = true; return lastNode = new ASTNode(expr, start, end, fields); } /** * Process the current typed node * @param decl * @return */ private ASTNode procTypedNode(boolean decl) { while (true) { if (lastNode.getLiteralValue() instanceof String) { TypeDescriptor tDescr = new TypeDescriptor(((String) lastNode.getLiteralValue()).toCharArray(), 0); try { lastNode.setLiteralValue(getClassReference(pCtx, tDescr)); lastNode.discard(); } catch (Exception e) { // fall through; } } if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) { lastNode.discard(); captureToEOS(); if (decl) { splitAccumulator.add(new DeclTypedVarNode(new String(expr, start, cursor - start), (Class) lastNode.getLiteralValue(), fields | ASTNode.ASSIGN, pCtx)); } else { captureToEOS(); splitAccumulator.add(new TypedVarNode(subArray(start, cursor), fields | ASTNode.ASSIGN, (Class) lastNode.getLiteralValue(), pCtx)); } } else if (lastNode instanceof Proto) { captureToEOS(); if (decl) { splitAccumulator.add(new DeclProtoVarNode(new String(expr, start, cursor - start), (Proto) lastNode, fields | ASTNode.ASSIGN, pCtx)); } else { splitAccumulator.add(new ProtoVarNode(subArray(start, cursor), fields | ASTNode.ASSIGN, (Proto) lastNode, pCtx)); } } // this redundant looking code is needed to work with the interpreter and MVELSH properly. else if ((fields & ASTNode.COMPILE_IMMEDIATE) == 0) { if (stk.peek() instanceof Class) { captureToEOS(); if (decl) { splitAccumulator.add(new DeclTypedVarNode(new String(expr, start, cursor - start), (Class) stk.pop(), fields | ASTNode.ASSIGN, pCtx)); } else { splitAccumulator.add(new TypedVarNode(subArray(start, cursor), fields | ASTNode.ASSIGN, (Class) stk.pop(), pCtx)); } } else if (stk.peek() instanceof Proto) { captureToEOS(); if (decl) { splitAccumulator.add(new DeclProtoVarNode(new String(expr, start, cursor - start), (Proto) stk.pop(), fields | ASTNode.ASSIGN, pCtx)); } else { splitAccumulator.add(new ProtoVarNode(subArray(start, cursor), fields | ASTNode.ASSIGN, (Proto) stk.pop(), pCtx)); } } else { throw new CompileException("unknown class or illegal statement: " + lastNode.getLiteralValue(), expr, cursor); } } else { throw new CompileException("unknown class or illegal statement: " + lastNode.getLiteralValue(), expr, cursor); } skipWhitespace(); if (cursor < length && expr[cursor] == ',') { start = ++cursor; splitAccumulator.add(new EndOfStatement()); } else { return (ASTNode) splitAccumulator.pop(); } } } /** * Generate a code block token. * @param condStart * @param condEnd * @param blockStart * @param blockEnd * @param type * @return */ private ASTNode createBlockToken(final int condStart, final int condEnd, final int blockStart, final int blockEnd, int type) { lastWasIdentifier = false; cursor++; if (isStatementNotManuallyTerminated()) { splitAccumulator.add(new EndOfStatement()); } switch (type) { case ASTNode.BLOCK_IF: return new IfNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields, pCtx); case ASTNode.BLOCK_FOR: for (int i = condStart; i < condEnd; i++) { if (expr[i] == ';') return new ForNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields, pCtx); else if (expr[i] == ':') break; } case ASTNode.BLOCK_FOREACH: return new ForEachNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields, pCtx); case ASTNode.BLOCK_WHILE: return new WhileNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields, pCtx); case ASTNode.BLOCK_UNTIL: return new UntilNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields, pCtx); case ASTNode.BLOCK_DO: return new DoNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields, pCtx); case ASTNode.BLOCK_DO_UNTIL: return new DoUntilNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), pCtx); default: return new WithNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields, pCtx); } } /** * Capture a code block by type. * @param type * @return */ private ASTNode captureCodeBlock(int type) { boolean cond = true; ASTNode first = null; ASTNode tk = null; switch (type) { case ASTNode.BLOCK_IF: { do { if (tk != null) { captureToNextTokenJunction(); skipWhitespace(); cond = expr[cursor] != '{' && expr[cursor] == 'i' && expr[++cursor] == 'f' && expr[cursor = incNextNonBlank()] == '('; } if (((IfNode) (tk = _captureBlock(tk, expr, cond, type))).getElseBlock() != null) { cursor++; return first; } if (first == null) first = tk; if (cursor != length && expr[cursor] != ';') { cursor++; } } while (ifThenElseBlockContinues()); return first; } case ASTNode.BLOCK_DO: skipWhitespace(); return _captureBlock(null, expr, false, type); default: // either BLOCK_WITH or BLOCK_FOREACH captureToNextTokenJunction(); skipWhitespace(); return _captureBlock(null, expr, true, type); } } private ASTNode _captureBlock(ASTNode node, final char[] expr, boolean cond, int type) { skipWhitespace(); int startCond = 0; int endCond = 0; int blockStart; int blockEnd; String name; /** * Functions are a special case we handle differently from the rest of block parsing */ switch (type) { case FUNCTION: { int start = cursor; captureToNextTokenJunction(); if (cursor == length) { throw new CompileException("unexpected end of statement", expr, start); } /** * Check to see if the name is legal. */ if (isReservedWord(name = createStringTrimmed(expr, start, cursor - start)) || isNotValidNameorLabel(name)) throw new CompileException("illegal function name or use of reserved word", expr, cursor); if (pCtx == null) pCtx = getParserContext(); FunctionParser parser = new FunctionParser(name, cursor, expr.length, expr, pCtx, splitAccumulator); Function function = parser.parse(); cursor = parser.getCursor(); return lastNode = function; } case PROTO: if (ProtoParser.isUnresolvedWaiting()) { if (pCtx == null) pCtx = getParserContext(); ProtoParser.checkForPossibleUnresolvedViolations(expr, cursor, pCtx); } int start = cursor; captureToNextTokenJunction(); if (isReservedWord(name = createStringTrimmed(expr, start, cursor - start)) || isNotValidNameorLabel(name)) throw new CompileException("illegal prototype name or use of reserved word", expr, cursor); if (expr[cursor = nextNonBlank()] != '{') { throw new CompileException("expected '{' but found: " + expr[cursor]); } cursor = balancedCaptureWithLineAccounting(expr, start = cursor + 1, '{', pCtx); if (pCtx == null) pCtx = getParserContext(); ProtoParser parser = new ProtoParser(expr, start, cursor, name, pCtx, fields, splitAccumulator); Proto proto = parser.parse(); if (pCtx == null) pCtx = getParserContext(); pCtx.addImport(proto); proto.setCursorPosition(start, cursor); cursor = parser.getCursor(); ProtoParser.notifyForLateResolution(proto); return lastNode = proto; default: if (cond) { if (expr[cursor] != '(') { throw new CompileException("expected '(' but encountered: " + expr[cursor]); } /** * This block is an: IF, FOREACH or WHILE node. */ endCond = cursor = balancedCaptureWithLineAccounting(expr, startCond = cursor, '(', pCtx); startCond++; cursor++; } } skipWhitespace(); if (cursor >= length) { throw new CompileException("unexpected end of statement", expr, cursor); } else if (expr[cursor] == '{') { blockEnd = cursor = balancedCaptureWithLineAccounting(expr, blockStart = cursor, '{', pCtx); } else { blockStart = cursor - 1; captureToEOSorEOL(); blockEnd = cursor + 1; } if (type == ASTNode.BLOCK_IF) { IfNode ifNode = (IfNode) node; if (node != null) { if (!cond) { return ifNode.setElseBlock(subArray(trimRight(blockStart + 1), trimLeft(blockEnd - 1))); } else { return ifNode.setElseIf((IfNode) createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type)); } } else { return createBlockToken(startCond, endCond, blockStart + 1, blockEnd, type); } } else if (type == ASTNode.BLOCK_DO) { cursor++; skipWhitespace(); start = cursor; captureToNextTokenJunction(); if ("while".equals(name = new String(expr, start, cursor - start))) { skipWhitespace(); startCond = cursor + 1; endCond = cursor = balancedCaptureWithLineAccounting(expr, cursor, '(', pCtx); return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type); } else if ("until".equals(name)) { skipWhitespace(); startCond = cursor + 1; endCond = cursor = balancedCaptureWithLineAccounting(expr, cursor, '(', pCtx); return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), ASTNode.BLOCK_DO_UNTIL); } else { throw new CompileException("expected 'while' or 'until' but encountered: " + name, expr, cursor); } } // DON"T REMOVE THIS COMMENT! // else if (isFlag(ASTNode.BLOCK_FOREACH) || isFlag(ASTNode.BLOCK_WITH)) { else { return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type); } } /** * Checking from the current cursor position, check to see if the if-then-else block continues. * * @return boolean value */ protected boolean ifThenElseBlockContinues() { if ((cursor + 4) < length) { if (expr[cursor] != ';') cursor--; skipWhitespace(); return expr[cursor] == 'e' && expr[cursor + 1] == 'l' && expr[cursor + 2] == 's' && expr[cursor + 3] == 'e' && (isWhitespace(expr[cursor + 4]) || expr[cursor + 4] == '{'); } return false; } /** * Checking from the current cursor position, check to see if we're inside a contiguous identifier. * * @return - */ protected boolean tokenContinues() { if (cursor == length) return false; else if (expr[cursor] == '.' || expr[cursor] == '[') return true; else if (isWhitespace(expr[cursor])) { int markCurrent = cursor; skipWhitespace(); if (cursor != length && (expr[cursor] == '.' || expr[cursor] == '[')) return true; cursor = markCurrent; } return false; } /** * The parser should find a statement ending condition when this is called, otherwise everything should blow up. */ protected void expectEOS() { skipWhitespace(); if (cursor != length && expr[cursor] != ';') { switch (expr[cursor]) { case '&': if (lookAhead() == '&') return; else break; case '|': if (lookAhead() == '|') return; else break; case '!': if (lookAhead() == '=') return; else break; case '<': case '>': return; case '=': { switch (lookAhead()) { case '=': case '+': case '-': case '*': return; } break; } case '+': case '-': case '/': case '*': if (lookAhead() == '=') return; else break; } throw new CompileException("expected end of statement but encountered: " + (cursor == length ? "" : expr[cursor]), expr, cursor); } } /** * Checks to see if the next part of the statement is an identifier part. * * @return boolean true if next part is identifier part. */ protected boolean isNextIdentifier() { while (cursor != length && isWhitespace(expr[cursor])) cursor++; return cursor != length && isIdentifierPart(expr[cursor]); } /** * Capture from the current cursor position, to the end of the statement. */ protected void captureToEOS() { while (cursor != length) { switch (expr[cursor]) { case '(': case '[': case '{': if ((cursor = balancedCaptureWithLineAccounting(expr, cursor, expr[cursor], pCtx)) >= length) return; break; case '"': case '\'': cursor = captureStringLiteral(expr[cursor], expr, cursor, length); break; case ',': case ';': case '}': return; } cursor++; } } /** * From the current cursor position, capture to the end of statement, or the end of line, whichever comes first. */ protected void captureToEOSorEOL() { while (cursor != length && (expr[cursor] != '\n' && expr[cursor] != '\r' && expr[cursor] != ';')) { cursor++; } } /** * From the current cursor position, capture to the end of the line. */ protected void captureToEOL() { while (cursor != length && (expr[cursor] != '\n')) cursor++; } /** * Capture to the end of the current identifier under the cursor. */ protected void captureIdentifier() { boolean captured = false; if (cursor == length) throw new CompileException("unexpected end of statement: EOF", expr, cursor); while (cursor != length) { switch (expr[cursor]) { case ';': return; default: { if (!isIdentifierPart(expr[cursor])) { if (captured) return; throw new CompileException("unexpected symbol (was expecting an identifier): " + expr[cursor], expr, cursor); } else { captured = true; } } } cursor++; } } /** * From the current cursor position, capture to the end of the current token. */ protected void captureToEOT() { skipWhitespace(); do { switch (expr[cursor]) { case '(': case '[': case '{': if ((cursor = balancedCaptureWithLineAccounting(expr, cursor, expr[cursor], pCtx)) == -1) { throw new CompileException("unbalanced braces", expr, cursor); } break; case ',': case '=': case '&': case '|': case ';': return; case '.': skipWhitespace(); break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('"', expr, cursor, length); break; default: if (isWhitespace(expr[cursor])) { skipWhitespace(); if (cursor < length && expr[cursor] == '.') { if (cursor != length) cursor++; skipWhitespace(); break; } else { trimWhitespace(); return; } } } } while (++cursor != length); } protected boolean lastNonWhite(char c) { int i = cursor - 1; while (isWhitespace(expr[i])) i--; return c == expr[i]; } /** * From the specified cursor position, trim out any whitespace between the current position and the end of the * last non-whitespace character. * * @param pos - current position * @return new position. */ protected int trimLeft(int pos) { if (pos > length) pos = length; while (pos > 0 && pos >= start && isWhitespace(expr[pos - 1])) pos--; return pos; } /** * From the specified cursor position, trim out any whitespace between the current position and beginning of the * first non-whitespace character. * * @param pos - * @return - */ protected int trimRight(int pos) { while (pos != length && isWhitespace(expr[pos])) pos++; return pos; } /** * If the cursor is currently pointing to whitespace, move the cursor forward to the first non-whitespace * character, but account for carraige returns in the script (updates parser field: line). */ protected void skipWhitespace() { Skip: while (cursor != length) { switch (expr[cursor]) { case '\n': line++; lastLineStart = cursor; case '\r': cursor++; continue; case '/': if (cursor + 1 != length) { switch (expr[cursor + 1]) { case '/': expr[cursor++] = ' '; while (cursor != length && expr[cursor] != '\n') expr[cursor++] = ' '; if (cursor != length) expr[cursor++] = ' '; line++; lastLineStart = cursor; continue; case '*': int len = length - 1; expr[cursor++] = ' '; while (cursor != len && !(expr[cursor] == '*' && expr[cursor + 1] == '/')) { if (expr[cursor] == '\n') { line++; lastLineStart = cursor; } expr[cursor++] = ' '; } if (cursor != len) expr[cursor++] = expr[cursor++] = ' '; continue; default: break Skip; } } default: if (!isWhitespace(expr[cursor])) break Skip; } cursor++; } } /** * From the current cursor position, capture to the end of the next token junction. */ protected void captureToNextTokenJunction() { while (cursor != length) { switch (expr[cursor]) { case '{': case '(': return; case '[': cursor = balancedCaptureWithLineAccounting(expr, cursor, '[', pCtx) + 1; continue; default: if (isWhitespace(expr[cursor])) { return; } cursor++; } } } /** * From the current cursor position, trim backward over any whitespace to the first non-whitespace character. */ protected void trimWhitespace() { while (cursor != 0 && isWhitespace(expr[cursor - 1])) cursor--; } /** * Set and finesse the expression, trimming an leading or proceeding whitespace. * * @param expression */ protected void setExpression(String expression) { if (expression != null && expression.length() != 0) { synchronized (EX_PRECACHE) { if ((this.expr = EX_PRECACHE.get(expression)) == null) { length = (this.expr = expression.toCharArray()).length; // trim any whitespace. while (length != 0 && isWhitespace(this.expr[length - 1])) length--; char[] e = new char[length]; for (int i = 0; i != e.length; i++) e[i] = expr[i]; EX_PRECACHE.put(expression, e); } else { length = this.expr.length; } } } } /** * Set and finesse the expression, trimming an leading or proceeding whitespace. * * @param expression */ protected void setExpression(char[] expression) { length = (this.expr = expression).length; while (length != 0 && isWhitespace(this.expr[length - 1])) length--; } /** * Return the previous non-whitespace character. * * @return - */ protected char lookToLast() { if (cursor == 0) return 0; int temp = cursor; while (temp != 0 && isWhitespace(expr[--temp])) ; return expr[temp]; } /** * Return the last character (delta -1 of cursor position). * * @return - */ protected char lookBehind() { if (cursor == 0) return 0; else return expr[cursor - 1]; } /** * Return the next character (delta 1 of cursor position). * * @return - */ protected char lookAhead() { if (cursor + 1 < length) { return expr[cursor + 1]; } else { return 0; } } /** * Return the character, forward of the currrent cursor position based on the specified range delta. * * @param range - * @return - */ protected char lookAhead(int range) { if ((cursor + range) >= length) return 0; else { return expr[cursor + range]; } } /** * Returns true if the next is an identifier or literal. * @return */ protected boolean isNextIdentifierOrLiteral() { int tmp = cursor; if (tmp == length) return false; else { while (tmp != length && isWhitespace(expr[tmp])) tmp++; if (tmp == length) return false; char n = expr[tmp]; return isIdentifierPart(n) || isDigit(n) || n == '\'' || n == '"'; } } /** * Increment one cursor position, and move cursor to next non-blank part. * @return */ public int incNextNonBlank() { cursor++; return nextNonBlank(); } /** * Move to next cursor position from current cursor position. * @return */ public int nextNonBlank() { if ((cursor + 1) >= length) { throw new CompileException("unexpected end of statement", expr, cursor); } int i = cursor; while (i != length && isWhitespace(expr[i])) i++; return i; } /** * Expect the next specified character or fail * @param c */ public void expectNextChar_IW(char c) { nextNonBlank(); if (cursor == length) throw new CompileException("unexpected end of statement", expr, cursor); if (expr[cursor] != c) throw new CompileException("unexpected character ('" + expr[cursor] + "'); was expecting: " + c); } /** * NOTE: This method assumes that the current position of the cursor is at the end of a logical statement, to * begin with. *

* Determines whether or not the logical statement is manually terminated with a statement separator (';'). * * @return - */ protected boolean isStatementNotManuallyTerminated() { if (cursor >= length) return false; int c = cursor; while (c != length && isWhitespace(expr[c])) c++; return !(c != length && expr[c] == ';'); } protected ParserContext getParserContext() { if (parserContext == null || parserContext.get() == null) { newContext(); } return parserContext.get(); } public static ParserContext getCurrentThreadParserContext() { return contextControl(GET_OR_CREATE, null, null); } public static void setCurrentThreadParserContext(ParserContext pCtx) { contextControl(SET, pCtx, null); } /** * Create a new ParserContext in the current thread. */ public void newContext() { contextControl(SET, new ParserContext(), this); } /** * Create a new ParserContext in the current thread, using the one specified. * * @param pCtx - */ public void newContext(ParserContext pCtx) { contextControl(SET, pCtx, this); } /** * Remove the current ParserContext from the thread. */ public void removeContext() { contextControl(REMOVE, null, this); } public static ParserContext contextControl(int operation, ParserContext pCtx, AbstractParser parser) { synchronized (getRuntime()) { if (parserContext == null) parserContext = new ThreadLocal(); switch (operation) { case SET: pCtx.setRootParser(parser); parserContext.set(pCtx); return pCtx; case REMOVE: parserContext.set(null); return null; case GET_OR_CREATE: if (parserContext.get() == null) { parserContext.set(new ParserContext(parser)); } case GET: return parserContext.get(); } } return null; } protected static final int SET = 0; protected static final int REMOVE = 1; protected static final int GET = 2; protected static final int GET_OR_CREATE = 3; protected static String getCurrentSourceFileName() { if (parserContext != null && parserContext.get() != null) { return parserContext.get().getSourceFile(); } return null; } protected void addFatalError(String message) { getParserContext().addError(new ErrorDetail(getParserContext().getLineCount(), cursor - getParserContext().getLineOffset(), true, message)); } protected void addFatalError(String message, int row, int cols) { getParserContext().addError(new ErrorDetail(row, cols, true, message)); } protected void addWarning(String message) { getParserContext().addError(new ErrorDetail(message, false)); } public static final int LEVEL_5_CONTROL_FLOW = 5; public static final int LEVEL_4_ASSIGNMENT = 4; public static final int LEVEL_3_ITERATION = 3; public static final int LEVEL_2_MULTI_STATEMENT = 2; public static final int LEVEL_1_BASIC_LANG = 1; public static final int LEVEL_0_PROPERTY_ONLY = 0; public static void setLanguageLevel(int level) { OPERATORS.clear(); OPERATORS.putAll(loadLanguageFeaturesByLevel(level)); } public static HashMap loadLanguageFeaturesByLevel(int languageLevel) { HashMap operatorsTable = new HashMap(); switch (languageLevel) { case 6: // prototype definition operatorsTable.put("proto", PROTO); case 5: // control flow operations operatorsTable.put("if", IF); operatorsTable.put("else", ELSE); operatorsTable.put("?", TERNARY); operatorsTable.put("switch", SWITCH); operatorsTable.put("function", FUNCTION); operatorsTable.put("def", FUNCTION); case 4: // assignment operatorsTable.put("=", ASSIGN); operatorsTable.put("var", UNTYPED_VAR); operatorsTable.put("+=", ASSIGN_ADD); operatorsTable.put("-=", ASSIGN_SUB); operatorsTable.put("/=", ASSIGN_DIV); operatorsTable.put("%=", ASSIGN_MOD); case 3: // iteration operatorsTable.put("foreach", FOREACH); operatorsTable.put("while", WHILE); operatorsTable.put("until", UNTIL); operatorsTable.put("for", FOR); operatorsTable.put("do", DO); case 2: // multi-statement operatorsTable.put("return", RETURN); operatorsTable.put(";", END_OF_STMT); case 1: // boolean, math ops, projection, assertion, objection creation, block setters, imports operatorsTable.put("+", ADD); operatorsTable.put("-", SUB); operatorsTable.put("*", MULT); operatorsTable.put("**", POWER); operatorsTable.put("/", DIV); operatorsTable.put("%", MOD); operatorsTable.put("==", EQUAL); operatorsTable.put("!=", NEQUAL); operatorsTable.put(">", GTHAN); operatorsTable.put(">=", GETHAN); operatorsTable.put("<", LTHAN); operatorsTable.put("<=", LETHAN); operatorsTable.put("&&", AND); operatorsTable.put("and", AND); operatorsTable.put("||", OR); operatorsTable.put("or", CHOR); operatorsTable.put("~=", REGEX); operatorsTable.put("instanceof", INSTANCEOF); operatorsTable.put("is", INSTANCEOF); operatorsTable.put("contains", CONTAINS); operatorsTable.put("soundslike", SOUNDEX); operatorsTable.put("strsim", SIMILARITY); operatorsTable.put("convertable_to", CONVERTABLE_TO); operatorsTable.put("isdef", ISDEF); operatorsTable.put("#", STR_APPEND); operatorsTable.put("&", BW_AND); operatorsTable.put("|", BW_OR); operatorsTable.put("^", BW_XOR); operatorsTable.put("<<", BW_SHIFT_LEFT); operatorsTable.put("<<<", BW_USHIFT_LEFT); operatorsTable.put(">>", BW_SHIFT_RIGHT); operatorsTable.put(">>>", BW_USHIFT_RIGHT); operatorsTable.put("new", Operator.NEW); operatorsTable.put("in", PROJECTION); operatorsTable.put("with", WITH); operatorsTable.put("assert", ASSERT); operatorsTable.put("import", IMPORT); operatorsTable.put("import_static", IMPORT_STATIC); operatorsTable.put("++", INC); operatorsTable.put("--", DEC); case 0: // Property access and inline collections operatorsTable.put(":", TERNARY_ELSE); } return operatorsTable; } /** * Remove the current parser context from the thread. */ public static void resetParserContext() { contextControl(REMOVE, null, null); } protected static boolean isArithmeticOperator(int operator) { return operator != -1 && operator < 6; } /** * Reduce the current operations on the stack. * @param operator * @return */ protected int arithmeticFunctionReduction(int operator) { ASTNode tk; int operator2; /** * If the next token is an operator, we check to see if it has a higher * precdence. */ if ((tk = nextToken()) != null) { if (isArithmeticOperator(operator2 = tk.getOperator()) && PTABLE[operator2] > PTABLE[operator]) { stk.xswap(); /** * The current arith. operator is of higher precedence the last. */ tk = nextToken(); /** * Check to see if we're compiling or executing interpretively. If we're compiling, we really * need to stop if this is not a literal. */ if (compileMode && !tk.isLiteral()) { // BAIL OUT! splitAccumulator.push(tk); splitAccumulator.push(new OperatorNode(operator2)); return tk instanceof Substatement ? -2 : OP_TERMINATE; } dStack.push(operator = operator2, tk.getReducedValue(ctx, ctx, variableFactory)); while (true) { // look ahead again if ((tk = nextToken()) != null && (operator2 = tk.getOperator()) != -1 && operator2 != 37 && PTABLE[operator2] > PTABLE[operator]) { // if we have back to back operations on the stack, we don't xswap if (dStack.isReduceable()) { stk.copyx2(dStack); } /** * This operator is of higher precedence, or the same level precedence. push to the RHS. */ dStack.push(operator = operator2, nextToken().getReducedValue(ctx, ctx, variableFactory)); continue; } else if (tk != null && operator2 != -1 && operator2 != 37) { if (PTABLE[operator2] == PTABLE[operator]) { if (!dStack.isEmpty()) dreduce(); else { while (stk.isReduceable()) { stk.xswap_op(); } } /** * This operator is of the same level precedence. push to the RHS. */ dStack.push(operator = operator2, nextToken().getReducedValue(ctx, ctx, variableFactory)); continue; } else { /** * The operator doesn't have higher precedence. Therfore reduce the LHS. */ while (dStack.size() > 1) { dreduce(); } operator = tk.getOperator(); // Reduce the lesser or equal precedence operations. while (stk.size() != 1 && stk.peek2() instanceof Integer && ((operator2 = (Integer) stk.peek2()) < PTABLE.length) && PTABLE[operator2] >= PTABLE[operator]) { stk.xswap_op(); } } } else { /** * There are no more tokens. */ if (dStack.size() > 1) { dreduce(); } if (stk.isReduceable()) stk.xswap(); break; } if ((tk = nextToken()) != null) { switch (operator) { case AND: { if (!(stk.peekBoolean())) return OP_TERMINATE; else { splitAccumulator.add(tk); return AND; } } case OR: { if ((stk.peekBoolean())) return OP_TERMINATE; else { splitAccumulator.add(tk); return OR; } } default: stk.push(operator, tk.getReducedValue(ctx, ctx, variableFactory)); } } } } else if (!tk.isOperator()) { throw new CompileException("unexpected token: " + tk.getName()); } else { reduce(); splitAccumulator.push(tk); } } // while any values remain on the stack // keep XSWAPing and reducing, until there is nothing left. while (stk.isReduceable()) { reduce(); if (stk.isReduceable()) stk.xswap(); } return OP_RESET_FRAME; } private void dreduce() { stk.copy2(dStack); stk.op(); } /** * This method is called when we reach the point where we must subEval a trinary operation in the expression. * (ie. val1 op val2). This is not the same as a binary operation, although binary operations would appear * to have 3 structures as well. A binary structure (or also a junction in the expression) compares the * current state against 2 downrange structures (usually an op and a val). */ protected void reduce() { Object v1, v2; int operator; try { switch (operator = (Integer) stk.pop()) { case ADD: case SUB: case DIV: case MULT: case MOD: case EQUAL: case NEQUAL: case GTHAN: case LTHAN: case GETHAN: case LETHAN: case POWER: stk.op(operator); break; case AND: v1 = stk.pop(); stk.push(((Boolean) stk.pop()) && ((Boolean) v1)); break; case OR: v1 = stk.pop(); stk.push(((Boolean) stk.pop()) || ((Boolean) v1)); break; case CHOR: v1 = stk.pop(); if (!isEmpty(v2 = stk.pop()) || !isEmpty(v1)) { stk.clear(); stk.push(!isEmpty(v2) ? v2 : v1); return; } else stk.push(null); break; case REGEX: stk.push(java.util.regex.Pattern.compile(java.lang.String.valueOf(stk.pop())) .matcher(java.lang.String.valueOf(stk.pop())).matches()); break; case INSTANCEOF: stk.push(((Class) stk.pop()).isInstance(stk.pop())); break; case CONVERTABLE_TO: stk.push(org.mvel2.DataConversion.canConvert(stk.peek2().getClass(), (Class) stk.pop2())); break; case CONTAINS: stk.push(containsCheck(stk.peek2(), stk.pop2())); break; case BW_AND: stk.push(asInt(stk.peek2()) & asInt(stk.pop2())); break; case BW_OR: stk.push(asInt(stk.peek2()) | asInt(stk.pop2())); break; case BW_XOR: stk.push(asInt(stk.peek2()) ^ asInt(stk.pop2())); break; case BW_SHIFT_LEFT: stk.push(asInt(stk.peek2()) << asInt(stk.pop2())); break; case BW_USHIFT_LEFT: int iv2 = asInt(stk.peek2()); if (iv2 < 0) iv2 *= -1; stk.push(iv2 << asInt(stk.pop2())); break; case BW_SHIFT_RIGHT: stk.push(asInt(stk.peek2()) >> asInt(stk.pop2())); break; case BW_USHIFT_RIGHT: stk.push(asInt(stk.peek2()) >>> asInt(stk.pop2())); break; case SOUNDEX: stk.push(Soundex.soundex(java.lang.String.valueOf(stk.pop())) .equals(Soundex.soundex(java.lang.String.valueOf(stk.pop())))); break; case SIMILARITY: stk.push(similarity(java.lang.String.valueOf(stk.pop()), java.lang.String.valueOf(stk.pop()))); break; } } catch (ClassCastException e) { throw new CompileException("syntax error or incompatable types", expr, cursor, e); } catch (ArithmeticException e) { throw new CompileException("arithmetic error: " + e.getMessage(), e); } catch (Exception e) { throw new CompileException("failed to subEval expression", e); } } private static int asInt(final Object o) { return (Integer) o; } public ParserContext getPCtx() { return pCtx; } public void setPCtx(ParserContext pCtx) { this.debugSymbols = (this.pCtx = pCtx).isDebugSymbols(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/ExecutableLiteral.java0000644000175000017500000000501011132471451025716 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.ast.Safe; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class ExecutableLiteral implements ExecutableStatement, Safe { private Object literal; private int integer32; private boolean intOptimized; public ExecutableLiteral(Object literal) { if ((this.literal = literal) instanceof Integer) this.integer32 = (Integer) literal; } public ExecutableLiteral(int literal) { this.literal = this.integer32 = literal; this.intOptimized = true; } public int getInteger32() { return integer32; } public void setInteger32(int integer32) { this.integer32 = integer32; } public Object getValue(Object staticContext, VariableResolverFactory factory) { return literal; } public void setKnownIngressType(Class type) { } public void setKnownEgressType(Class type) { } public Class getKnownIngressType() { return null; } public Class getKnownEgressType() { return this.literal == null ? Object.class : this.literal.getClass(); } public boolean isConvertableIngressEgress() { return false; } public void computeTypeConversionRule() { } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { return literal; } public Object getLiteral() { return literal; } public boolean intOptimized() { return intOptimized; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { // not implemented return null; } public boolean isLiteralOnly() { return true; } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/AccessorNode.java0000644000175000017500000000160511077457613024712 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import java.io.Serializable; public interface AccessorNode extends Accessor, Serializable { public AccessorNode getNextNode(); public AccessorNode setNextNode(AccessorNode accessorNode); } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/CompiledAccExpression.java0000644000175000017500000000625011167215375026563 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.ParserContext; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.optimizers.OptimizerFactory.getThreadAccessorOptimizer; import java.io.Serializable; public class CompiledAccExpression implements ExecutableStatement, Serializable { private char[] expression; private transient Accessor accessor; private ParserContext context; private Class ingressType; public CompiledAccExpression(char[] expression, Class ingressType, ParserContext context) { this.expression = expression; this.context = context; this.ingressType = ingressType != null ? ingressType : Object.class; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory vrf, Object value) { if (accessor == null) { if (ingressType == Object.class && value != null) ingressType = value.getClass(); accessor = getThreadAccessorOptimizer() .optimizeSetAccessor(context, expression, ctx, ctx, vrf, false, value, ingressType); } else { accessor.setValue(ctx, elCtx, vrf, value); } return value; } public Object getValue(Object staticContext, VariableResolverFactory factory) { if (accessor == null) { accessor = getThreadAccessorOptimizer() .optimizeAccessor(context, expression, staticContext, staticContext, factory, false, ingressType); } return accessor.getValue(staticContext, staticContext, factory); } public void setKnownIngressType(Class type) { this.ingressType = type; } public void setKnownEgressType(Class type) { } public Class getKnownIngressType() { return ingressType; } public Class getKnownEgressType() { return null; } public boolean isConvertableIngressEgress() { return false; } public void computeTypeConversionRule() { } public boolean intOptimized() { return false; } public boolean isLiteralOnly() { return false; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { if (accessor == null) { accessor = getThreadAccessorOptimizer().optimizeAccessor(context, expression, ctx, elCtx, variableFactory, false, ingressType); } return accessor.getValue(ctx, elCtx, variableFactory); } public Accessor getAccessor() { return accessor; } } mvel-2.0.18.orig/src/main/java/org/mvel2/compiler/PropertyVerifier.java0000644000175000017500000004231211332105653025646 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.compiler; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.PropertyAccessException; import org.mvel2.ast.Function; import org.mvel2.optimizers.AbstractOptimizer; import org.mvel2.optimizers.impl.refl.nodes.WithAccessor; import static org.mvel2.util.ParseTools.*; import static org.mvel2.util.PropertyTools.getFieldOrAccessor; import org.mvel2.util.StringAppender; import java.lang.reflect.*; import java.util.*; /** * This verifier is used by the compiler to enforce rules such as type strictness. It is, as side-effect, also * responsible for extracting type information. * * @author Mike Brock * @author Dhanji Prasanna */ public class PropertyVerifier extends AbstractOptimizer { private static final int DONE = -1; private static final int NORM = 0; private static final int METH = 1; private static final int COL = 2; private static final int WITH = 3; private List inputs = new LinkedList(); private boolean first = false; private boolean classLiteral = false; private boolean resolvedExternally; private boolean deepProperty = false; private Map paramTypes; private Class ctx = null; public PropertyVerifier(char[] property, ParserContext parserContext) { this.length = (this.expr = property).length; this.pCtx = parserContext; } public PropertyVerifier(char[] property, ParserContext parserContext, Class contextType) { this.length = (this.expr = property).length; this.pCtx = parserContext; this.ctx = contextType; } public PropertyVerifier(String property, ParserContext parserContext) { this.length = (this.expr = property.toCharArray()).length; this.pCtx = parserContext; } public PropertyVerifier(String property, ParserContext parserContext, Class root) { this.length = (this.expr = property.toCharArray()).length; this.pCtx = parserContext; this.ctx = root; } public List getInputs() { return inputs; } public void setInputs(List inputs) { this.inputs = inputs; } /** * Analyze the statement and return the known egress type. * * @return known engress type */ public Class analyze() { resolvedExternally = true; if (ctx == null) { ctx = Object.class; first = true; } while (cursor < length) { classLiteral = false; switch (nextSubToken()) { case NORM: ctx = getBeanProperty(ctx, capture()); break; case METH: ctx = getMethod(ctx, capture()); break; case COL: ctx = getCollectionProperty(ctx, capture()); break; case WITH: ctx = getWithProperty(ctx); break; case DONE: break; } if (!first) deepProperty = true; first = false; } return ctx; } private void recordTypeParmsForProperty(String property) { if (pCtx.isStrictTypeEnforcement()) { if ((paramTypes = pCtx.getTypeParameters(property)) == null) { pCtx.addTypeParameters(property, pCtx.getVarOrInputType(property)); } pCtx.setLastTypeParameters(pCtx.getTypeParametersAsArray(property)); } } /** * Process bean property * * @param ctx - the ingress type * @param property - the property component * @return known egress type. */ private Class getBeanProperty(Class ctx, String property) { if (first) { if (pCtx.hasVarOrInput(property)) { if (pCtx.isStrictTypeEnforcement()) { recordTypeParmsForProperty(property); } return pCtx.getVarOrInputType(property); } else if (pCtx.hasImport(property)) { resolvedExternally = false; return pCtx.getImport(property); } else if (!pCtx.isStrongTyping()) { return Object.class; } else if (pCtx.hasVarOrInput("this")) { if (pCtx.isStrictTypeEnforcement()) { recordTypeParmsForProperty("this"); } ctx = pCtx.getVarOrInputType("this"); } } start = cursor; boolean switchStateReg; Member member = ctx != null ? getFieldOrAccessor(ctx, property) : null; if (member instanceof Field) { if (pCtx.isStrictTypeEnforcement()) { Field f = ((Field) member); if (f.getGenericType() != null && f.getGenericType() instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) f.getGenericType(); pCtx.setLastTypeParameters(pt.getActualTypeArguments()); Type[] gpt = pt.getActualTypeArguments(); Type[] classArgs = ((Class) pt.getRawType()).getTypeParameters(); if (gpt.length > 0 && paramTypes == null) paramTypes = new HashMap(); for (int i = 0; i < gpt.length; i++) { paramTypes.put(classArgs[i].toString(), (Class) gpt[i]); } } return f.getType(); } else { return ((Field) member).getType(); } } else if (member != null) { Method method = (Method) member; if (pCtx.isStrictTypeEnforcement()) { //if not a field, then this is a property getter Type parametricReturnType = method.getGenericReturnType(); //push return type parameters onto parser context, only if this is a parametric type if (parametricReturnType instanceof ParameterizedType) { pCtx.setLastTypeParameters(((ParameterizedType) parametricReturnType).getActualTypeArguments()); } } Class rt = method.getReturnType(); return rt.isPrimitive() ? boxPrimitive(rt) : rt; } else if (pCtx != null && pCtx.hasImport(property)) { return pCtx.getImport(property); } else if (pCtx.getLastTypeParameters() != null && ((Collection.class.isAssignableFrom(ctx) && !(switchStateReg = false)) || (Map.class.isAssignableFrom(ctx) && (switchStateReg = true)))) { Class parm = (Class) pCtx.getLastTypeParameters()[switchStateReg ? 1 : 0]; pCtx.setLastTypeParameters(null); return parm; } else { Object tryStaticMethodRef = tryStaticAccess(); if (tryStaticMethodRef != null) { if (tryStaticMethodRef instanceof Class) { classLiteral = true; resolvedExternally = false; return (Class) tryStaticMethodRef; } else if (tryStaticMethodRef instanceof Field) { try { return ((Field) tryStaticMethodRef).get(null).getClass(); } catch (Exception e) { throw new CompileException("in verifier: ", e); } } else { try { return ((Method) tryStaticMethodRef).getReturnType(); } catch (Exception e) { throw new CompileException("in verifier: ", e); } } } else if (ctx != null && ctx.getClass() == Class.class) { for (Method m : ctx.getMethods()) { if (property.equals(m.getName())) { return m.getReturnType(); } } } if (pCtx.isStrictTypeEnforcement()) { addFatalError("unqualified type in strict mode for: " + property); } return Object.class; } } /** * Process collection property * * @param ctx - the ingress type * @param property - the property component * @return known egress type */ private Class getCollectionProperty(Class ctx, String property) { if (first) { if (pCtx.hasVarOrInput(property)) { ctx = getSubComponentType(pCtx.getVarOrInputType(property)); } else if (pCtx.hasImport(property)) { resolvedExternally = false; ctx = getSubComponentType(pCtx.getImport(property)); } else { ctx = Object.class; } } if (pCtx.isStrictTypeEnforcement()) { if (Map.class.isAssignableFrom(property.length() != 0 ? ctx = getBeanProperty(ctx, property) : ctx)) { ctx = (Class) pCtx.getLastTypeParameters()[1]; } else if (Collection.class.isAssignableFrom(ctx)) { ctx = (Class) pCtx.getLastTypeParameters()[0]; } else if (ctx.isArray()) { ctx = getBaseComponentType(ctx); } else if (pCtx.isStrongTyping()) { throw new CompileException("unknown collection type: " + ctx + "; property=" + property); } } else { ctx = Object.class; } ++cursor; skipWhitespace(); int start = cursor; if (cursor == length) throw new PropertyAccessException("unterminated '['"); if (scanTo(']')) { addFatalError("unterminated [ in token"); } ExpressionCompiler compiler = new ExpressionCompiler(new String(expr, start, cursor - start)); compiler.setVerifyOnly(true); compiler.compile(pCtx); ++cursor; return ctx; } /** * Process method * * @param ctx - the ingress type * @param name - the property component * @return known egress type. */ private Class getMethod(Class ctx, String name) { int st = cursor; /** * Check to see if this is the first element in the statement. */ if (first) { first = false; /** * It's the first element in the statement, therefore we check to see if there is a static import of a * native Java method or an MVEL function. */ if (pCtx.hasImport(name)) { Method m = pCtx.getStaticImport(name).getMethod(); /** * Replace the method parameters. */ ctx = m.getDeclaringClass(); name = m.getName(); } else if (pCtx.hasFunction(name)) { resolvedExternally = false; Function f = pCtx.getFunction(name); f.checkArgumentCount(parseParameterList((((cursor = balancedCapture(expr, cursor, '(')) - st) > 1 ? new String(expr, st + 1, cursor - st - 1) : "").toCharArray(), 0, -1).length); return f.getEgressType(); } } /** * Get the arguments for the method. */ String tk = ((cursor = balancedCapture(expr, cursor, '(')) - st) > 1 ? new String(expr, st + 1, cursor - st - 1) : ""; cursor++; /** * Parse out the arguments list. */ Class[] args; String[] subtokens = parseParameterList(tk.toCharArray(), 0, -1); if (subtokens.length == 0) { args = new Class[0]; subtokens = new String[0]; } else { // ParserContext subCtx = pCtx.createSubcontext(); args = new Class[subtokens.length]; /** * Subcompile all the arguments to determine their known types. */ // ExpressionCompiler compiler; CompiledExpression ce; for (int i = 0; i < subtokens.length; i++) { args[i] = MVEL.analyze(subtokens[i], pCtx); } } /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Method m; /** * If we have not cached the method then we need to go ahead and try to resolve it. */ if ((m = getBestCandidate(args, name, ctx, ctx.getMethods(), pCtx.isStrongTyping())) == null) { if ((m = getBestCandidate(args, name, ctx, ctx.getDeclaredMethods(), pCtx.isStrongTyping())) == null) { StringAppender errorBuild = new StringAppender(); for (int i = 0; i < args.length; i++) { errorBuild.append(args[i] != null ? args[i].getName() : null); if (i < args.length - 1) errorBuild.append(", "); } if ("size".equals(name) && args.length == 0 && ctx.isArray()) { return Integer.class; } if (pCtx.isStrictTypeEnforcement()) { addFatalError("unable to resolve method using strict-mode: " + ctx.getName() + "." + name + "(" + errorBuild.toString() + ")"); } return Object.class; } } /** * If we're in strict mode, we look for generic type information. */ if (pCtx.isStrictTypeEnforcement() && m.getGenericReturnType() != null) { Map typeArgs = new HashMap(); Type[] gpt = m.getGenericParameterTypes(); Class z; ParameterizedType pt; for (int i = 0; i < gpt.length; i++) { if (gpt[i] instanceof ParameterizedType) { pt = (ParameterizedType) gpt[i]; if ((z = pCtx.getImport(subtokens[i])) != null) { /** * We record the value of the type parameter to our typeArgs Map. */ if (pt.getRawType().equals(Class.class)) { /** * If this is an instance of Class, we deal with the special parameterization case. */ typeArgs.put(pt.getActualTypeArguments()[0].toString(), z); } else { typeArgs.put(gpt[i].toString(), z); } } } } /** * Get the return type argument */ Type parametricReturnType = m.getGenericReturnType(); String returnTypeArg = parametricReturnType.toString(); //push return type parameters onto parser context, only if this is a parametric type if (parametricReturnType instanceof ParameterizedType) { pCtx.setLastTypeParameters(((ParameterizedType) parametricReturnType).getActualTypeArguments()); } if (paramTypes != null && paramTypes.containsKey(returnTypeArg)) { /** * If the paramTypes Map contains the known type, return that type. */ return paramTypes.get(returnTypeArg); } else if (typeArgs.containsKey(returnTypeArg)) { /** * If the generic type was declared as part of the method, it will be in this * Map. */ return typeArgs.get(returnTypeArg); } } return m.getReturnType(); } private Class getWithProperty(Class ctx) { String root = new String(expr, 0, cursor - 1).trim(); int start = cursor + 1; cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx); new WithAccessor(root, subset(expr, start, cursor++ - start), ctx, pCtx.isStrictTypeEnforcement()); return ctx; } public boolean isResolvedExternally() { return resolvedExternally; } public boolean isClassLiteral() { return classLiteral; } public boolean isDeepProperty() { return deepProperty; } public Class getCtx() { return ctx; } public void setCtx(Class ctx) { this.ctx = ctx; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ImmutableElementException.java0000644000175000017500000000225611100376377025635 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; /** * Exception thrown by internal immutable structures if any modifications are attempted. */ public class ImmutableElementException extends RuntimeException { public ImmutableElementException() { super(); } public ImmutableElementException(String s) { super(s); } public ImmutableElementException(String s, Throwable throwable) { super(s, throwable); } public ImmutableElementException(Throwable throwable) { super(throwable); } } mvel-2.0.18.orig/src/main/java/org/mvel2/MacroProcessor.java0000644000175000017500000001110211165767772023472 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import org.mvel2.compiler.AbstractParser; import static org.mvel2.util.ParseTools.isWhitespace; import static org.mvel2.util.ParseTools.isIdentifierPart; import static org.mvel2.util.ParseTools.captureStringLiteral; import org.mvel2.util.StringAppender; import org.mvel2.util.ParseTools; import java.util.Map; /** * A simple, fast, macro processor. This processor works by simply replacing a matched identifier with a set of code. */ public class MacroProcessor extends AbstractParser implements PreProcessor { private Map macros; public MacroProcessor() { } public MacroProcessor(Map macros) { this.macros = macros; } public char[] parse(char[] input) { setExpression(input); StringAppender appender = new StringAppender(); int start; boolean macroArmed = true; String token; for (; cursor < length; cursor++) { start = cursor; while (cursor < length && isIdentifierPart(expr[cursor])) cursor++; if (cursor > start) { if (macros.containsKey(token = new String(expr, start, cursor - start)) && macroArmed) { appender.append(macros.get(token).doMacro()); } else { appender.append(token); } } if (cursor < length) { switch (expr[cursor]) { case '\\': cursor++; break; case '/': start = cursor; if (cursor + 1 != length) { switch (expr[cursor + 1]) { case '/': while (cursor != length && expr[cursor] != '\n') cursor++; break; case '*': int len = length-1; while (cursor != len && !(expr[cursor] == '*' && expr[cursor+1] == '/')) cursor++; cursor += 2; break; } } if (cursor < length) cursor++; appender.append(new String(expr, start, cursor - start)); if (cursor < length) cursor--; break; case '"': case '\'': appender.append(new String(expr, (start = cursor), (cursor = captureStringLiteral(expr[cursor], expr, cursor, length)) - start)); if (cursor >= length) break; else if (isIdentifierPart(expr[cursor])) cursor--; default: switch (expr[cursor]) { case '.': macroArmed = false; break; case ';': case '{': case '(': macroArmed = true; break; } appender.append(expr[cursor]); } } } return appender.toChars(); } public String parse(String input) { return new String(parse(input.toCharArray())); } public Map getMacros() { return macros; } public void setMacros(Map macros) { this.macros = macros; } public void captureToWhitespace() { while (cursor < length && !isWhitespace(expr[cursor])) cursor++; } } mvel-2.0.18.orig/src/main/java/org/mvel2/DataTypes.java0000644000175000017500000000346311224677601022425 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 MVFLEX/Valhalla Project and the Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; /** * Contains constants for standard internal types. */ public interface DataTypes { public static final int NULL = -1; public static final int OBJECT = 0; public static final int STRING = 1; public static final int SHORT = 100; public static final int INTEGER = 101; public static final int LONG = 102; public static final int DOUBLE = 103; public static final int FLOAT = 104; public static final int BOOLEAN = 7; public static final int CHAR = 8; public static final int BYTE = 9; public static final int W_SHORT = 105; public static final int W_INTEGER = 106; public static final int W_LONG = 107; public static final int W_FLOAT = 108; public static final int W_DOUBLE = 109; public static final int W_CHAR = 112; public static final int W_BYTE = 113; public static final int W_BOOLEAN = 15; public static final int BIG_DECIMAL = 110; public static final int BIG_INTEGER = 111; public static final int EMPTY = 200; public static final int UNIT = 300; } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/0000755000175000017500000000000011412747052020442 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/ast/PreFixIncNode.java0000644000175000017500000000312611153102156023734 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.DataTypes; import org.mvel2.math.MathProcessor; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class PreFixIncNode extends ASTNode { private String name; public PreFixIncNode(String name) { this.name = name; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver vResolver = factory.getVariableResolver(name); vResolver.setValue(ctx = MathProcessor.doOperations(vResolver.getValue(), Operator.ADD, DataTypes.INTEGER, 1)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IfNode.java0000644000175000017500000001006111114570772022451 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import static org.mvel2.MVEL.eval; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import static org.mvel2.util.CompilerTools.expectType; import static org.mvel2.util.ParseTools.subCompileExpression; import java.util.HashMap; /** * @author Christopher Brock */ public class IfNode extends ASTNode implements NestedStatement { protected char[] block; protected ExecutableStatement condition; protected ExecutableStatement nestedStatement; protected IfNode elseIf; protected ExecutableStatement elseBlock; public IfNode(char[] condition, char[] block, int fields, ParserContext pCtx) { if ((this.name = condition) == null || condition.length == 0) { throw new CompileException("statement expected"); } this.block = block; if ((fields & COMPILE_IMMEDIATE) != 0) { expectType(this.condition = (ExecutableStatement) subCompileExpression(condition, pCtx), Boolean.class, true); this.nestedStatement = (ExecutableStatement) subCompileExpression(block, pCtx); } } public IfNode(ExecutableStatement condition, ExecutableStatement nestedStatement, ExecutableStatement elseBlock) { expectType(this.condition = condition, Boolean.class, true); this.nestedStatement = nestedStatement; this.elseBlock = elseBlock; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if ((Boolean) condition.getValue(ctx, thisValue, factory)) { return nestedStatement.getValue(ctx, thisValue, new MapVariableResolverFactory(new HashMap(0), factory)); } else if (elseIf != null) { return elseIf.getReducedValueAccelerated(ctx, thisValue, new MapVariableResolverFactory(new HashMap(0), factory)); } else if (elseBlock != null) { return elseBlock.getValue(ctx, thisValue, new MapVariableResolverFactory(new HashMap(0), factory)); } else { return null; } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { if ((Boolean) eval(name, ctx, factory)) { return eval(block, ctx, new MapVariableResolverFactory(new HashMap(0), factory)); } else if (elseIf != null) { return elseIf.getReducedValue(ctx, thisValue, new MapVariableResolverFactory(new HashMap(0), factory)); } else if (elseBlock != null) { return elseBlock.getValue(ctx, thisValue, new MapVariableResolverFactory(new HashMap(0), factory)); } else { return null; } } public ExecutableStatement getNestedStatement() { return nestedStatement; } public IfNode setElseIf(IfNode elseIf) { return this.elseIf = elseIf; } public ExecutableStatement getElseBlock() { return elseBlock; } public IfNode setElseBlock(char[] block) { elseBlock = (ExecutableStatement) subCompileExpression(block); return this; } public String toString() { return new String(name); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/NewObjectNode.java0000644000175000017500000003010611363353131023767 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.*; import static org.mvel2.DataConversion.convert; import static org.mvel2.MVEL.analyze; import static org.mvel2.MVEL.eval; import org.mvel2.compiler.Accessor; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import static org.mvel2.optimizers.OptimizerFactory.getThreadAccessorOptimizer; import org.mvel2.util.ArrayTools; import org.mvel2.util.ParseTools; import static org.mvel2.util.CompilerTools.getInjectedImports; import static org.mvel2.util.ArrayTools.findFirst; import static org.mvel2.util.ParseTools.*; import java.io.Serializable; import static java.lang.Thread.currentThread; import static java.lang.reflect.Array.newInstance; import static org.mvel2.util.ParseTools.getBestConstructorCandidate; import java.lang.reflect.Constructor; import java.util.Arrays; /** * @author Christopher Brock */ @SuppressWarnings({"ManualArrayCopy"}) public class NewObjectNode extends ASTNode { private transient Accessor newObjectOptimizer; private TypeDescriptor typeDescr; public NewObjectNode(TypeDescriptor typeDescr, int fields, ParserContext pCtx) { this.typeDescr = typeDescr; this.fields = fields; this.name = typeDescr.getClassNameArray(); if ((fields & COMPILE_IMMEDIATE) != 0) { if (pCtx != null && pCtx.hasImport(typeDescr.getClassName())) { pCtx.setAllowBootstrapBypass(false); egressType = pCtx.getImport(typeDescr.getClassName()); } else { try { egressType = Class.forName(typeDescr.getClassName(), true, currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { if (pCtx != null && pCtx.isStrongTyping()) pCtx.addError(new ErrorDetail("could not resolve class: " + typeDescr.getClassName(), true)); // do nothing. } } if (egressType != null) { rewriteClassReferenceToFQCN(fields); if (typeDescr.isArray()) { try { egressType = findClass(null, repeatChar('[', typeDescr.getArrayLength()) + "L" + egressType.getName() + ";", pCtx); } catch (Exception e) { e.printStackTrace(); // for now, don't handle this. } } } if (pCtx != null && pCtx.isStrongTyping()) { if (egressType == null) { pCtx.addError(new ErrorDetail("could not resolve class: " + typeDescr.getClassName(), true)); return; } if (!typeDescr.isArray()) { final String[] constructorParms = parseMethodOrConstructor(captureContructorAndResidual(name)[0].toCharArray()); final Class[] parms = new Class[constructorParms.length]; for (int i = 0; i < parms.length; i++) { parms[i] = analyze(constructorParms[i], pCtx); } if (getBestConstructorCandidate(parms, egressType, true) == null) { if (pCtx.isStrongTyping()) pCtx.addError(new ErrorDetail("could not resolve constructor " + typeDescr.getClassName() + Arrays.toString(parms), pCtx.isStrongTyping())); } } } } } private void rewriteClassReferenceToFQCN(int fields) { String FQCN = egressType.getName(); if (typeDescr.getClassName().indexOf('.') == -1) { int idx = ArrayTools.findFirst('(', name); char[] fqcn = FQCN.toCharArray(); if (idx == -1) { this.name = new char[idx = fqcn.length]; for (int i = 0; i < idx; i++) this.name[i] = fqcn[i]; } else { char[] newName = new char[fqcn.length + (name.length - idx)]; for (int i = 0; i < fqcn.length; i++) newName[i] = fqcn[i]; int i0 = name.length - idx; int i1 = fqcn.length; for (int i = 0; i < i0; i++) newName[i + i1] = name[i + idx]; this.name = newName; } this.typeDescr.updateClassName(name, fields); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (newObjectOptimizer == null) { if (egressType == null) { /** * This means we couldn't resolve the type at the time this AST node was created, which means * we have to attempt runtime resolution. */ if (factory != null && factory.isResolveable(typeDescr.getClassName())) { try { egressType = (Class) factory.getVariableResolver(typeDescr.getClassName()).getValue(); rewriteClassReferenceToFQCN(COMPILE_IMMEDIATE); if (typeDescr.isArray()) { try { egressType = findClass(factory, repeatChar('[', typeDescr.getArrayLength()) + "L" + egressType.getName() + ";", null); } catch (Exception e) { // for now, don't handle this. } } } catch (ClassCastException e) { throw new CompileException("cannot construct object: " + typeDescr.getClassName() + " is not a class reference", e); } } } if (typeDescr.isArray()) { return (newObjectOptimizer = new NewObjectArray(getBaseComponentType(egressType.getComponentType()), typeDescr.getCompiledArraySize())) .getValue(ctx, thisValue, factory); } AccessorOptimizer optimizer = getThreadAccessorOptimizer(); ParserContext pCtx = new ParserContext(); pCtx.getParserConfiguration().setAllImports(getInjectedImports(factory)); newObjectOptimizer = optimizer.optimizeObjectCreation(pCtx, name, ctx, thisValue, factory); /** * Check to see if the optimizer actually produced the object during optimization. If so, * we return that value now. */ if (optimizer.getResultOptPass() != null) { egressType = optimizer.getEgressType(); return optimizer.getResultOptPass(); } } return newObjectOptimizer.getValue(ctx, thisValue, factory); } private static final Class[] EMPTYCLS = new Class[0]; public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { try { if (typeDescr.isArray()) { Class cls = findClass(factory, typeDescr.getClassName(), null); int[] s = new int[typeDescr.getArrayLength()]; ArraySize[] arraySize = typeDescr.getArraySize(); for (int i = 0; i < s.length; i++) { s[i] = convert(eval(arraySize[i].value, ctx, factory), Integer.class); } return newInstance(cls, s); } else { String[] cnsRes = captureContructorAndResidual(name); String[] constructorParms = parseMethodOrConstructor(cnsRes[0].toCharArray()); if (constructorParms != null) { Class cls = findClass(factory, new String(subset(name, 0, findFirst('(', name))), null); Object[] parms = new Object[constructorParms.length]; for (int i = 0; i < constructorParms.length; i++) { parms[i] = eval(constructorParms[i], ctx, factory); } Constructor cns = getBestConstructorCandidate(parms, cls, false); if (cns == null) throw new CompileException("unable to find constructor for: " + cls.getName()); for (int i = 0; i < parms.length; i++) { //noinspection unchecked parms[i] = convert(parms[i], cns.getParameterTypes()[i]); } if (cnsRes.length > 1) { return PropertyAccessor.get(cnsRes[1], cns.newInstance(parms), factory, thisValue); } else { return cns.newInstance(parms); } } else { Constructor cns = Class.forName(typeDescr.getClassName(), true, currentThread().getContextClassLoader()) .getConstructor(EMPTYCLS); if (cnsRes.length > 1) { return PropertyAccessor.get(cnsRes[1], cns.newInstance(), factory, thisValue); } else { return cns.newInstance(); } } } } catch (CompileException e) { throw e; } catch (ClassNotFoundException e) { throw new CompileException("unable to resolve class: " + e.getMessage(), e); } catch (NoSuchMethodException e) { throw new CompileException("cannot resolve constructor: " + e.getMessage()); } catch (Exception e) { throw new CompileException("could not instantiate class: " + e.getMessage()); } } public Accessor getNewObjectOptimizer() { return newObjectOptimizer; } public static class NewObjectArray implements Accessor, Serializable { private ExecutableStatement[] sizes; private Class arrayType; public NewObjectArray(Class arrayType, ExecutableStatement[] sizes) { this.arrayType = arrayType; this.sizes = sizes; } public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { int[] s = new int[sizes.length]; for (int i = 0; i < s.length; i++) { s[i] = convert(sizes[i].getValue(ctx, elCtx, variableFactory), Integer.class); } return newInstance(arrayType, s); } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { return null; } public Class getKnownEgressType() { try { return Class.forName("[L" + arrayType.getName() + ";"); } catch (ClassNotFoundException cne) { return null; } } } public TypeDescriptor getTypeDescr() { return typeDescr; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Instance.java0000644000175000017500000000257011104132451023042 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.compiler.Accessor; import org.mvel2.util.ParseTools; import org.mvel2.util.CompilerTools; import org.mvel2.MVEL; import org.mvel2.CompileException; public class Instance extends ASTNode { private ASTNode stmt; private ASTNode clsStmt; public Instance(ASTNode stmt, ASTNode clsStmt) { this.stmt = stmt; this.clsStmt = clsStmt; CompilerTools.expectType(clsStmt, Class.class, true); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Class) clsStmt.getReducedValueAccelerated(ctx, thisValue, factory)).isInstance(stmt.getReducedValueAccelerated(ctx, thisValue, factory)); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { try { Class i = (Class) clsStmt.getReducedValue(ctx, thisValue, factory); if (i == null) throw new ClassCastException(); return i.isInstance(stmt.getReducedValue(ctx, thisValue, factory)); } catch (ClassCastException e) { throw new CompileException("not a class reference: " + clsStmt.getName()); } } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/OperatorNode.java0000644000175000017500000000324611155433536023716 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import static org.mvel2.debug.DebugTools.getOperatorSymbol; import org.mvel2.integration.VariableResolverFactory; public class OperatorNode extends ASTNode { private Integer operator; public OperatorNode(Integer operator) { assert operator != null; this.literal = this.operator = operator; } public boolean isOperator() { return true; } public boolean isOperator(Integer operator) { return operator.equals(this.operator); } public Integer getOperator() { return operator; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { throw new CompileException("illegal use of operator: " + getOperatorSymbol(operator)); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { throw new CompileException("illegal use of operator: " + getOperatorSymbol(operator)); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IntAdd.java0000644000175000017500000000172111307306541022446 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.Operator; public class IntAdd extends BinaryOperation implements IntOptimized { public IntAdd(ASTNode left, ASTNode right) { super(Operator.ADD); this.left = left; this.right = right; } @Override public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Integer) left.getReducedValueAccelerated(ctx, thisValue, factory)) + ((Integer) right.getReducedValueAccelerated(ctx, thisValue, factory)); } @Override public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Integer) left.getReducedValue(ctx, thisValue, factory)) + ((Integer) right.getReducedValue(ctx, thisValue, factory)); } @Override public Class getEgressType() { return Integer.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Negation.java0000644000175000017500000000440311212317476023053 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.subCompileExpression; public class Negation extends ASTNode { private ExecutableStatement stmt; public Negation(char[] name, int fields, ParserContext pCtx) { this.name = name; if ((fields & COMPILE_IMMEDIATE) != 0) { if (((this.stmt = (ExecutableStatement) subCompileExpression(name, pCtx)).getKnownEgressType() != null) && (!ParseTools.boxPrimitive(stmt.getKnownEgressType()).isAssignableFrom(Boolean.class))) { throw new CompileException("negation operator cannot be applied to non-boolean type"); } } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return !((Boolean) stmt.getValue(ctx, thisValue, factory)); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { try { return !((Boolean) MVEL.eval(name, ctx, factory)); } catch (NullPointerException e) { throw new CompileException("negation operator applied to a null value", e); } catch (ClassCastException e) { throw new CompileException("negation operator applied to non-boolean expression", e); } } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IndexedPreFixIncNode.java0000644000175000017500000000316711153102156025242 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.DataTypes; import org.mvel2.math.MathProcessor; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class IndexedPreFixIncNode extends ASTNode { private int register; public IndexedPreFixIncNode(int register) { this.register = register; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver vResolver = factory.getIndexedVariableResolver(register); vResolver.setValue(ctx = MathProcessor.doOperations(vResolver.getValue(), Operator.ADD, DataTypes.INTEGER, 1)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/ForNode.java0000644000175000017500000000752611114570772022655 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import static org.mvel2.util.CompilerTools.expectType; import static org.mvel2.util.ParseTools.subCompileExpression; import static org.mvel2.util.ParseTools.subset; import java.util.HashMap; /** * @author Christopher Brock */ public class ForNode extends BlockNode { protected String item; protected ExecutableStatement initializer; protected ExecutableStatement condition; protected ExecutableStatement compiledBlock; protected ExecutableStatement after; public ForNode(char[] condition, char[] block, int fields, ParserContext pCtx) { handleCond(this.name = condition, fields); this.compiledBlock = (ExecutableStatement) subCompileExpression(this.block = block, pCtx); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory ctxFactory = new MapVariableResolverFactory(new HashMap(0), factory); for (initializer.getValue(ctx, thisValue, factory); (Boolean) condition.getValue(ctx, thisValue, factory); after.getValue(ctx, thisValue, factory)) { compiledBlock.getValue(ctx, thisValue, ctxFactory); } return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { for (initializer.getValue(ctx, thisValue, factory = new MapVariableResolverFactory(new HashMap(0), factory)); (Boolean) condition.getValue(ctx, thisValue, factory); after.getValue(ctx, thisValue, factory)) { compiledBlock.getValue(ctx, thisValue, factory); } return null; } public ForNode() { super(); //To change body of overridden methods use File | Settings | File Templates. } private void handleCond(char[] condition, int fields) { int start = 0; int cursor = nextCondPart(condition, start, false); try { this.initializer = (ExecutableStatement) subCompileExpression(subset(condition, start, cursor - start - 1)); expectType(this.condition = (ExecutableStatement) subCompileExpression(subset(condition, start = cursor, (cursor = nextCondPart(condition, start, false)) - start - 1)), Boolean.class, ((fields & COMPILE_IMMEDIATE) != 0)); this.after = (ExecutableStatement) subCompileExpression(subset(condition, start = cursor, (nextCondPart(condition, start, true)) - start)); } catch (NegativeArraySizeException e) { throw new CompileException("wrong syntax; did you mean to use 'foreach'?"); } } private static int nextCondPart(char[] condition, int cursor, boolean allowEnd) { for (; cursor < condition.length; cursor++) { if (condition[cursor] == ';') return ++cursor; } if (!allowEnd) throw new CompileException("expected ;"); return cursor; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Fold.java0000644000175000017500000001247711154053737022207 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory; import org.mvel2.integration.impl.ItemResolverFactory; import org.mvel2.util.CompilerTools; import org.mvel2.util.FastList; import org.mvel2.util.ParseTools; import static org.mvel2.util.CompilerTools.expectType; import static org.mvel2.util.ParseTools.*; import java.util.Collection; import java.util.List; import java.util.Iterator; public class Fold extends ASTNode { private ExecutableStatement subEx; private ExecutableStatement dataEx; private ExecutableStatement constraintEx; public Fold(char[] name, int fields, ParserContext pCtx) { this.name = name; int cursor = 0; for (; cursor < name.length; cursor++) { if (isWhitespace(name[cursor])) { while (cursor < name.length && isWhitespace(name[cursor])) cursor++; if (name[cursor] == 'i' && name[cursor + 1] == 'n' && isJunct(name[cursor + 2])) { break; } } } subEx = (ExecutableStatement) subCompileExpression(subset(name, 0, cursor - 1), pCtx); int start = cursor += 2; // skip 'in' for (; cursor < name.length; cursor++) { if (isWhitespace(name[cursor])) { while (cursor < name.length && isWhitespace(name[cursor])) cursor++; if (name[cursor] == 'i' && name[cursor + 1] == 'f' && isJunct(name[cursor + 2])) { int s = cursor + 2; constraintEx = (ExecutableStatement) subCompileExpression(subset(name, s, name.length - s), pCtx); break; } } } expectType(dataEx = (ExecutableStatement) subCompileExpression(subset(name, start, cursor - start), pCtx), Collection.class, ((fields & COMPILE_IMMEDIATE) != 0)); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { ItemResolverFactory.ItemResolver itemR = new ItemResolverFactory.ItemResolver("$"); ItemResolverFactory itemFactory = new ItemResolverFactory(itemR, new DefaultLocalVariableResolverFactory(factory)); List list; if (constraintEx != null) { Collection col = ((Collection) dataEx.getValue(ctx, thisValue, factory)); list = new FastList(col.size()); for (Object o : col) { itemR.value = o; if ((Boolean) constraintEx.getValue(ctx, thisValue, itemFactory)) { list.add(subEx.getValue(o, thisValue, itemFactory)); } } } else { Collection col = ((Collection) dataEx.getValue(ctx, thisValue, factory)); list = new FastList(col.size()); for (Object o : col) { list.add(subEx.getValue(itemR.value = o, thisValue, itemFactory)); } } return list; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { ItemResolverFactory.ItemResolver itemR = new ItemResolverFactory.ItemResolver("$"); ItemResolverFactory itemFactory = new ItemResolverFactory(itemR, new DefaultLocalVariableResolverFactory(factory)); List list; if (constraintEx != null) { Object x = dataEx.getValue(ctx, thisValue, factory); if (!(x instanceof Collection)) throw new CompileException("was expecting type: Collection; but found type: " + (x == null ? "null" : x.getClass().getName())); list = new FastList(((Collection) x).size()); for (Object o : (Collection) x) { itemR.value = o; if ((Boolean) constraintEx.getValue(ctx, thisValue, itemFactory)) { list.add(subEx.getValue(o, thisValue, itemFactory)); } } } else { Object x = dataEx.getValue(ctx, thisValue, factory); if (!(x instanceof Collection)) throw new CompileException("was expecting type: Collection; but found type: " + (x == null ? "null" : x.getClass().getName())); list = new FastList(((Collection) x).size()); for (Object o : (Collection) x) { list.add(subEx.getValue(itemR.value = o, thisValue, itemFactory)); } } return list; } public Class getEgressType() { return Collection.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IndexedAssignmentNode.java0000644000175000017500000001225211162250032025513 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.MVEL; import static org.mvel2.MVEL.compileSetExpression; import org.mvel2.ParserContext; import org.mvel2.compiler.CompiledAccExpression; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ArrayTools.findFirst; import static org.mvel2.util.ParseTools.*; /** * @author Christopher Brock */ public class IndexedAssignmentNode extends ASTNode implements Assignment { private String name; private int register; private transient CompiledAccExpression accExpr; private char[] indexTarget; private char[] index; private char[] stmt; private ExecutableStatement statement; private boolean col = false; public IndexedAssignmentNode(char[] expr, int fields, int operation, String name, int register, ParserContext pCtx) { super.name = expr; this.register = register; int assignStart; if (operation != -1) { checkNameSafety(this.name = name); this.egressType = (statement = (ExecutableStatement) subCompileExpression(stmt = createShortFormOperativeAssignment(name, expr, operation), pCtx)).getKnownEgressType(); } else if ((assignStart = find(expr, '=')) != -1) { this.name = createStringTrimmed(expr, 0, assignStart); this.egressType = (statement = (ExecutableStatement) subCompileExpression(stmt = subset(expr, assignStart + 1), pCtx)) .getKnownEgressType(); if (col = ((endOfName = (short) findFirst('[', indexTarget = this.name.toCharArray())) > 0)) { if (((this.fields |= COLLECTION) & COMPILE_IMMEDIATE) != 0) { accExpr = (CompiledAccExpression) compileSetExpression(indexTarget, pCtx); } this.name = new String(expr, 0, endOfName); index = subset(indexTarget, endOfName, indexTarget.length - endOfName); } checkNameSafety(this.name); } else { checkNameSafety(this.name = new String(expr)); } if ((fields & COMPILE_IMMEDIATE) != 0) { pCtx.addVariable(name, egressType); } } public IndexedAssignmentNode(char[] expr, int fields, int register, ParserContext pCtx) { this(expr, fields, -1, null, register, pCtx); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (accExpr == null) { accExpr = (CompiledAccExpression) compileSetExpression(indexTarget); } if (col) { accExpr.setValue(ctx, thisValue, factory, ctx = statement.getValue(ctx, thisValue, factory)); } else if (statement != null) { if (factory.isIndexedFactory()) { factory.createIndexedVariable(register, name, ctx = statement.getValue(ctx, thisValue, factory)); } else { factory.createVariable(name, ctx = statement.getValue(ctx, thisValue, factory)); } } else { if (factory.isIndexedFactory()) { factory.createIndexedVariable(register, name, null); } else { factory.createVariable(name, statement.getValue(ctx, thisValue, factory)); } return Void.class; } return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { checkNameSafety(name); if (col) { MVEL.setProperty(factory.getIndexedVariableResolver(register).getValue(), new String(index), ctx = MVEL.eval(stmt, ctx, factory)); } else { factory.createIndexedVariable(register, name, ctx = MVEL.eval(stmt, ctx, factory)); } return ctx; } public String getAssignmentVar() { return name; } public char[] getExpression() { return stmt; } public int getRegister() { return register; } public void setRegister(int register) { this.register = register; } public boolean isAssignment() { return true; } public boolean isNewDeclaration() { return false; } public void setValueStatement(ExecutableStatement stmt) { this.statement = stmt; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/LiteralNode.java0000644000175000017500000000343611151622475023516 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.compiler.BlankLiteral; /** * @author Christopher Brock */ public class LiteralNode extends ASTNode { public LiteralNode(Object literal, Class type) { this(literal); this.egressType = type; } public LiteralNode(Object literal) { if ((this.literal = literal) != null) { if ((this.egressType = literal.getClass()) == BlankLiteral.class) this.egressType = Object.class; } else { this.egressType = Object.class; } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return literal; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return literal; } public Object getLiteralValue() { return literal; } public void setLiteralValue(Object literal) { this.literal = literal; } public boolean isLiteral() { return true; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/BlockNode.java0000644000175000017500000000154411077457613023161 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; /** * @author Christopher Brock */ public class BlockNode extends ASTNode { protected char[] block; public BlockNode() { } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/NewPrototypeNode.java0000644000175000017500000000144011252763061024571 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.ParserContext; import org.mvel2.integration.VariableResolverFactory; public class NewPrototypeNode extends ASTNode { private String protoName; public NewPrototypeNode(TypeDescriptor t) { this.protoName = t.getClassName(); } @Override public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Proto) factory.getVariableResolver(protoName).getValue()) .newInstance(ctx, thisValue, factory); } @Override public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Proto) factory.getVariableResolver(protoName).getValue()) .newInstance(ctx, thisValue, factory); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IndexedPostFixDecNode.java0000644000175000017500000000336111154053737025432 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.DataTypes; import org.mvel2.util.ParseTools; import org.mvel2.math.MathProcessor; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class IndexedPostFixDecNode extends ASTNode { private int register; public IndexedPostFixDecNode(int register) { this.register = register; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver vResolver = factory.getIndexedVariableResolver(register); // ctx = vResolver.getValue(); vResolver.setValue(MathProcessor.doOperations(ParseTools.resolveType(ctx = vResolver.getValue()), ctx, Operator.SUB, DataTypes.INTEGER, 1)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/UntilNode.java0000644000175000017500000000460711114570772023217 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import static org.mvel2.util.CompilerTools.expectType; import static org.mvel2.util.ParseTools.subCompileExpression; import org.mvel2.ParserContext; import java.util.HashMap; /** * @author Christopher Brock */ public class UntilNode extends BlockNode { protected String item; protected ExecutableStatement condition; protected ExecutableStatement compiledBlock; public UntilNode(char[] condition, char[] block, int fields, ParserContext pCtx) { expectType(this.condition = (ExecutableStatement) subCompileExpression(this.name = condition, pCtx), Boolean.class, ((fields & COMPILE_IMMEDIATE) != 0)); this.compiledBlock = (ExecutableStatement) subCompileExpression(this.block = block, pCtx); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory ctxFactory = new MapVariableResolverFactory(new HashMap(0), factory); while (!(Boolean) condition.getValue(ctx, thisValue, factory)) { compiledBlock.getValue(ctx, thisValue, ctxFactory); } return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory ctxFactory = new MapVariableResolverFactory(new HashMap(0), factory); while (!(Boolean) condition.getValue(ctx, thisValue, factory)) { compiledBlock.getValue(ctx, thisValue, ctxFactory); } return null; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Union.java0000644000175000017500000000450311154053737022402 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.PropertyAccessor; import static org.mvel2.compiler.AbstractParser.getCurrentThreadParserContext; import org.mvel2.compiler.Accessor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import org.mvel2.optimizers.OptimizerFactory; public class Union extends ASTNode { private ASTNode main; private transient Accessor accessor; public Union(char[] expr, int start, int end, int fields, ASTNode main) { super(expr, start, end, fields); this.main = main; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (accessor != null) { return accessor.getValue(main.getReducedValueAccelerated(ctx, thisValue, factory), thisValue, factory); } else { AccessorOptimizer o = OptimizerFactory.getThreadAccessorOptimizer(); accessor = o.optimizeAccessor(getCurrentThreadParserContext(), name, main.getReducedValueAccelerated(ctx, thisValue, factory), thisValue, factory, false, main.getEgressType()); return o.getResultOptPass(); } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return PropertyAccessor.get( name, main.getReducedValue(ctx, thisValue, factory), factory, thisValue); } public Class getLeftEgressType() { return main.getEgressType(); } public String toString() { return (main != null ? main.toString() : "") + "-[union]->" + (accessor != null ? accessor.toString() : ""); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/ReturnNode.java0000644000175000017500000000340111114570772023372 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.MVEL.eval; import org.mvel2.compiler.Accessor; import org.mvel2.compiler.EndWithValue; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; import org.mvel2.ParserContext; /** * @author Christopher Brock */ public class ReturnNode extends ASTNode { public ReturnNode(char[] expr, int fields, ParserContext pCtx){ this.name = expr; if ((fields & COMPILE_IMMEDIATE) != 0) { setAccessor((Accessor) subCompileExpression(expr, pCtx)); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (accessor == null) { setAccessor((Accessor) subCompileExpression(this.name)); } throw new EndWithValue(accessor.getValue(ctx, thisValue, factory)); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { throw new EndWithValue(eval(this.name, ctx, factory)); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/DeclProtoVarNode.java0000644000175000017500000000501711253516374024466 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.checkNameSafety; /** * @author Christopher Brock */ public class DeclProtoVarNode extends ASTNode implements Assignment { private String name; public DeclProtoVarNode(String name, Proto type, int fields, ParserContext pCtx) { this.egressType = Proto.ProtoInstance.class; checkNameSafety(this.name = name); if ((fields & COMPILE_IMMEDIATE) != 0) { pCtx.addVariable(name, egressType, true); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (!factory.isResolveable(name)) factory.createVariable(name, null, egressType); else throw new CompileException("variable defined within scope: " + name); return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { if (!factory.isResolveable(name)) factory.createVariable(name, null, egressType); else throw new CompileException("variable defined within scope: " + name); return null; } public String getName() { return name; } public String getAssignmentVar() { return name; } public char[] getExpression() { return new char[0]; } public boolean isAssignment() { return true; } public boolean isNewDeclaration() { return true; } public void setValueStatement(ExecutableStatement stmt) { throw new RuntimeException("illegal operation"); } public String toString() { return "var:" + name; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Sign.java0000644000175000017500000000704611235611312022204 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.boxPrimitive; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.io.Serializable; public class Sign extends ASTNode { private Signer signer; private ExecutableStatement stmt; public Sign(char[] expr, int start, int end, int fields, ParserContext pCtx) { super(expr, start + 1, end, fields); if ((fields & COMPILE_IMMEDIATE) != 0) { stmt = (ExecutableStatement) ParseTools.subCompileExpression(name, pCtx); egressType = stmt.getKnownEgressType(); if (egressType != null && egressType != Object.class) { initSigner(egressType); } } } @Override public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return sign(stmt.getValue(ctx, thisValue, factory)); } @Override public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return sign(MVEL.eval(name, thisValue, factory)); } private Object sign(Object o) { if (o == null) return null; if (signer == null) { if (egressType == null || egressType == Object.class) egressType = o.getClass(); initSigner(egressType); } return signer.sign(o); } private void initSigner(Class type) { if (Integer.class.isAssignableFrom(type = boxPrimitive(type))) signer = new IntegerSigner(); else if (Double.class.isAssignableFrom(type)) signer = new DoubleSigner(); else if (Long.class.isAssignableFrom(type)) signer = new LongSigner(); else if (Float.class.isAssignableFrom(type)) signer = new FloatSigner(); else if (Short.class.isAssignableFrom(type)) signer = new ShortSigner(); else if (BigInteger.class.isAssignableFrom(type)) signer = new BigIntSigner(); else if (BigDecimal.class.isAssignableFrom(type)) signer = new BigDecSigner(); else { throw new CompileException("illegal use of '-': cannot be applied to: " + type.getName()); } } private interface Signer extends Serializable { public Object sign(Object o); } private class IntegerSigner implements Signer { public Object sign(Object o) { return -((Integer) o); } } private class ShortSigner implements Signer { public Object sign(Object o) { return -((Short) o); } } private class LongSigner implements Signer { public Object sign(Object o) { return -((Long) o); } } private class DoubleSigner implements Signer { public Object sign(Object o) { return -((Double) o); } } private class FloatSigner implements Signer { public Object sign(Object o) { return -((Float) o); } } private class BigIntSigner implements Signer { public Object sign(Object o) { return new BigInteger(String.valueOf(-(((BigInteger) o).longValue()))); } } private class BigDecSigner implements Signer { public Object sign(Object o) { return new BigDecimal(-((BigInteger) o).longValue()); } } @Override public boolean isIdentifier() { return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/ThisWithNode.java0000644000175000017500000000361211111332212023640 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import static org.mvel2.MVEL.executeSetExpression; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class ThisWithNode extends WithNode { public ThisWithNode(char[] expr, char[] block, int fields, ParserContext pCtx) { super(expr, block, fields, pCtx); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (thisValue == null) throw new CompileException("with-block against null pointer (this)"); for (ParmValuePair pvp : withExpressions) { if (pvp.getSetExpression() != null) { executeSetExpression(pvp.getSetExpression(), thisValue, factory, pvp.getStatement().getValue(ctx, thisValue, factory)); } else { pvp.getStatement().getValue(thisValue, thisValue, factory); } } return thisValue; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IntOptimized.java0000644000175000017500000000007211244064005023714 0ustar drazzibdrazzibpackage org.mvel2.ast; public interface IntOptimized { } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/BinaryOperation.java0000644000175000017500000001366511244064005024416 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import org.mvel2.Operator; import static org.mvel2.Operator.PTABLE; import org.mvel2.ParserContext; import static org.mvel2.debug.DebugTools.getOperatorSymbol; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.math.MathProcessor.doOperations; import static org.mvel2.util.CompilerTools.getReturnTypeFromOp; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.boxPrimitive; public class BinaryOperation extends BooleanNode { private final int operation; private int lType = -1; private int rType = -1; public BinaryOperation(int operation) { this.operation = operation; } public BinaryOperation(int operation, ASTNode left, ASTNode right) { this.operation = operation; if ((this.left = left) == null) { throw new CompileException("not a statement"); } if ((this.right = right) == null) { throw new CompileException("not a statement"); } egressType = getReturnTypeFromOp(operation, left.egressType, right.egressType); } public BinaryOperation(int operation, ASTNode left, ASTNode right, ParserContext ctx) { this.operation = operation; if ((this.left = left) == null) { throw new CompileException("not a statement"); } if ((this.right = right) == null) { throw new CompileException("not a statement"); } if (ctx.isStrongTyping()) { switch (operation) { case Operator.ADD: /** * In the special case of Strings, the return type may leftward propogate. */ if (left.getEgressType() == String.class || right.getEgressType() == String.class) { egressType = String.class; lType = ParseTools.__resolveType(left.egressType); rType = ParseTools.__resolveType(right.egressType); return; } default: if (!left.getEgressType().isAssignableFrom(right.getEgressType())) { if (right.isLiteral() && canConvert(right.getEgressType(), left.getEgressType())) { this.right = new LiteralNode(convert(right.getReducedValueAccelerated(null, null, null), left.getEgressType())); } else if (!(Number.class.isAssignableFrom(right.getEgressType()) && Number.class.isAssignableFrom(left.getEgressType())) && ((!right.getEgressType().isPrimitive() && !left.getEgressType().isPrimitive()) || (!canConvert(boxPrimitive(left.getEgressType()), boxPrimitive(right.getEgressType()))))) { throw new CompileException("incompatible types in statement: " + right.getEgressType() + " (compared from: " + left.getEgressType() + ")"); } } } } if (this.left.isLiteral() && this.right.isLiteral()) { if (this.left.egressType == this.right.egressType) { lType = rType = ParseTools.__resolveType(left.egressType); } else { lType = ParseTools.__resolveType(this.left.egressType); rType = ParseTools.__resolveType(this.right.egressType); } } egressType = getReturnTypeFromOp(operation, this.left.egressType, this.right.egressType); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return doOperations(lType, left.getReducedValueAccelerated(ctx, thisValue, factory), operation, rType, right.getReducedValueAccelerated(ctx, thisValue, factory)); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { throw new RuntimeException("unsupported AST operation"); } public int getOperation() { return operation; } public BinaryOperation getRightBinary() { return right != null && right instanceof BinaryOperation ? (BinaryOperation) right : null; } public void setRightMost(ASTNode right) { BinaryOperation n = this; while (n.right != null && n.right instanceof BinaryOperation) { n = (BinaryOperation) n.right; } n.right = right; if (n == this) { if ((rType = ParseTools.__resolveType(n.right.getEgressType())) == 0) rType = -1; } } public ASTNode getRightMost() { BinaryOperation n = this; while (n.right != null && n.right instanceof BinaryOperation) { n = (BinaryOperation) n.right; } return n.right; } public int getPrecedence() { return PTABLE[operation]; } public boolean isGreaterPrecedence(BinaryOperation o) { return o.getPrecedence() > PTABLE[operation]; } @Override public boolean isLiteral() { return false; } public String toString() { return "(" + left + " " + getOperatorSymbol(operation) + " " + right + ")"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/ArraySize.java0000644000175000017500000000155311077457613023232 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import java.io.Serializable; public class ArraySize implements Serializable { public ArraySize(char[] value) { this.value = value; } public char[] value; } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Substatement.java0000644000175000017500000000353011224677601023767 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; public class Substatement extends ASTNode { private ExecutableStatement statement; public Substatement(char[] expr, int fields, ParserContext pCtx) { this.name = expr; if (((this.fields = fields) & COMPILE_IMMEDIATE) != 0) { this.egressType = (this.statement = (ExecutableStatement) subCompileExpression(this.name, pCtx)) .getKnownEgressType(); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return statement.getValue(ctx, thisValue, factory); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return MVEL.eval(this.name, ctx, factory); } public ExecutableStatement getStatement() { return statement; } public String toString() { return statement == null ? "(" + new String(name) + ")" : statement.toString(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Strsim.java0000644000175000017500000000271411104141054022556 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.CompilerTools; import static org.mvel2.util.ParseTools.similarity; public class Strsim extends ASTNode { private ASTNode stmt; private ASTNode soundslike; public Strsim(ASTNode stmt, ASTNode clsStmt) { this.stmt = stmt; this.soundslike = clsStmt; CompilerTools.expectType(clsStmt, String.class, true); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return similarity(String.valueOf(soundslike.getReducedValueAccelerated(ctx, thisValue, factory)), ((String) stmt.getReducedValueAccelerated(ctx, thisValue, factory))); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { try { String i = String.valueOf(soundslike.getReducedValue(ctx, thisValue, factory)); if (i == null) throw new ClassCastException(); String x = (String) stmt.getReducedValue(ctx, thisValue, factory); if (x == null) throw new CompileException("not a string: " + stmt.getName()); return similarity(i,x); } catch (ClassCastException e) { throw new CompileException("not a string: " + soundslike.getName()); } } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/EndOfStatement.java0000644000175000017500000000273511077457613024204 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class EndOfStatement extends ASTNode { public EndOfStatement() { this.literal = getOperator(); } public boolean isOperator() { return true; } public boolean isOperator(Integer operator) { return operator == Operator.END_OF_STMT; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return null; } public Integer getOperator() { return Operator.END_OF_STMT; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/RegExMatchNode.java0000644000175000017500000000326511077457613024120 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.MVEL.eval; import org.mvel2.integration.VariableResolverFactory; import static java.lang.String.valueOf; import static java.util.regex.Pattern.compile; public class RegExMatchNode extends ASTNode { private ASTNode node; private ASTNode patternNode; public RegExMatchNode(ASTNode matchNode, ASTNode patternNode) { this.node = matchNode; this.patternNode = patternNode; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return compile(valueOf(patternNode.getReducedValueAccelerated(ctx, thisValue, factory))).matcher(valueOf(node.getReducedValueAccelerated(ctx, thisValue, factory))).matches(); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return compile(valueOf(eval(name, ctx, factory))).matcher(valueOf(eval(name, ctx, factory))).matches(); } public Class getEgressType() { return Boolean.class; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IsDef.java0000644000175000017500000000275111210544111022267 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.PropertyTools.getFieldOrAccessor; public class IsDef extends ASTNode { public IsDef(char[] expr) { this.nameCache = new String(this.name = expr); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return factory.isResolveable(nameCache) || (thisValue != null && getFieldOrAccessor(thisValue.getClass(), nameCache) != null); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return factory.isResolveable(nameCache) || (thisValue != null && getFieldOrAccessor(thisValue.getClass(), nameCache) != null); } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IndexedPreFixDecNode.java0000644000175000017500000000316511153102156025222 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.DataTypes; import org.mvel2.math.MathProcessor; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class IndexedPreFixDecNode extends ASTNode { private int register; public IndexedPreFixDecNode(int register) { this.register = register; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver vResolver = factory.getIndexedVariableResolver(register); vResolver.setValue(ctx = MathProcessor.doOperations(vResolver.getValue(), Operator.SUB, DataTypes.INTEGER, 1)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/PostFixDecNode.java0000644000175000017500000000312611153102156024115 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.DataTypes; import org.mvel2.math.MathProcessor; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class PostFixDecNode extends ASTNode { private String name; public PostFixDecNode(String name) { this.name = name; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver vResolver = factory.getVariableResolver(name); vResolver.setValue(MathProcessor.doOperations(ctx = vResolver.getValue(), Operator.SUB, DataTypes.INTEGER, 1)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Invert.java0000644000175000017500000000366711115170774022571 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.CompilerTools; import static org.mvel2.util.CompilerTools.expectType; import static org.mvel2.util.ParseTools.subCompileExpression; public class Invert extends ASTNode { private ExecutableStatement stmt; public Invert(char[] name, int fields, ParserContext pCtx) { this.name = name; if ((fields & COMPILE_IMMEDIATE) != 0) { expectType(this.stmt = (ExecutableStatement) subCompileExpression(name, pCtx), Integer.class, true); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return ~((Integer) stmt.getValue(ctx, thisValue, factory)); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { Object o = MVEL.eval(name, ctx, factory); if (o instanceof Integer) { return ~((Integer) o); } else { throw new CompileException("was expecting type: Integer; but found type: " + (o == null ? "null" : o.getClass().getName())); } } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/AssertNode.java0000644000175000017500000000464611163351223023360 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; /** * @author Christopher Brock */ public class AssertNode extends ASTNode { public ExecutableStatement assertion; public ExecutableStatement fail; public AssertNode(char[] expr, int fields, ParserContext pCtx) { this.name = expr; if ((fields & COMPILE_IMMEDIATE) != 0) { assertion = (ExecutableStatement) subCompileExpression(expr, pCtx); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { try { if (!((Boolean) assertion.getValue(ctx, thisValue, factory))) { throw new AssertionError("assertion failed in expression: " + new String(this.name)); } else { return true; } } catch (ClassCastException e) { throw new CompileException("assertion does not contain a boolean statement"); } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { try { if (!((Boolean) MVEL.eval(this.name, ctx, factory))) { throw new AssertionError("assertion failed in expression: " + new String(this.name)); } else { return true; } } catch (ClassCastException e) { throw new CompileException("assertion does not contain a boolean statement"); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/DoUntilNode.java0000644000175000017500000000456311114570772023503 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import static org.mvel2.util.CompilerTools.expectType; import static org.mvel2.util.ParseTools.subCompileExpression; import org.mvel2.ParserContext; import java.util.HashMap; /** * @author Christopher Brock */ public class DoUntilNode extends BlockNode { protected String item; protected ExecutableStatement condition; protected ExecutableStatement compiledBlock; public DoUntilNode(char[] condition, char[] block, ParserContext pCtx) { expectType(this.condition = (ExecutableStatement) subCompileExpression(this.name = condition, pCtx), Boolean.class, ((fields & COMPILE_IMMEDIATE) != 0)); this.compiledBlock = (ExecutableStatement) subCompileExpression(this.block = block, pCtx); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory lc = new MapVariableResolverFactory(new HashMap(0), factory); do { compiledBlock.getValue(ctx, thisValue, lc); } while (!(Boolean) condition.getValue(ctx, thisValue, lc)); return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory lc = new MapVariableResolverFactory(new HashMap(0), factory); do { compiledBlock.getValue(ctx, thisValue, lc); } while (!(Boolean) condition.getValue(ctx, thisValue, lc)); return null; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/AssignmentNode.java0000644000175000017500000001016211165573105024224 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.MVEL; import static org.mvel2.MVEL.compileSetExpression; import org.mvel2.ParserContext; import org.mvel2.PropertyAccessor; import org.mvel2.compiler.CompiledAccExpression; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ArrayTools.findFirst; import static org.mvel2.util.ParseTools.*; /** * @author Christopher Brock */ public class AssignmentNode extends ASTNode implements Assignment { private String varName; private transient CompiledAccExpression accExpr; private char[] indexTarget; private String index; private char[] stmt; private ExecutableStatement statement; private boolean col = false; public AssignmentNode(char[] expr, int fields, ParserContext pCtx) { this.name = expr; int assignStart; if ((assignStart = find(expr, '=')) != -1) { this.varName = createStringTrimmed(expr, 0, assignStart); stmt = subset(expr, assignStart + 1); if ((fields & COMPILE_IMMEDIATE) != 0) { this.egressType = (statement = (ExecutableStatement) subCompileExpression(stmt, pCtx)).getKnownEgressType(); } if (col = ((endOfName = findFirst('[', indexTarget = this.varName.toCharArray())) > 0)) { if (((this.fields |= COLLECTION) & COMPILE_IMMEDIATE) != 0) { accExpr = (CompiledAccExpression) compileSetExpression(indexTarget, pCtx); } this.varName = new String(expr, 0, endOfName); index = new String(indexTarget, endOfName, indexTarget.length - endOfName); } checkNameSafety(this.varName); } else { checkNameSafety(this.varName = new String(expr)); } if ((fields & COMPILE_IMMEDIATE) != 0) { pCtx.addVariable(this.varName, egressType); } this.name = this.varName.toCharArray(); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (accExpr == null) { accExpr = (CompiledAccExpression) compileSetExpression(indexTarget); } if (col) { return accExpr.setValue(ctx, thisValue, factory, statement.getValue(ctx, thisValue, factory)); } else if (statement != null) { return factory.createVariable(varName, statement.getValue(ctx, thisValue, factory)).getValue(); } else { factory.createVariable(varName, null); return null; } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { checkNameSafety(varName); if (col) { PropertyAccessor.set(factory.getVariableResolver(varName).getValue(), factory, index, ctx = MVEL.eval(stmt, ctx, factory)); } else { return factory.createVariable(varName, MVEL.eval(stmt, ctx, factory)).getValue(); } return ctx; } public String getAssignmentVar() { return varName; } public char[] getExpression() { return stmt; } public boolean isNewDeclaration() { return false; } public void setValueStatement(ExecutableStatement stmt) { this.statement = stmt; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Contains.java0000644000175000017500000000302111077457613023067 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.containsCheck; public class Contains extends ASTNode { private ASTNode stmt; private ASTNode stmt2; public Contains(ASTNode stmt, ASTNode stmt2) { this.stmt = stmt; this.stmt2 = stmt2; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return containsCheck(stmt.getReducedValueAccelerated(ctx, thisValue, factory), stmt2.getReducedValueAccelerated(ctx, thisValue, factory)); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { throw new RuntimeException("operation not supported"); } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Convertable.java0000644000175000017500000000270111104135617023545 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.DataConversion; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.CompilerTools; public class Convertable extends ASTNode { private ASTNode stmt; private ASTNode clsStmt; public Convertable(ASTNode stmt, ASTNode clsStmt) { this.stmt = stmt; this.clsStmt = clsStmt; CompilerTools.expectType(clsStmt, Class.class, true); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { Object o = stmt.getReducedValueAccelerated(ctx, thisValue, factory); return o != null && DataConversion.canConvert( (Class) clsStmt.getReducedValueAccelerated(ctx, thisValue, factory), o.getClass()); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { try { Object o = stmt.getReducedValue(ctx, thisValue, factory); if (o == null) return false; Class i = (Class) clsStmt.getReducedValue(ctx, thisValue, factory); if (i == null) throw new ClassCastException(); return DataConversion.canConvert(i,o.getClass()); } catch (ClassCastException e) { throw new CompileException("not a class reference: " + clsStmt.getName()); } } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IntMult.java0000644000175000017500000000172411307306541022702 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.integration.VariableResolverFactory; public class IntMult extends BinaryOperation implements IntOptimized { public IntMult(ASTNode left, ASTNode right) { super(Operator.MULT); this.left = left; this.right = right; } @Override public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Integer) left.getReducedValueAccelerated(ctx, thisValue, factory)) * ((Integer) right.getReducedValueAccelerated(ctx, thisValue, factory)); } @Override public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Integer) left.getReducedValue(ctx, thisValue, factory)) * ((Integer) right.getReducedValue(ctx, thisValue, factory)); } @Override public Class getEgressType() { return Integer.class; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/TypedVarNode.java0000644000175000017500000000600511115170774023653 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.MVEL.eval; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.compiler.AbstractParser; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.*; /** * @author Christopher Brock */ public class TypedVarNode extends ASTNode implements Assignment { private String name; private char[] stmt; private ExecutableStatement statement; public TypedVarNode(String name, Class type) { this.name = name; this.egressType = type; } public TypedVarNode(char[] expr, int fields, Class type, ParserContext pCtx) { this.egressType = type; this.fields = fields; int assignStart; if ((assignStart = find(super.name = expr, '=')) != -1) { checkNameSafety(name = createStringTrimmed(expr, 0, assignStart)); if (((fields |= ASSIGN) & COMPILE_IMMEDIATE) != 0) { statement = (ExecutableStatement) subCompileExpression(stmt = subset(expr, assignStart + 1), pCtx); } else { stmt = subset(expr, assignStart + 1); } } else { checkNameSafety(name = new String(expr)); } if ((fields & COMPILE_IMMEDIATE) != 0) { pCtx.addVariable(name, egressType, true); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (statement == null) statement = (ExecutableStatement) subCompileExpression(stmt); factory.createVariable(name, ctx = statement.getValue(ctx, thisValue, factory), egressType); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { factory.createVariable(name, ctx = eval(stmt, thisValue, factory), egressType); return ctx; } public String getName() { return name; } public String getAssignmentVar() { return name; } public char[] getExpression() { return stmt; } public boolean isNewDeclaration() { return true; } public void setValueStatement(ExecutableStatement stmt) { this.statement = stmt; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/TypeCast.java0000644000175000017500000000542711274117371023052 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import static org.mvel2.MVEL.eval; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; import org.mvel2.util.CompilerTools; import org.mvel2.ParserContext; import org.mvel2.DataConversion; import org.mvel2.CompileException; public class TypeCast extends ASTNode { private ExecutableStatement statement; private boolean widen; public TypeCast(char[] expr, Class cast, int fields, ParserContext pCtx) { this.egressType = cast; this.name = expr; if ((fields & COMPILE_IMMEDIATE) != 0) { if ((statement = (ExecutableStatement) subCompileExpression(name, pCtx)).getKnownEgressType() != Object.class && !canConvert(cast, statement.getKnownEgressType())) { if (statement.getKnownEgressType().isAssignableFrom(cast)) { widen = true; } else { throw new CompileException("unable to cast type: " + statement.getKnownEgressType() + "; to: " + cast); } } } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { //noinspection unchecked return widen ? typeCheck(statement.getValue(ctx, thisValue, factory), egressType) : convert(statement.getValue(ctx, thisValue, factory), egressType); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { //noinspection unchecked return widen ? typeCheck(eval(name, ctx, factory), egressType) : convert(eval(name, ctx, factory), egressType); } private static Object typeCheck(Object inst, Class type) { if (inst == null) return null; if (type.isInstance(inst)) { return inst; } else { throw new ClassCastException(inst.getClass().getName() + " cannot be cast to: " + type.getClass().getName()); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/OperativeAssign.java0000644000175000017500000000457511153102156024413 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.MVEL.eval; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; import org.mvel2.util.ParseTools; import org.mvel2.math.MathProcessor; import org.mvel2.ParserContext; public class OperativeAssign extends ASTNode { private String varName; private ExecutableStatement statement; private final int operation; private int knownInType = -1; public OperativeAssign(String variableName, char[] expr, int operation, int fields, ParserContext pCtx) { this.varName = variableName; this.operation = operation; this.name = expr; if ((fields & COMPILE_IMMEDIATE) != 0) { egressType = (statement = (ExecutableStatement) subCompileExpression(expr, pCtx)).getKnownEgressType(); if (pCtx.isStrongTyping()) { knownInType = ParseTools.__resolveType(egressType); } } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver resolver = factory.getVariableResolver(varName); resolver.setValue(ctx = MathProcessor.doOperations(resolver.getValue(), operation, knownInType, statement.getValue(ctx, thisValue, factory))); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver resolver = factory.getVariableResolver(varName); resolver.setValue(ctx = MathProcessor.doOperations(resolver.getValue(), operation, eval(name, ctx, factory))); return ctx; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/BooleanNode.java0000644000175000017500000000100011144173417023461 0ustar drazzibdrazzibpackage org.mvel2.ast; public abstract class BooleanNode extends ASTNode { protected ASTNode left; protected ASTNode right; public ASTNode getLeft() { return this.left; } public ASTNode getRight() { return this.right; } public void setLeft(ASTNode node) { this.left = node; } public void setRight(ASTNode node) { this.right = node; } public abstract void setRightMost(ASTNode right); public abstract ASTNode getRightMost(); } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/NestedStatement.java0000644000175000017500000000160211077457613024423 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.compiler.ExecutableStatement; /** * @author Christopher Brock */ public interface NestedStatement { public ExecutableStatement getNestedStatement(); } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IntSub.java0000644000175000017500000000172311307306541022511 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.Operator; public class IntSub extends BinaryOperation implements IntOptimized { public IntSub(ASTNode left, ASTNode right) { super(Operator.SUB); this.left = left; this.right = right; } @Override public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Integer) left.getReducedValueAccelerated(ctx, thisValue, factory)) - ((Integer) right.getReducedValueAccelerated(ctx, thisValue, factory)); } @Override public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Integer) left.getReducedValue(ctx, thisValue, factory)) - ((Integer) right.getReducedValue(ctx, thisValue, factory)); } @Override public Class getEgressType() { return Integer.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Safe.java0000644000175000017500000000143111077457613022172 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; /** * Marker interface to tell MVEL it can safely hard-reference. */ public interface Safe { } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/DoNode.java0000644000175000017500000000464711114570772022472 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import static org.mvel2.util.CompilerTools.expectType; import static org.mvel2.util.ParseTools.subCompileExpression; import org.mvel2.ParserContext; import java.util.HashMap; /** * @author Christopher Brock */ public class DoNode extends BlockNode { protected String item; protected ExecutableStatement condition; protected ExecutableStatement compiledBlock; public DoNode(char[] condition, char[] block, int fields, ParserContext pCtx) { this.condition = (ExecutableStatement) subCompileExpression(this.name = condition, pCtx); expectType(this.condition, Boolean.class, ((fields & COMPILE_IMMEDIATE) != 0)); this.compiledBlock = (ExecutableStatement) subCompileExpression(this.block = block, pCtx); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory ctxFactory = new MapVariableResolverFactory(new HashMap(0), factory); do { compiledBlock.getValue(ctx, thisValue, ctxFactory); } while ((Boolean) condition.getValue(ctx, thisValue, factory)); return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory ctxFactory = new MapVariableResolverFactory(new HashMap(0), factory); do { compiledBlock.getValue(ctx, thisValue, ctxFactory); } while ((Boolean) condition.getValue(ctx, thisValue, factory)); return null; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/DeepAssignmentNode.java0000644000175000017500000000742411166754071025035 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.MVEL.compileSetExpression; import static org.mvel2.MVEL.eval; import org.mvel2.ParserContext; import static org.mvel2.PropertyAccessor.set; import static org.mvel2.compiler.AbstractParser.getCurrentThreadParserContext; import org.mvel2.compiler.CompiledAccExpression; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.*; /** * @author Christopher Brock */ public class DeepAssignmentNode extends ASTNode implements Assignment { private String property; private char[] stmt; private CompiledAccExpression acc; private ExecutableStatement statement; public DeepAssignmentNode(char[] expr, int fields, int operation, String name, ParserContext pCtx) { this.fields |= DEEP_PROPERTY | fields; this.name = expr; int mark; if (operation != -1) { this.egressType = ((statement = (ExecutableStatement) subCompileExpression(stmt = createShortFormOperativeAssignment(this.property = name, expr, operation), pCtx))).getKnownEgressType(); } else if ((mark = find(expr, '=')) != -1) { property = createStringTrimmed(expr, 0, mark); stmt = subset(expr, mark + 1); if ((fields & COMPILE_IMMEDIATE) != 0) { statement = (ExecutableStatement) subCompileExpression(stmt, pCtx); } } else { property = new String(expr); } if ((fields & COMPILE_IMMEDIATE) != 0) { acc = (CompiledAccExpression) compileSetExpression(property.toCharArray(), pCtx); } } public DeepAssignmentNode(char[] expr, int fields, ParserContext pCtx) { this(expr, fields, -1, null, pCtx); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (statement == null) { statement = (ExecutableStatement) subCompileExpression(stmt); acc = (CompiledAccExpression) compileSetExpression(property.toCharArray(), statement.getKnownEgressType(), getCurrentThreadParserContext()); } acc.setValue(ctx, thisValue, factory, ctx = statement.getValue(ctx, thisValue, factory)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { set(ctx, factory, property, ctx = eval(stmt, ctx, factory)); return ctx; } @Override public String getAbsoluteName() { return property.substring(0, property.indexOf('.')); } public String getAssignmentVar() { return property; } public char[] getExpression() { return stmt; } public boolean isNewDeclaration() { return false; } public boolean isAssignment() { return true; } public void setValueStatement(ExecutableStatement stmt) { this.statement = stmt; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/DeclTypedVarNode.java0000644000175000017500000000477211155416072024452 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.checkNameSafety; /** * @author Christopher Brock */ public class DeclTypedVarNode extends ASTNode implements Assignment { private String name; public DeclTypedVarNode(String name, Class type, int fields, ParserContext pCtx) { this.egressType = type; checkNameSafety(this.name = name); if ((fields & COMPILE_IMMEDIATE) != 0) { pCtx.addVariable(name, egressType, true); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (!factory.isResolveable(name)) factory.createVariable(name, null, egressType); else throw new CompileException("variable defined within scope: " + name); return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { if (!factory.isResolveable(name)) factory.createVariable(name, null, egressType); else throw new CompileException("variable defined within scope: " + name); return null; } public String getName() { return name; } public String getAssignmentVar() { return name; } public char[] getExpression() { return new char[0]; } public boolean isAssignment() { return true; } public boolean isNewDeclaration() { return true; } public void setValueStatement(ExecutableStatement stmt) { throw new RuntimeException("illegal operation"); } public String toString() { return "var:" + name; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Or.java0000644000175000017500000000411211144173417021663 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.CompilerTools.expectType; import org.mvel2.ast.BooleanNode; public class Or extends BooleanNode { public Or(ASTNode left, ASTNode right, boolean strongTyping) { expectType(this.left = left, Boolean.class, strongTyping); expectType(this.right = right, Boolean.class, strongTyping); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return (((Boolean) left.getReducedValueAccelerated(ctx, thisValue, factory)) || ((Boolean) right.getReducedValueAccelerated(ctx, thisValue, factory))); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { throw new RuntimeException("improper use of AST element"); } public void setRightMost(ASTNode right) { Or n = this; while (n.right != null && n.right instanceof Or) { n = (Or) n.right; } n.right = right; } public ASTNode getRightMost() { Or n = this; while (n.right != null && n.right instanceof Or) { n = (Or) n.right; } return n.right; } public String toString() { return "(" + left.toString() + " || " + right.toString() + ")"; } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/ASTNode.java0000644000175000017500000003205711354152713022550 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import static org.mvel2.Operator.NOOP; import org.mvel2.ParserConfiguration; import org.mvel2.ParserContext; import static org.mvel2.PropertyAccessor.get; import org.mvel2.compiler.Accessor; import org.mvel2.debug.DebugTools; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import org.mvel2.optimizers.OptimizationNotSupported; import static org.mvel2.optimizers.OptimizerFactory.*; import static org.mvel2.util.CompilerTools.getInjectedImports; import static org.mvel2.util.ParseTools.handleNumericConversion; import static org.mvel2.util.ParseTools.isNumber; import java.io.Serializable; import static java.lang.Thread.currentThread; @SuppressWarnings({"ManualArrayCopy", "CaughtExceptionImmediatelyRethrown"}) public class ASTNode implements Cloneable, Serializable { public static final int LITERAL = 1; public static final int DEEP_PROPERTY = 1 << 1; public static final int OPERATOR = 1 << 2; public static final int IDENTIFIER = 1 << 3; public static final int COMPILE_IMMEDIATE = 1 << 4; public static final int NUMERIC = 1 << 5; public static final int INVERT = 1 << 6; public static final int ASSIGN = 1 << 7; public static final int COLLECTION = 1 << 8; public static final int THISREF = 1 << 9; public static final int INLINE_COLLECTION = 1 << 10; public static final int BLOCK_IF = 1 << 11; public static final int BLOCK_FOREACH = 1 << 12; public static final int BLOCK_WITH = 1 << 13; public static final int BLOCK_UNTIL = 1 << 14; public static final int BLOCK_WHILE = 1 << 15; public static final int BLOCK_DO = 1 << 16; public static final int BLOCK_DO_UNTIL = 1 << 17; public static final int BLOCK_FOR = 1 << 18; public static final int OPT_SUBTR = 1 << 19; public static final int DEFERRED_TYPE_RES = 1 << 23; public static final int STRONG_TYPING = 1 << 24; public static final int PCTX_STORED = 1 << 25; public static final int ARRAY_TYPE_LITERAL = 1 << 26; public static final int NOJIT = 1 << 27; public static final int DEOP = 1 << 28; public static final int DISCARD = 1 << 29; // *** // protected int firstUnion; protected int endOfName; public int fields = 0; protected Class egressType; protected char[] name; protected String nameCache; protected Object literal; protected transient volatile Accessor accessor; protected volatile Accessor safeAccessor; protected int cursorPosition; public ASTNode nextASTNode; public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (accessor != null) { try { return accessor.getValue(ctx, thisValue, factory); } catch (ClassCastException ce) { if ((fields & DEOP) == 0) { accessor = null; fields |= DEOP | NOJIT; synchronized (this) { return getReducedValueAccelerated(ctx, thisValue, factory); } } else { throw ce; } } } else { if ((fields & DEOP) != 0) { fields ^= DEOP; } AccessorOptimizer optimizer; Object retVal = null; if ((fields & NOJIT) != 0) { optimizer = getAccessorCompiler(SAFE_REFLECTIVE); } else { optimizer = getDefaultAccessorCompiler(); } ParserContext pCtx; if ((fields & PCTX_STORED) != 0) { pCtx = (ParserContext) literal; } else { pCtx = new ParserContext(new ParserConfiguration(getInjectedImports(factory), null)); } try { setAccessor(optimizer.optimizeAccessor(pCtx, name, ctx, thisValue, factory, true, egressType)); } catch (OptimizationNotSupported ne) { setAccessor((optimizer = getAccessorCompiler(SAFE_REFLECTIVE)) .optimizeAccessor(pCtx, name, ctx, thisValue, factory, true, null)); } if (accessor == null) { return get(name, ctx, factory, thisValue); } if (retVal == null) { retVal = optimizer.getResultOptPass(); } if (egressType == null) { egressType = optimizer.getEgressType(); } return retVal; } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { if ((fields & (LITERAL)) != 0) { return literal; } else { return get(name, ctx, factory, thisValue); } } protected String getAbsoluteRootElement() { if ((fields & (DEEP_PROPERTY | COLLECTION)) != 0) { return new String(name, 0, getAbsoluteFirstPart()); } return nameCache; } public Class getEgressType() { return egressType; } public void setEgressType(Class egressType) { this.egressType = egressType; } protected String getAbsoluteRemainder() { return (fields & COLLECTION) != 0 ? new String(name, endOfName, name.length - endOfName) : ((fields & DEEP_PROPERTY) != 0 ? new String(name, firstUnion + 1, name.length - firstUnion - 1) : null); } public char[] getNameAsArray() { return name; } private int getAbsoluteFirstPart() { if ((fields & COLLECTION) != 0) { if (firstUnion < 0 || endOfName < firstUnion) return endOfName; else return firstUnion; } else if ((fields & DEEP_PROPERTY) != 0) { return firstUnion; } else { return -1; } } public String getAbsoluteName() { if (firstUnion > 0) { return new String(name, 0, getAbsoluteFirstPart()); } else { return getName(); } } public String getName() { if (nameCache != null) { return nameCache; } else if (name != null) { return nameCache = new String(name); } return ""; } public Object getLiteralValue() { return literal; } public void storeInLiteralRegister(Object o) { this.literal = o; } public void setLiteralValue(Object literal) { this.literal = literal; this.fields |= LITERAL; } protected Object tryStaticAccess(Object thisRef, VariableResolverFactory factory) { try { /** * Try to resolve this *smartly* as a static class reference. * * This starts at the end of the token and starts to step backwards to figure out whether * or not this may be a static class reference. We search for method calls simply by * inspecting for ()'s. The first union area we come to where no brackets are present is our * test-point for a class reference. If we find a class, we pass the reference to the * property accessor along with trailing methods (if any). * */ boolean meth = false; int depth = 0; int last = name.length; for (int i = last - 1; i > 0; i--) { switch (name[i]) { case '.': if (depth == 0 && !meth) { try { Class.forName(new String(name, 0, i), true, currentThread().getContextClassLoader()); return get(new String(name, last, name.length - last), Class.forName(new String(name, 0, last), true, currentThread().getContextClassLoader()), factory, thisRef); } catch (ClassNotFoundException e) { return get(new String(name, i + 1, name.length - i - 1), Class.forName(new String(name, 0, i), true, currentThread().getContextClassLoader()), factory, thisRef); } } meth = false; last = i; break; case ')': depth++; break; case '(': if (--depth == 0) meth = true; break; } } } catch (Exception cnfe) { // do nothing. } return null; } @SuppressWarnings({"SuspiciousMethodCalls"}) protected void setName(char[] name) { if (isNumber(name)) { egressType = (literal = handleNumericConversion(name)).getClass(); if (((fields |= NUMERIC | LITERAL | IDENTIFIER) & INVERT) != 0) { try { literal = ~((Integer) literal); } catch (ClassCastException e) { throw new CompileException("bitwise (~) operator can only be applied to integers"); } } return; } this.literal = new String(name); Scan: for (int i = 0; i < name.length; i++) { switch (name[i]) { case '.': if (firstUnion == 0) { firstUnion = i; } break; case '[': if (firstUnion == 0) { firstUnion = i; } if (endOfName == 0) { endOfName = i; if (i < name.length && name[i+1] == ']') fields |= ARRAY_TYPE_LITERAL; break Scan; } } } if ((fields & INLINE_COLLECTION) != 0) { return; } if (firstUnion > 0) { fields |= DEEP_PROPERTY | IDENTIFIER; } else { fields |= IDENTIFIER; } } public Accessor setAccessor(Accessor accessor) { return this.accessor = accessor; } public boolean isIdentifier() { return (fields & IDENTIFIER) != 0; } public boolean isLiteral() { return (fields & LITERAL) != 0; } public boolean isThisVal() { return (fields & THISREF) != 0; } public boolean isOperator() { return (fields & OPERATOR) != 0; } public boolean isOperator(Integer operator) { return (fields & OPERATOR) != 0 && operator.equals(literal); } public Integer getOperator() { return NOOP; } protected boolean isCollection() { return (fields & COLLECTION) != 0; } public boolean isAssignment() { return ((fields & ASSIGN) != 0); } public boolean isDeepProperty() { return ((fields & DEEP_PROPERTY) != 0); } public void setAsLiteral() { fields |= LITERAL; } public int getCursorPosition() { return cursorPosition; } public void setCursorPosition(int cursorPosition) { this.cursorPosition = cursorPosition; } public boolean isDiscard() { return fields != -1 && (fields & DISCARD) != 0; } public void discard() { this.fields |= DISCARD; } public void strongTyping() { this.fields |= STRONG_TYPING; } public void storePctx() { this.fields |= PCTX_STORED; } public boolean isDebuggingSymbol() { return this.fields == -1; } public int getFields() { return fields; } public Accessor getAccessor() { return accessor; } public boolean canSerializeAccessor() { return safeAccessor != null; } public ASTNode() { } public ASTNode(char[] expr, int start, int end, int fields) { this.fields = fields; name = new char[end - (this.cursorPosition = start)]; for (int i = 0; i < name.length; i++) { name[i] = expr[i + start]; } setName(name); } public String toString() { return isOperator() ? "<<" + DebugTools.getOperatorName(getOperator()) + ">>" : String.valueOf(literal); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IndexedPostFixIncNode.java0000644000175000017500000000317111153102156025434 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.DataTypes; import org.mvel2.math.MathProcessor; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class IndexedPostFixIncNode extends ASTNode { private int register; public IndexedPostFixIncNode(int register) { this.register = register; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver vResolver = factory.getIndexedVariableResolver(register); vResolver.setValue(MathProcessor.doOperations(ctx = vResolver.getValue(), Operator.ADD, DataTypes.INTEGER, 1)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IndexedDeclTypedVarNode.java0000644000175000017500000000361511077457613025757 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class IndexedDeclTypedVarNode extends ASTNode implements Assignment { private int register; public IndexedDeclTypedVarNode(int register, Class type) { this.egressType = type; this.register = register; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { factory.createIndexedVariable(register, null, egressType); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { factory.createIndexedVariable(register, null, egressType); return null; } public String getAssignmentVar() { return null; } public char[] getExpression() { return new char[0]; } public boolean isAssignment() { return true; } public boolean isNewDeclaration() { return true; } public void setValueStatement(ExecutableStatement stmt) { throw new RuntimeException("illegal operation"); } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Function.java0000644000175000017500000001423111163351223023065 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import org.mvel2.compiler.AbstractParser; import org.mvel2.compiler.EndWithValue; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory; import org.mvel2.integration.impl.FunctionVariableResolverFactory; import static org.mvel2.util.ParseTools.parseParameterDefList; import static org.mvel2.util.ParseTools.subCompileExpression; import java.util.Map; @SuppressWarnings({"unchecked"}) public class Function extends ASTNode implements Safe { protected String name; protected ExecutableStatement compiledBlock; protected String[] parameters; protected int parmNum; public Function(String name, char[] parameters, char[] block, ParserContext pCtx) { if ((this.name = name) == null || name.length() == 0) { this.name = null; } parmNum = (this.parameters = parseParameterDefList(parameters, 0, parameters.length)).length; pCtx.declareFunction(this); ParserContext ctx = new ParserContext(pCtx.getParserConfiguration()); ctx.setIndexAllocation(true); /** * To prevent the function parameters from being counted as * external inputs, we must add them explicitly here. */ for (String s : this.parameters) { ctx.addVariable(s, Object.class); ctx.addIndexedVariable(s); } /** * Compile the expression so we can determine the input-output delta. */ ExpressionCompiler compiler = new ExpressionCompiler(block); compiler.setVerifyOnly(true); compiler.compile(ctx); /** * Add globals as inputs */ if (pCtx.getVariables() != null) { for (Map.Entry e : pCtx.getVariables().entrySet()) { ctx.addInput(e.getKey(), e.getValue()); } ctx.processTables(); } ctx.addIndexedVariables(ctx.getVariables().keySet()); ctx.getVariables().clear(); this.compiledBlock = (ExecutableStatement) subCompileExpression(block, ctx); AbstractParser.setCurrentThreadParserContext(pCtx); this.parameters = new String[ctx.getIndexedVariables().size()]; int i = 0; for (String s : ctx.getIndexedVariables()) { this.parameters[i++] = s; } this.egressType = this.compiledBlock.getKnownEgressType(); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (name != null) { if (factory.isResolveable(name)) throw new CompileException("duplicate function: " + name); factory.createVariable(name, this); } return this; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { if (name != null) { if (factory.isResolveable(name)) throw new CompileException("duplicate function: " + name); factory.createVariable(name, this); } return this; } public Object call(Object ctx, Object thisValue, VariableResolverFactory factory, Object[] parms) { try { if (parms != null && parms.length != 0) { // detect tail recursion if (factory instanceof FunctionVariableResolverFactory && ((FunctionVariableResolverFactory) factory).getIndexedVariableResolvers().length == parms.length) { FunctionVariableResolverFactory fvrf = (FunctionVariableResolverFactory) factory; if (fvrf.getFunction().equals(this)) { VariableResolver[] swapVR = fvrf.getIndexedVariableResolvers(); fvrf.updateParameters(parms); try { return compiledBlock.getValue(ctx, thisValue, fvrf); } finally { fvrf.setIndexedVariableResolvers(swapVR); } } } return compiledBlock.getValue(ctx, thisValue, new FunctionVariableResolverFactory(this, factory, parameters, parms)); } else { return compiledBlock.getValue(ctx, thisValue, new DefaultLocalVariableResolverFactory(factory)); } } catch (EndWithValue end) { return end.getValue(); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String[] getParameters() { return parameters; } public void setParameters(String[] parameters) { this.parameters = parameters; } public boolean hasParameters() { return this.parameters != null && this.parameters.length != 0; } public void checkArgumentCount(int passing) { if (passing != parmNum) { throw new CompileException("bad number of arguments in function call: " + passing + " (expected: " + (parmNum == 0 ? "none" : parmNum) + ")"); } } public ExecutableStatement getCompiledBlock() { return compiledBlock; } public String toString() { return "FunctionDef:" + (name == null ? "Anonymous" : name); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/PreFixDecNode.java0000644000175000017500000000312411153102156023714 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.DataTypes; import org.mvel2.math.MathProcessor; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class PreFixDecNode extends ASTNode { private String name; public PreFixDecNode(String name) { this.name = name; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver vResolver = factory.getVariableResolver(name); vResolver.setValue(ctx = MathProcessor.doOperations(vResolver.getValue(), Operator.SUB, DataTypes.INTEGER, 1)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/LineLabel.java0000644000175000017500000000357511077457613023156 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class LineLabel extends ASTNode { private String sourceFile; private int lineNumber; public LineLabel(int lineNumber) { this.lineNumber = lineNumber; this.fields = -1; } public LineLabel(String sourceFile, int lineNumber) { this.lineNumber = lineNumber; this.sourceFile = sourceFile; this.fields = -1; } public String getSourceFile() { return sourceFile; } public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; } public int getLineNumber() { return lineNumber; } public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return null; } public String toString() { return "[SourceLine:" + lineNumber + "]"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/And.java0000644000175000017500000000412511144173417022011 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.CompilerTools.expectType; import org.mvel2.ast.BooleanNode; public class And extends BooleanNode { public And(ASTNode left, ASTNode right, boolean strongTyping) { expectType(this.left = left, Boolean.class, strongTyping); expectType(this.right = right, Boolean.class, strongTyping); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return (((Boolean) left.getReducedValueAccelerated(ctx, thisValue, factory)) && ((Boolean) right.getReducedValueAccelerated(ctx, thisValue, factory))); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { throw new RuntimeException("improper use of AST element"); } public String toString() { return "(" + left.toString() + " && " + right.toString() + ")"; } public void setRightMost(ASTNode right) { And n = this; while (n.right != null && n.right instanceof And) { n = (And) n.right; } n.right = right; } public ASTNode getRightMost() { And n = this; while (n.right != null && n.right instanceof And) { n = (And) n.right; } return n.right; } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/PostFixIncNode.java0000644000175000017500000000312411153102156024131 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.DataTypes; import org.mvel2.math.MathProcessor; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class PostFixIncNode extends ASTNode { private String name; public PostFixIncNode(String name) { this.name = name; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver vResolver = factory.getVariableResolver(name); vResolver.setValue(MathProcessor.doOperations(ctx = vResolver.getValue(), Operator.ADD, DataTypes.INTEGER, 1)); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/InterceptorWrapper.java0000644000175000017500000000323711077457613025161 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.integration.Interceptor; import org.mvel2.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class InterceptorWrapper extends ASTNode { private Interceptor interceptor; private ASTNode node; public InterceptorWrapper(Interceptor interceptor, ASTNode node) { this.interceptor = interceptor; this.node = node; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { interceptor.doBefore(node, factory); interceptor.doAfter(ctx = node.getReducedValueAccelerated(ctx, thisValue, factory), node, factory); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { interceptor.doBefore(node, factory); interceptor.doAfter(ctx = node.getReducedValue(ctx, thisValue, factory), node, factory); return ctx; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/TypeDescriptor.java0000644000175000017500000001447511253250512024271 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import static org.mvel2.ast.ASTNode.COMPILE_IMMEDIATE; import org.mvel2.compiler.AbstractParser; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ArrayTools.findFirst; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.*; import java.io.Serializable; import static java.lang.Character.isDigit; import java.util.Iterator; import java.util.LinkedList; public class TypeDescriptor implements Serializable { private String className; private char[] classNameArray; private ArraySize[] arraySize; private ExecutableStatement[] compiledArraySize; int endRange; public TypeDescriptor() { } public TypeDescriptor(char[] name, int fields) { updateClassName(this.classNameArray = name, fields); } public void updateClassName(char[] name, int fields) { this.classNameArray = name; if (name.length == 0 || !ParseTools.isIdentifierPart(name[0]) || isDigit(name[0])) return; if ((endRange = findFirst('(', name)) == -1) { if ((endRange = findFirst('[', name)) != -1) { className = new String(name, 0, endRange); int to; LinkedList sizes = new LinkedList(); while (endRange < name.length) { while (endRange < name.length && isWhitespace(name[endRange])) endRange++; if (endRange == name.length || name[endRange] == '{') break; if (name[endRange] != '[') { throw new CompileException("unexpected token in contstructor", name, endRange); } to = balancedCapture(name, endRange, '['); sizes.add(subset(name, ++endRange, to - endRange)); endRange = to + 1; } Iterator iter = sizes.iterator(); arraySize = new ArraySize[sizes.size()]; for (int i = 0; i < arraySize.length; i++) arraySize[i] = new ArraySize(iter.next()); if ((fields & COMPILE_IMMEDIATE) != 0) { compiledArraySize = new ExecutableStatement[arraySize.length]; for (int i = 0; i < compiledArraySize.length; i++) compiledArraySize[i] = (ExecutableStatement) subCompileExpression(arraySize[i].value); } return; } className = new String(name); } else { className = new String(name, 0, endRange); } } public boolean isArray() { return arraySize != null; } public int getArrayLength() { return arraySize.length; } public ArraySize[] getArraySize() { return arraySize; } public ExecutableStatement[] getCompiledArraySize() { return compiledArraySize; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public boolean isClass() { return className != null && className.length() != 0; } public int getEndRange() { return endRange; } public void setEndRange(int endRange) { this.endRange = endRange; } public static Class getClassReference(Class baseType, TypeDescriptor tDescr, VariableResolverFactory factory, ParserContext ctx) throws ClassNotFoundException { return findClass(factory, repeatChar('[', tDescr.arraySize.length) + "L" + baseType.getName() + ";", ctx); } public static Class getClassReference(ParserContext ctx, Class cls, TypeDescriptor tDescr) throws ClassNotFoundException { if (tDescr.isArray()) { cls = findClass(null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx); } return cls; } public static Class getClassReference(ParserContext ctx, TypeDescriptor tDescr) throws ClassNotFoundException { Class cls; if (ctx != null && ctx.hasImport(tDescr.className)) { cls = ctx.getImport(tDescr.className); if (tDescr.isArray()) { cls = findClass(null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx); } } else if (ctx == null && hasContextFreeImport(tDescr.className)) { cls = getContextFreeImport(tDescr.className); if (tDescr.isArray()) { cls = findClass(null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx); } } else { cls = createClass(tDescr.getClassName(), ctx); if (tDescr.isArray()) { cls = findClass(null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx); } } return cls; } public boolean isUndimensionedArray() { if (arraySize != null) { for (ArraySize anArraySize : arraySize) { if (anArraySize.value.length == 0) return true; } } return false; } public static boolean hasContextFreeImport(String name) { return AbstractParser.LITERALS.containsKey(name) && AbstractParser.LITERALS.get(name) instanceof Class; } public static Class getContextFreeImport(String name) { return (Class) AbstractParser.LITERALS.get(name); } public char[] getClassNameArray() { return classNameArray; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/ForEachNode.java0000644000175000017500000001740011205051661023416 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory; import org.mvel2.integration.impl.ItemResolverFactory; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.*; import java.lang.reflect.Array; import java.util.Iterator; /** * @author Christopher Brock */ public class ForEachNode extends BlockNode { protected String item; protected Class itemType; private char[] cond; protected ExecutableStatement condition; protected ExecutableStatement compiledBlock; private static final int ITERABLE = 0; private static final int ARRAY = 1; private static final int CHARSEQUENCE = 2; private static final int INTEGER = 3; private int type = -1; public ForEachNode(char[] condition, char[] block, int fields, ParserContext pCtx) { handleCond(this.name = condition, this.fields = fields, pCtx); this.block = block; if ((fields & COMPILE_IMMEDIATE) != 0) { if (pCtx.isStrictTypeEnforcement() && itemType != null) { pCtx = pCtx.createSubcontext(); pCtx.addInput(item, itemType); } this.compiledBlock = (ExecutableStatement) subCompileExpression(block, pCtx); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { ItemResolverFactory.ItemResolver itemR = new ItemResolverFactory.ItemResolver(item); ItemResolverFactory itemFactory = new ItemResolverFactory(itemR, new DefaultLocalVariableResolverFactory(factory)); Object iterCond = condition.getValue(ctx, thisValue, factory); if (type == -1) { determineIterType(iterCond.getClass()); } switch (type) { case ARRAY: int len = Array.getLength(iterCond); for (int i = 0; i < len; i++) { itemR.setValue(Array.get(iterCond, i)); compiledBlock.getValue(ctx, thisValue, itemFactory); } break; case CHARSEQUENCE: for (Object o : iterCond.toString().toCharArray()) { itemR.setValue(o); compiledBlock.getValue(ctx, thisValue, itemFactory); } break; case INTEGER: int max = (Integer) iterCond + 1; for (int i = 1; i != max; i++) { itemR.setValue(i); compiledBlock.getValue(ctx, thisValue, itemFactory); } break; case ITERABLE: for (Object o : (Iterable) iterCond) { itemR.setValue(o); compiledBlock.getValue(ctx, thisValue, itemFactory); } break; } return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { ItemResolverFactory.ItemResolver itemR = new ItemResolverFactory.ItemResolver(item); ItemResolverFactory itemFactory = new ItemResolverFactory(itemR, new DefaultLocalVariableResolverFactory(factory)); Object iterCond = MVEL.eval(cond, thisValue, factory); if (itemType != null && itemType.isArray()) enforceTypeSafety(itemType, getBaseComponentType(iterCond.getClass())); this.compiledBlock = (ExecutableStatement) subCompileExpression(block); if (iterCond instanceof Iterable) { for (Object o : (Iterable) iterCond) { itemR.setValue(o); compiledBlock.getValue(ctx, thisValue, itemFactory); } } else if (iterCond != null && iterCond.getClass().isArray()) { int len = Array.getLength(iterCond); for (int i = 0; i < len; i++) { itemR.setValue(Array.get(iterCond, i)); compiledBlock.getValue(ctx, thisValue, itemFactory); } } else if (iterCond instanceof CharSequence) { for (Object o : iterCond.toString().toCharArray()) { itemR.setValue(o); compiledBlock.getValue(ctx, thisValue, itemFactory); } } else if (iterCond instanceof Integer) { int max = (Integer) iterCond + 1; for (int i = 1; i != max; i++) { itemR.setValue(i); compiledBlock.getValue(ctx, thisValue, itemFactory); } } else { throw new CompileException("non-iterable type: " + (iterCond != null ? iterCond.getClass().getName() : "null")); } return null; } private void handleCond(char[] condition, int fields, ParserContext pCtx) { int cursor = 0; while (cursor < condition.length && condition[cursor] != ':') cursor++; if (cursor == condition.length || condition[cursor] != ':') throw new CompileException("expected : in foreach"); int x; if ((x = (item = createStringTrimmed(condition, 0, cursor)).indexOf(' ')) != -1) { String tk = new String(condition, 0, x).trim(); try { itemType = ParseTools.findClass(null, tk, pCtx); item = new String(condition, x, cursor - x).trim(); } catch (ClassNotFoundException e) { throw new CompileException("cannot resolve identifier: " + tk); } } this.cond = subset(condition, ++cursor); if ((fields & COMPILE_IMMEDIATE) != 0) { Class egress = (this.condition = (ExecutableStatement) subCompileExpression(this.cond, pCtx)).getKnownEgressType(); if (itemType != null && egress.isArray()) { enforceTypeSafety(itemType, getBaseComponentType(this.condition.getKnownEgressType())); } else if (pCtx.isStrongTyping()) { determineIterType(egress); } } } private void determineIterType(Class t) { if (Iterable.class.isAssignableFrom(t)) { type = ITERABLE; } else if (t.isArray()) { type = ARRAY; } else if (CharSequence.class.isAssignableFrom(t)) { type = CHARSEQUENCE; } else if (Integer.class.isAssignableFrom(t)) { type = INTEGER; } else { throw new CompileException("non-iterable type: " + t.getName()); } } private static void enforceTypeSafety(Class required, Class actual) { if (!required.isAssignableFrom(actual)) { throw new CompileException("type mismatch in foreach: expected: " + required.getName() + "; but found: " + getBaseComponentType(actual)); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IndexedOperativeAssign.java0000644000175000017500000000424411115170774025716 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.MVEL.eval; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; import org.mvel2.math.MathProcessor; import org.mvel2.ParserContext; public class IndexedOperativeAssign extends ASTNode { private final int register; private ExecutableStatement statement; private final int operation; public IndexedOperativeAssign(char[] expr, int operation, int register, int fields, ParserContext pCtx) { this.operation = operation; this.name = expr; this.register = register; if ((fields & COMPILE_IMMEDIATE) != 0) { statement = (ExecutableStatement) subCompileExpression(expr, pCtx); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver resolver = factory.getIndexedVariableResolver(register); resolver.setValue(ctx = MathProcessor.doOperations(resolver.getValue(), operation, statement.getValue(ctx, thisValue, factory))); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolver resolver = factory.getIndexedVariableResolver(register); resolver.setValue(ctx = MathProcessor.doOperations(resolver.getValue(), operation, eval(name, ctx, factory))); return ctx; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Soundslike.java0000644000175000017500000000274711104135617023433 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.CompilerTools; import static org.mvel2.util.Soundex.soundex; public class Soundslike extends ASTNode { private ASTNode stmt; private ASTNode soundslike; public Soundslike(ASTNode stmt, ASTNode clsStmt) { this.stmt = stmt; this.soundslike = clsStmt; CompilerTools.expectType(clsStmt, String.class, true); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return soundex(String.valueOf(soundslike.getReducedValueAccelerated(ctx, thisValue, factory))) .equals(soundex((String) stmt.getReducedValueAccelerated(ctx, thisValue, factory))); } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { try { String i = String.valueOf(soundslike.getReducedValue(ctx, thisValue, factory)); if (i == null) throw new ClassCastException(); String x = (String) stmt.getReducedValue(ctx, thisValue, factory); if (x == null) throw new CompileException("not a string: " + stmt.getName()); return soundex(i).equals(soundex(x)); } catch (ClassCastException e) { throw new CompileException("not a string: " + soundslike.getName()); } } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/LiteralDeepPropertyNode.java0000644000175000017500000000400511110327536026045 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.PropertyAccessor.get; import static org.mvel2.compiler.AbstractParser.getCurrentThreadParserContext; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import static org.mvel2.optimizers.OptimizerFactory.getThreadAccessorOptimizer; /** * @author Christopher Brock */ @SuppressWarnings({"CaughtExceptionImmediatelyRethrown"}) public class LiteralDeepPropertyNode extends ASTNode { private Object literal; public LiteralDeepPropertyNode(char[] expr, int fields, Object literal) { this.fields = fields; this.name = expr; this.literal = literal; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (accessor != null) { return accessor.getValue(literal, thisValue, factory); } else { AccessorOptimizer aO = getThreadAccessorOptimizer(); accessor = aO.optimizeAccessor(getCurrentThreadParserContext(), name, literal, thisValue, factory, false, null); return aO.getResultOptPass(); } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return get(name, literal, factory, thisValue); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/ImportNode.java0000644000175000017500000000517611147075773023407 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.findClassImportResolverFactory; /** * @author Christopher Brock */ public class ImportNode extends ASTNode { private Class importClass; private boolean packageImport; private short offset; private static final char[] WC_TEST = new char[]{'.', '*'}; public ImportNode(char[] expr) { this.name = expr; if (ParseTools.endsWith(expr, WC_TEST)) { packageImport = true; offset = (short) ParseTools.findLast(expr, '.'); } else { try { this.importClass = Class.forName(new String(expr), true, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { throw new CompileException("class not found: " + new String(expr)); } } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (!packageImport) { return findClassImportResolverFactory(factory).addClass(importClass); } else { findClassImportResolverFactory(factory).addPackageImport(new String(name, 0, (int) offset)); return null; } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } public Class getImportClass() { return importClass; } public boolean isPackageImport() { return packageImport; } public void setPackageImport(boolean packageImport) { this.packageImport = packageImport; } public String getPackageImport() { return new String(name, 0, offset); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/WithNode.java0000644000175000017500000002145611246517502023036 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.MVEL; import static org.mvel2.MVEL.executeSetExpression; import org.mvel2.Operator; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.*; import static org.mvel2.util.ParseTools.parseWithExpressions; import static org.mvel2.util.PropertyTools.getReturnType; import org.mvel2.util.StringAppender; import org.mvel2.util.ParseTools; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author Christopher Brock */ public class WithNode extends BlockNode implements NestedStatement { protected String nestParm; protected ExecutableStatement nestedStatement; protected ParmValuePair[] withExpressions; public WithNode(char[] expr, char[] block, int fields, ParserContext pCtx) { nestParm = createStringTrimmed(this.name = expr); this.block = block; if ((fields & COMPILE_IMMEDIATE) != 0) { pCtx.setBlockSymbols(true); egressType = (nestedStatement = (ExecutableStatement) subCompileExpression(nestParm.toCharArray(), pCtx)).getKnownEgressType(); withExpressions = compileWithExpressions(block, nestParm, egressType, pCtx); pCtx.setBlockSymbols(false); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { Object ctxObject = nestedStatement.getValue(ctx, thisValue, factory); if (ctxObject == null) throw new CompileException("with-block against null pointer"); for (ParmValuePair pvp : withExpressions) { pvp.eval(ctxObject, factory); } return ctxObject; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { parseWithExpressions(nestParm, block, 0, block.length, ctx = MVEL.eval(name, ctx, factory), factory); return ctx; } public static ParmValuePair[] compileWithExpressions(char[] block, String nestParm, Class egressType, ParserContext pCtx) { /** * * MAINTENANCE NOTE: AN INTERPRETED MODE VERSION OF THIS CODE IS DUPLICATED IN: ParseTools * */ List parms = new ArrayList(); String parm = ""; int start = 0; int end = -1; int oper = -1; for (int i = 0; i < block.length; i++) { switch (block[i]) { case '{': case '[': case '(': i = balancedCapture(block, i, block[i]); continue; case '/': if (i < block.length && block[i + 1] == '/') { while (i < block.length && block[i] != '\n') block[i++] = ' '; if (parm == null) start = i; } else if (i < block.length && block[i + 1] == '*') { int len = block.length - 1; while (i < len && !(block[i] == '*' && block[i + 1] == '/')) { block[i++] = ' '; } block[i++] = ' '; block[i++] = ' '; if (parm == null) start = i; } else if (i < block.length && block[i + 1] == '=') { oper = Operator.DIV; } continue; case '%': case '*': case '-': case '+': if (i + 1 < block.length && block[i + 1] == '=') { oper = opLookup(block[i]); } continue; case '=': parm = createStringTrimmed(block, start, i - start - (oper != -1 ? 1 : 0)); start = i + 1; continue; case ',': if (end == -1) end = i; if (parm == null || parm.length() == 0) { parms.add( new ParmValuePair(null, (ExecutableStatement) subCompileExpression( new StringAppender(nestParm).append('.') .append(subset(block, start, end - start)).toChars(), pCtx), egressType, pCtx) ); oper = -1; start = ++i; } else { parms.add(new ParmValuePair( parm, (ExecutableStatement) subCompileExpression( createShortFormOperativeAssignment(nestParm + "." + parm, subset(block, start, end - start), oper), pCtx ) , egressType, pCtx)); parm = null; oper = -1; start = ++i; } end = -1; break; } } if (start != (end = block.length)) { if (parm == null || "".equals(parm)) { parms.add( new ParmValuePair(null, (ExecutableStatement) subCompileExpression(new StringAppender(nestParm).append('.') .append(subset(block, start, end - start)).toChars(), pCtx), egressType, pCtx) ); } else { parms.add(new ParmValuePair( parm, (ExecutableStatement) subCompileExpression( createShortFormOperativeAssignment(nestParm + "." + parm, subset(block, start, end - start), oper), pCtx ) , egressType, pCtx)); } } ParmValuePair[] withExpressions; parms.toArray(withExpressions = new ParmValuePair[parms.size()]); return withExpressions; } public ExecutableStatement getNestedStatement() { return nestedStatement; } public ParmValuePair[] getWithExpressions() { return withExpressions; } public static final class ParmValuePair implements Serializable { private Serializable setExpression; private ExecutableStatement statement; public ParmValuePair() { } public ParmValuePair(String parameter, ExecutableStatement statement, Class ingressType, ParserContext pCtx) { if (parameter != null && parameter.length() != 0) { this.setExpression = MVEL.compileSetExpression(parameter, ingressType != null ? getReturnType(ingressType, parameter, pCtx) : Object.class , pCtx); } this.statement = statement; } public Serializable getSetExpression() { return setExpression; } public void setSetExpression(Serializable setExpression) { this.setExpression = setExpression; } public ExecutableStatement getStatement() { return statement; } public void setStatement(ExecutableStatement statement) { this.statement = statement; } public void eval(Object ctx, VariableResolverFactory factory) { if (setExpression == null) { this.statement.getValue(ctx, factory); } else { MVEL.executeSetExpression(setExpression, ctx, factory, this.statement.getValue(ctx, factory)); } } } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/IntDiv.java0000644000175000017500000000205611307306541022502 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.Operator; import org.mvel2.integration.VariableResolverFactory; public class IntDiv extends BinaryOperation implements IntOptimized { public IntDiv(ASTNode left, ASTNode right) { super(Operator.MULT); this.left = left; this.right = right; } @Override public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Integer) left.getReducedValueAccelerated(ctx, thisValue, factory)) / ((Integer) right.getReducedValueAccelerated(ctx, thisValue, factory)); } @Override public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return ((Integer) left.getReducedValue(ctx, thisValue, factory)) / ((Integer) right.getReducedValue(ctx, thisValue, factory)); } @Override public void setRight(ASTNode node) { super.setRight(node); } @Override public Class getEgressType() { return Integer.class; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/InlineCollectionNode.java0000644000175000017500000001400411222477143025344 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.CompileException; import org.mvel2.compiler.AbstractParser; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.AccessorOptimizer; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.util.CollectionParser; import static org.mvel2.util.ParseTools.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Christopher Brock */ public class InlineCollectionNode extends ASTNode { private Object collectionGraph; private char[] trailing; public InlineCollectionNode(char[] expr, int start, int end, int fields, ParserContext pctx) { super(expr, start, end, fields | INLINE_COLLECTION); if ((fields & COMPILE_IMMEDIATE) != 0) { parseGraph(true, null, pctx); AccessorOptimizer ao = OptimizerFactory.getThreadAccessorOptimizer(); accessor = ao.optimizeCollection(pctx, collectionGraph, egressType, trailing, null, null, null); egressType = ao.getEgressType(); } } public InlineCollectionNode(char[] expr, int start, int end, int fields, Class type, ParserContext pctx) { super(expr, start, end, fields | INLINE_COLLECTION); this.egressType = type; if ((fields & COMPILE_IMMEDIATE) != 0) { parseGraph(true, type, pctx); AccessorOptimizer ao = OptimizerFactory.getThreadAccessorOptimizer(); accessor = ao.optimizeCollection(pctx,collectionGraph, egressType, trailing, null, null, null); egressType = ao.getEgressType(); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (accessor != null) { return accessor.getValue(ctx, thisValue, factory); } else { AccessorOptimizer ao = OptimizerFactory.getThreadAccessorOptimizer(); if (collectionGraph == null) parseGraph(true, null, null); accessor = ao.optimizeCollection(AbstractParser.getCurrentThreadParserContext(), collectionGraph, egressType, trailing, ctx, thisValue, factory); egressType = ao.getEgressType(); return accessor.getValue(ctx, thisValue, factory); } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { parseGraph(false, egressType, null); return execGraph(collectionGraph, egressType, ctx, factory); } private void parseGraph(boolean compile, Class type, ParserContext pCtx) { CollectionParser parser = new CollectionParser(); if (type == null) { collectionGraph = ((List) parser.parseCollection(name, compile, pCtx)).get(0); } else { collectionGraph = ((List) parser.parseCollection(name, compile, type, pCtx)).get(0); } if (parser.getCursor() + 2 < name.length) trailing = subset(name, parser.getCursor() + 2); if (this.egressType == null) this.egressType = collectionGraph.getClass(); } private Object execGraph(Object o, Class type, Object ctx, VariableResolverFactory factory) { if (o instanceof List) { ArrayList list = new ArrayList(((List)o).size()); for (Object item : (List) o) { list.add(execGraph(item, type, ctx, factory)); } return list; } else if (o instanceof Map) { HashMap map = new HashMap(); for (Object item : ((Map) o).keySet()) { map.put(execGraph(item, type, ctx, factory), execGraph(((Map)o).get(item), type, ctx, factory)); } return map; } else if (o instanceof Object[]) { int dim = 0; if (type != null) { String nm = type.getName(); while (nm.charAt(dim) == '[') dim++; } else { type = Object[].class; dim = 1; } Object newArray = Array.newInstance(getSubComponentType(type), ((Object[])o).length); try { Class cls = dim > 1 ? findClass(null, repeatChar('[', dim - 1) + "L" + getBaseComponentType(type).getName() + ";", AbstractParser.getCurrentThreadParserContext()) : type; int c = 0; for (Object item : (Object[]) o) { Array.set(newArray, c++, execGraph(item, cls, ctx, factory)); } return newArray; } catch (IllegalArgumentException e) { throw new CompileException("type mismatch in array", e); } catch (ClassNotFoundException e) { throw new RuntimeException("this error should never throw:" + getBaseComponentType(type).getName(), e); } } else { if (type.isArray()) { return MVEL.eval((String) o, ctx, factory, getBaseComponentType(type)); } else { return MVEL.eval((String) o, ctx, factory); } } } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/RegExMatch.java0000644000175000017500000000555111155605450023301 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.ParserContext; import static org.mvel2.MVEL.eval; import org.mvel2.compiler.ExecutableLiteral; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.subCompileExpression; import static java.lang.String.valueOf; import java.util.regex.Pattern; import static java.util.regex.Pattern.compile; import java.util.regex.PatternSyntaxException; public class RegExMatch extends ASTNode { private ExecutableStatement stmt; private ExecutableStatement patternStmt; private char[] pattern; private Pattern p; public RegExMatch(char[] expr, int fields, char[] pattern, ParserContext pCtx) { this.name = expr; this.pattern = pattern; if ((fields & COMPILE_IMMEDIATE) != 0) { this.stmt = (ExecutableStatement) subCompileExpression(expr); if ((this.patternStmt = (ExecutableStatement) subCompileExpression(pattern, pCtx)) instanceof ExecutableLiteral) { try { p = compile(valueOf(patternStmt.getValue(null, null))); } catch (PatternSyntaxException e) { throw new CompileException("bad regular expression", e); } } } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (p == null) { return compile(valueOf(patternStmt.getValue(ctx, thisValue, factory))).matcher(valueOf(stmt.getValue(ctx, thisValue, factory))).matches(); } else { return p.matcher(valueOf(stmt.getValue(ctx, thisValue, factory))).matches(); } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { try { return compile(valueOf(eval(pattern, ctx, factory))).matcher(valueOf(eval(name, ctx, factory))).matches(); } catch (PatternSyntaxException e) { throw new CompileException("bad regular expression", e); } } public Class getEgressType() { return Boolean.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Assignment.java0000644000175000017500000000167111077457613023432 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.compiler.ExecutableStatement; public interface Assignment { public String getAssignmentVar(); public char[] getExpression(); public boolean isNewDeclaration(); public void setValueStatement(ExecutableStatement stmt); } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/WhileNode.java0000644000175000017500000000460311114570772023170 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import static org.mvel2.util.CompilerTools.expectType; import static org.mvel2.util.ParseTools.subCompileExpression; import org.mvel2.ParserContext; import java.util.HashMap; /** * @author Christopher Brock */ public class WhileNode extends BlockNode { protected String item; protected ExecutableStatement condition; protected ExecutableStatement compiledBlock; public WhileNode(char[] condition, char[] block, int fields, ParserContext pCtx) { expectType(this.condition = (ExecutableStatement) subCompileExpression(this.name = condition, pCtx), Boolean.class, ((fields & COMPILE_IMMEDIATE) != 0)); this.compiledBlock = (ExecutableStatement) subCompileExpression(this.block = block, pCtx); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory ctxFactory = new MapVariableResolverFactory(new HashMap(0), factory); while ((Boolean) condition.getValue(ctx, thisValue, factory)) { compiledBlock.getValue(ctx, thisValue, ctxFactory); } return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { VariableResolverFactory ctxFactory = new MapVariableResolverFactory(new HashMap(0), factory); while ((Boolean) condition.getValue(ctx, thisValue, factory)) { compiledBlock.getValue(ctx, thisValue, ctxFactory); } return null; } }mvel-2.0.18.orig/src/main/java/org/mvel2/ast/StaticImportNode.java0000644000175000017500000000505411155605450024540 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import org.mvel2.CompileException; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ArrayTools.findLast; import static org.mvel2.util.ParseTools.subset; import static java.lang.Thread.currentThread; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isStatic; /** * @author Christopher Brock */ public class StaticImportNode extends ASTNode { private Class declaringClass; private String methodName; private transient Method method; public StaticImportNode(char[] expr) { try { declaringClass = Class.forName(new String(subset(expr, 0, findLast('.', this.name = expr))), true, currentThread().getContextClassLoader()); methodName = new String(subset(expr, findLast('.', expr) + 1)); if (resolveMethod() == null) { throw new CompileException("can not find method for static import: " + declaringClass.getName() + "." + methodName); } } catch (Exception e) { throw new CompileException("unable to import class", e); } } private Method resolveMethod() { for (Method meth : declaringClass.getMethods()) { if (isStatic(meth.getModifiers()) && methodName.equals(meth.getName())) { return method = meth; } } return null; } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { factory.createVariable(methodName, method == null ? method = resolveMethod() : method); return null; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/Proto.java0000644000175000017500000003274411257005261022416 0ustar drazzibdrazzibpackage org.mvel2.ast; import org.mvel2.CompileException; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import org.mvel2.UnresolveablePropertyException; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.integration.impl.SimpleValueResolver; import org.mvel2.util.CallableProxy; import org.mvel2.util.SimpleIndexHashMapWrapper; import java.util.Collection; import java.util.Map; import java.util.Set; public class Proto extends ASTNode { private String name; private Map receivers; private int cursorStart; private int cursorEnd; public Proto(String name) { this.name = name; this.receivers = new SimpleIndexHashMapWrapper(); } public Receiver declareReceiver(String name, Function function) { Receiver r = new Receiver(null, ReceiverType.FUNCTION, function); receivers.put(name, r); return r; } public Receiver declareReceiver(String name, Class type, ExecutableStatement initCode) { Receiver r = new Receiver(null, ReceiverType.PROPERTY, initCode); receivers.put(name, r); return r; } public Receiver declareReceiver(String name, ReceiverType type, ExecutableStatement initCode) { Receiver r = new Receiver(null, type, initCode); receivers.put(name, r); return r; } public ProtoInstance newInstance(Object ctx, Object thisCtx, VariableResolverFactory factory) { return new ProtoInstance(this, ctx, thisCtx, factory); } @Override public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { factory.createVariable(name, this); return this; } @Override public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { factory.createVariable(name, this); return this; } public class Receiver implements CallableProxy { private ReceiverType type; private Object receiver; private ExecutableStatement initValue; private ProtoInstance instance; public Receiver(ProtoInstance protoInstance, ReceiverType type, Object receiver) { this.instance = protoInstance; this.type = type; this.receiver = receiver; } public Receiver(ProtoInstance protoInstance, ReceiverType type, ExecutableStatement stmt) { this.instance = protoInstance; this.type = type; this.initValue = stmt; } public Object call(Object ctx, Object thisCtx, VariableResolverFactory factory, Object[] parms) { switch (type) { case FUNCTION: return ((Function) receiver).call(ctx, thisCtx, new InvokationContextFactory(factory, instance.instanceStates), parms); case PROPERTY: return receiver; case DEFERRED: throw new CompileException("unresolved prototype receiver"); } return null; } public Receiver init(ProtoInstance instance, Object ctx, Object thisCtx, VariableResolverFactory factory) { return new Receiver(instance, type, type == ReceiverType.PROPERTY && initValue != null ? initValue.getValue(ctx, thisCtx, factory) : receiver); } public void setType(ReceiverType type) { this.type = type; } public void setInitValue(ExecutableStatement initValue) { this.initValue = initValue; } } public enum ReceiverType { DEFERRED, FUNCTION, PROPERTY } public class ProtoInstance implements Map { private Proto protoType; private VariableResolverFactory instanceStates; private SimpleIndexHashMapWrapper receivers; public ProtoInstance(Proto protoType, Object ctx, Object thisCtx, VariableResolverFactory factory) { this.protoType = protoType; receivers = new SimpleIndexHashMapWrapper(); for (Map.Entry entry : protoType.receivers.entrySet()) { receivers.put(entry.getKey(), entry.getValue().init(this, ctx, thisCtx, factory)); } instanceStates = new ProtoContextFactory(receivers); } public Proto getProtoType() { return protoType; } public int size() { return receivers.size(); } public boolean isEmpty() { return receivers.isEmpty(); } public boolean containsKey(Object key) { return receivers.containsKey(key); } public boolean containsValue(Object value) { return receivers.containsValue(value); } public Receiver get(Object key) { return receivers.get(key); } public Receiver put(String key, Receiver value) { return receivers.put(key, value); } public Receiver remove(Object key) { return receivers.remove(key); } public void putAll(Map m) { } public void clear() { } public Set keySet() { return receivers.keySet(); } public Collection values() { return receivers.values(); } public Set> entrySet() { return receivers.entrySet(); } } @Override public String getName() { return name; } @Override public String toString() { return "proto " + name; } public class ProtoContextFactory extends MapVariableResolverFactory { private final SimpleIndexHashMapWrapper variableResolvers; public ProtoContextFactory(SimpleIndexHashMapWrapper variables) { super(variables); variableResolvers = new SimpleIndexHashMapWrapper(variables, true); } @Override public VariableResolver createVariable(String name, Object value) { VariableResolver vr; try { (vr = getVariableResolver(name)).setValue(value); return vr; } catch (UnresolveablePropertyException e) { addResolver(name, vr = new ProtoResolver(variables, name)).setValue(value); return vr; } } @Override public VariableResolver createVariable(String name, Object value, Class type) { VariableResolver vr; try { vr = getVariableResolver(name); } catch (UnresolveablePropertyException e) { vr = null; } if (vr != null && vr.getType() != null) { throw new CompileException("variable already defined within scope: " + vr.getType() + " " + name); } else { addResolver(name, vr = new ProtoResolver(variables, name, type)).setValue(value); return vr; } } @Override public void setIndexedVariableNames(String[] indexedVariableNames) { // } @Override public String[] getIndexedVariableNames() { // return null; } @Override public VariableResolver createIndexedVariable(int index, String name, Object value, Class type) { VariableResolver vr = this.variableResolvers != null ? this.variableResolvers.getByIndex(index) : null; if (vr != null && vr.getType() != null) { throw new CompileException("variable already defined within scope: " + vr.getType() + " " + name); } else { return createIndexedVariable(variableIndexOf(name), name, value); } } @Override public VariableResolver createIndexedVariable(int index, String name, Object value) { VariableResolver vr = variableResolvers.getByIndex(index); if (vr == null) { vr = new SimpleValueResolver(value); variableResolvers.putAtIndex(index, vr); } else { vr.setValue(value); } return indexedVariableResolvers[index]; } @Override public VariableResolver getIndexedVariableResolver(int index) { return variableResolvers.getByIndex(index); } @Override public VariableResolver setIndexedVariableResolver(int index, VariableResolver resolver) { variableResolvers.putAtIndex(index, resolver); return resolver; } @Override public int variableIndexOf(String name) { return variableResolvers.indexOf(name); } public VariableResolver getVariableResolver(String name) { VariableResolver vr = variableResolvers.get(name); if (vr != null) { return vr; } else if (variables.containsKey(name)) { variableResolvers.put(name, vr = new ProtoResolver(variables, name)); return vr; } else if (nextFactory != null) { return nextFactory.getVariableResolver(name); } throw new UnresolveablePropertyException("unable to resolve variable '" + name + "'"); } } public class ProtoResolver implements VariableResolver { private String name; private Class knownType; private Map variableMap; public ProtoResolver(Map variableMap, String name) { this.variableMap = variableMap; this.name = name; } public ProtoResolver(Map variableMap, String name, Class knownType) { this.name = name; this.knownType = knownType; this.variableMap = variableMap; } public void setName(String name) { this.name = name; } public void setStaticType(Class knownType) { this.knownType = knownType; } public String getName() { return name; } public Class getType() { return knownType; } public void setValue(Object value) { if (knownType != null && value != null && value.getClass() != knownType) { if (!canConvert(knownType, value.getClass())) { throw new CompileException("cannot assign " + value.getClass().getName() + " to type: " + knownType.getName()); } try { value = convert(value, knownType); } catch (Exception e) { throw new CompileException("cannot convert value of " + value.getClass().getName() + " to: " + knownType.getName()); } } ((Receiver) variableMap.get(name)).receiver = value; } public Object getValue() { return ((Receiver) variableMap.get(name)).receiver; } public int getFlags() { return 0; } } public class InvokationContextFactory extends MapVariableResolverFactory { private VariableResolverFactory protoContext; public InvokationContextFactory(VariableResolverFactory next, VariableResolverFactory protoContext) { this.nextFactory = next; this.protoContext = protoContext; } @Override public VariableResolver createVariable(String name, Object value) { if (isResolveable(name) && !protoContext.isResolveable(name)) { return nextFactory.createVariable(name, value); } else { return protoContext.createVariable(name, value); } } @Override public VariableResolver createVariable(String name, Object value, Class type) { if (isResolveable(name) && !protoContext.isResolveable(name)) { return nextFactory.createVariable(name, value, type); } else { return protoContext.createVariable(name, value, type); } } @Override public VariableResolver getVariableResolver(String name) { if (isResolveable(name) && !protoContext.isResolveable(name)) { return nextFactory.getVariableResolver(name); } else { return protoContext.getVariableResolver(name); } } @Override public boolean isTarget(String name) { return protoContext.isTarget(name); } @Override public boolean isResolveable(String name) { return protoContext.isResolveable(name) || nextFactory.isResolveable(name); } @Override public boolean isIndexedFactory() { return true; } } public void setCursorPosition(int start, int end) { this.cursorStart = start; this.cursorEnd = end; } public int getCursorStart() { return cursorStart; } public int getCursorEnd() { return cursorEnd; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ast/ProtoVarNode.java0000644000175000017500000000600211253516374023671 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.ast; import static org.mvel2.MVEL.eval; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import static org.mvel2.util.ParseTools.*; /** * @author Christopher Brock */ public class ProtoVarNode extends ASTNode implements Assignment { private String name; private char[] stmt; private ExecutableStatement statement; public ProtoVarNode(String name, Proto type) { this.name = name; this.egressType = Proto.ProtoInstance.class; } public ProtoVarNode(char[] expr, int fields, Proto type, ParserContext pCtx) { this.egressType = Proto.ProtoInstance.class; this.fields = fields; int assignStart; if ((assignStart = find(super.name = expr, '=')) != -1) { checkNameSafety(name = createStringTrimmed(expr, 0, assignStart)); if (((fields |= ASSIGN) & COMPILE_IMMEDIATE) != 0) { statement = (ExecutableStatement) subCompileExpression(stmt = subset(expr, assignStart + 1), pCtx); } else { stmt = subset(expr, assignStart + 1); } } else { checkNameSafety(name = new String(expr)); } if ((fields & COMPILE_IMMEDIATE) != 0) { pCtx.addVariable(name, egressType, true); } } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { if (statement == null) statement = (ExecutableStatement) subCompileExpression(stmt); factory.createVariable(name, ctx = statement.getValue(ctx, thisValue, factory), egressType); return ctx; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { factory.createVariable(name, ctx = eval(stmt, thisValue, factory), egressType); return ctx; } public String getName() { return name; } public String getAssignmentVar() { return name; } public char[] getExpression() { return stmt; } public boolean isNewDeclaration() { return true; } public void setValueStatement(ExecutableStatement stmt) { this.statement = stmt; } }mvel-2.0.18.orig/src/main/java/org/mvel2/PreProcessor.java0000644000175000017500000000160611100376377023151 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; /** * A preprocessor used for pre-processing any expressions before being parsed/compiled. */ public interface PreProcessor { public char[] parse(char[] input); public String parse(String input); } mvel-2.0.18.orig/src/main/java/org/mvel2/Unit.java0000644000175000017500000000146011077457613021446 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; public interface Unit extends ConversionHandler { public double getValue(); public void setValue(double value); } mvel-2.0.18.orig/src/main/java/org/mvel2/Operator.java0000644000175000017500000001143011252763061022310 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; /** * Contains a list of constants representing internal operators. */ public interface Operator { public static final int NOOP = -1; /** * The index positions of the operator precedence values * correspond to the actual operator itself. So ADD is PTABLE[0], * SUB is PTABLE[1] and so on. */ public static final int[] PTABLE = { 10, // ADD 10, // SUB 11, // MULT 11, // DIV 11, // MOD 12, // POWER 6, // BW_AND 4, // BW_OR 5, // BW_XOR 9, // BW_SHIFT_RIGHT 9, // BW_SHIFT_LEFT 9, // BW_USHIFT_LEFT 5, // BW_NOT 8, // LTHAN 8, // GTHAN 8, // LETHAN 8, // GETHAN 7, // EQUAL 7, // NEQUAL 13, // STR_APPEND 3, // AND 2, // OR 2, // CHOR 13, // REGEX 8, // INSTANCEOF 13, // CONTAINS 13, // SOUNDEX 13, // SIMILARITY 0, // TERNARY 0, // TERNARY ELSE 13, // ASSIGN 13, // INC_ASSIGN 13 // DEC ASSIGN }; public static final int ADD = 0; public static final int SUB = 1; public static final int MULT = 2; public static final int DIV = 3; public static final int MOD = 4; public static final int POWER = 5; public static final int BW_AND = 6; public static final int BW_OR = 7; public static final int BW_XOR = 8; public static final int BW_SHIFT_RIGHT = 9; public static final int BW_SHIFT_LEFT = 10; public static final int BW_USHIFT_RIGHT = 11; public static final int BW_USHIFT_LEFT = 12; public static final int BW_NOT = 13; public static final int LTHAN = 14; public static final int GTHAN = 15; public static final int LETHAN = 16; public static final int GETHAN = 17; public static final int EQUAL = 18; public static final int NEQUAL = 19; public static final int STR_APPEND = 20; public static final int AND = 21; public static final int OR = 22; public static final int CHOR = 23; public static final int REGEX = 24; public static final int INSTANCEOF = 25; public static final int CONTAINS = 26; public static final int SOUNDEX = 27; public static final int SIMILARITY = 28; public static final int TERNARY = 29; public static final int TERNARY_ELSE = 30; public static final int ASSIGN = 31; public static final int INC_ASSIGN = 32; public static final int DEC_ASSIGN = 33; public static final int NEW = 34; public static final int PROJECTION = 35; public static final int CONVERTABLE_TO = 36; public static final int END_OF_STMT = 37; public static final int FOREACH = 38; public static final int IF = 39; public static final int ELSE = 40; public static final int WHILE = 41; public static final int UNTIL = 42; public static final int FOR = 43; public static final int SWITCH = 44; public static final int DO = 45; public static final int WITH = 46; public static final int ISDEF = 47; public static final int PROTO = 48; public static final int INC = 50; public static final int DEC = 51; public static final int ASSIGN_ADD = 52; public static final int ASSIGN_SUB = 53; public static final int ASSIGN_STR_APPEND = 54; public static final int ASSIGN_DIV = 55; public static final int ASSIGN_MOD = 56; public static final int ASSIGN_OR = 57; public static final int ASSIGN_AND = 58; public static final int ASSIGN_XOR = 59; public static final int ASSIGN_LSHIFT = 60; public static final int ASSIGN_RSHIFT = 61; public static final int ASSIGN_RUSHIFT = 62; public static final int IMPORT_STATIC = 95; public static final int IMPORT = 96; public static final int ASSERT = 97; public static final int UNTYPED_VAR = 98; public static final int RETURN = 99; public static final int FUNCTION = 100; } mvel-2.0.18.orig/src/main/java/org/mvel2/Macro.java0000644000175000017500000000145411077457613021573 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; /** * @author Christopher Brock */ public interface Macro { public String doMacro(); } mvel-2.0.18.orig/src/main/java/org/mvel2/UnresolveablePropertyException.java0000644000175000017500000000271111077457613026761 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import org.mvel2.ast.ASTNode; /** * @author Christopher Brock */ public class UnresolveablePropertyException extends RuntimeException { private String name; public UnresolveablePropertyException(ASTNode astNode, Throwable throwable) { super("unable to resolve token: " + astNode.getName(), throwable); this.name = astNode.getName(); } public UnresolveablePropertyException(ASTNode astNode) { super("unable to resolve token: " + astNode.getName()); this.name = astNode.getName(); } public UnresolveablePropertyException(String name) { super("unable to resolve token: " + name); this.name = name; } public String getName() { return name; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/0000755000175000017500000000000011412747053021652 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/templates/TemplateRuntime.java0000644000175000017500000002751711317165145025650 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.templates.res.Node; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.templates.util.TemplateTools; import org.mvel2.templates.util.io.StandardOutputStream; import org.mvel2.templates.util.io.StringAppenderStream; import org.mvel2.util.StringAppender; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import static org.mvel2.templates.TemplateCompiler.compileTemplate; /** * This is the root of the template runtime, and contains various utility methods for executing templates. */ public class TemplateRuntime { private char[] template; private TemplateRegistry namedTemplateRegistry; private Node rootNode; public TemplateRuntime(char[] template, TemplateRegistry namedTemplateRegistry, Node rootNode) { this.template = template; this.namedTemplateRegistry = namedTemplateRegistry; this.rootNode = rootNode; } public static Object eval(File file, Object ctx, VariableResolverFactory vars, TemplateRegistry registry) { return execute(compileTemplate(TemplateTools.readInFile(file)), ctx, vars, registry); } public static Object eval(InputStream instream) { return eval(instream, null, (VariableResolverFactory) null, null); } public static Object eval(InputStream instream, Object ctx) { return eval(instream, ctx, (VariableResolverFactory) null, null); } public static Object eval(InputStream instream, Object ctx, VariableResolverFactory vars) { return eval(instream, ctx, vars); } public static Object eval(InputStream instream, Object ctx, Map vars) { return eval(instream, ctx, new MapVariableResolverFactory(vars), null); } public static Object eval(InputStream instream, Object ctx, Map vars, TemplateRegistry registry) { return execute(compileTemplate(TemplateTools.readStream(instream)), ctx, new MapVariableResolverFactory(vars), registry); } public static Object eval(InputStream instream, Object ctx, VariableResolverFactory vars, TemplateRegistry registry) { return execute(compileTemplate(TemplateTools.readStream(instream)), ctx, vars, registry); } public static void eval(InputStream instream, Object ctx, VariableResolverFactory vars, TemplateRegistry register, OutputStream stream) { execute(compileTemplate(TemplateTools.readStream(instream)), ctx, vars, register, stream); } public static Object eval(String template, Map vars) { return execute(compileTemplate(template), null, new MapVariableResolverFactory(vars)); } public static void eval(String template, Map vars, OutputStream stream) { execute(compileTemplate(template), null, new MapVariableResolverFactory(vars), null, stream); } public static Object eval(String template, Object ctx) { return execute(compileTemplate(template), ctx); } public static Object eval(String template, Object ctx, Map vars) { return execute(compileTemplate(template), ctx, new MapVariableResolverFactory(vars)); } public static void eval(String template, Object ctx, Map vars, OutputStream stream) { execute(compileTemplate(template), ctx, new MapVariableResolverFactory(vars), null, stream); } public static Object eval(String template, Object ctx, VariableResolverFactory vars) { return execute(compileTemplate(template), ctx, vars); } public static void eval(String template, Object ctx, VariableResolverFactory vars, TemplateOutputStream stream) { execute(compileTemplate(template), ctx, vars, null, stream); } public static void eval(String template, Object ctx, VariableResolverFactory vars, OutputStream stream) { execute(compileTemplate(template), ctx, vars, null, stream); } public static Object eval(String template, Map vars, TemplateRegistry registry) { return execute(compileTemplate(template), null, new MapVariableResolverFactory(vars), registry); } public static void eval(String template, Map vars, TemplateRegistry registry, TemplateOutputStream stream) { execute(compileTemplate(template), null, new MapVariableResolverFactory(vars), registry, stream); } public static void eval(String template, Map vars, TemplateRegistry registry, OutputStream stream) { execute(compileTemplate(template), null, new MapVariableResolverFactory(vars), registry, stream); } public static Object eval(String template, Object ctx, Map vars, TemplateRegistry registry) { return execute(compileTemplate(template), ctx, new MapVariableResolverFactory(vars), registry); } public static void eval(String template, Object ctx, Map vars, TemplateRegistry registry, OutputStream stream) { execute(compileTemplate(template), ctx, new MapVariableResolverFactory(vars), registry, stream); } public static Object eval(String template, Object ctx, VariableResolverFactory vars, TemplateRegistry registry) { return execute(compileTemplate(template), ctx, vars, registry); } public static void eval(String template, Object ctx, VariableResolverFactory vars, TemplateRegistry registry, OutputStream stream) { execute(compileTemplate(template), ctx, vars, registry, stream); } public static void eval(String template, Object ctx, VariableResolverFactory vars, TemplateRegistry registry, TemplateOutputStream stream) { execute(compileTemplate(template), ctx, vars, registry, stream); } public static Object execute(CompiledTemplate compiled) { return execute(compiled.getRoot(), compiled.getTemplate(), new StringAppender(), null, null, null); } public static void execute(CompiledTemplate compiled, OutputStream stream) { execute(compiled.getRoot(), compiled.getTemplate(), new StandardOutputStream(stream), null, null, null); } public static Object execute(CompiledTemplate compiled, Object context) { return execute(compiled.getRoot(), compiled.getTemplate(), new StringAppender(), context, null, null); } public static void execute(CompiledTemplate compiled, Object context, OutputStream stream) { execute(compiled.getRoot(), compiled.getTemplate(), new StandardOutputStream(stream), context, null, null); } public static Object execute(CompiledTemplate compiled, Map vars) { return execute(compiled.getRoot(), compiled.getTemplate(), new StringAppender(), null, new MapVariableResolverFactory(vars), null); } public static void execute(CompiledTemplate compiled, Map vars, OutputStream stream) { execute(compiled.getRoot(), compiled.getTemplate(), new StandardOutputStream(stream), null, new MapVariableResolverFactory(vars), null); } public static Object execute(CompiledTemplate compiled, Object context, Map vars) { return execute(compiled.getRoot(), compiled.getTemplate(), new StringAppender(), context, new MapVariableResolverFactory(vars), null); } public static void execute(CompiledTemplate compiled, Object context, Map vars, OutputStream stream) { execute(compiled.getRoot(), compiled.getTemplate(), new StandardOutputStream(stream), context, new MapVariableResolverFactory(vars), null); } public static Object execute(CompiledTemplate compiled, Object context, TemplateRegistry registry) { return execute(compiled.getRoot(), compiled.getTemplate(), new StringAppender(), context, null, registry); } public static void execute(CompiledTemplate compiled, Object context, TemplateRegistry registry, OutputStream stream) { execute(compiled.getRoot(), compiled.getTemplate(), new StandardOutputStream(stream), context, null, registry); } public static Object execute(CompiledTemplate compiled, Object context, Map vars, TemplateRegistry registry) { return execute(compiled.getRoot(), compiled.getTemplate(), new StringAppender(), context, new MapVariableResolverFactory(vars), registry); } public static void execute(CompiledTemplate compiled, Object context, Map vars, TemplateRegistry registry, OutputStream stream) { execute(compiled.getRoot(), compiled.getTemplate(), new StandardOutputStream(stream), context, new MapVariableResolverFactory(vars), registry); } public static Object execute(CompiledTemplate compiled, Object context, VariableResolverFactory factory) { return execute(compiled.getRoot(), compiled.getTemplate(), new StringAppender(), context, factory, null); } public static void execute(CompiledTemplate compiled, Object context, VariableResolverFactory factory, OutputStream stream) { execute(compiled.getRoot(), compiled.getTemplate(), new StandardOutputStream(stream), context, factory, null); } public static Object execute(CompiledTemplate compiled, Object context, VariableResolverFactory factory, TemplateRegistry registry) { return execute(compiled.getRoot(), compiled.getTemplate(), new StringAppender(), context, factory, registry); } public static Object execute(CompiledTemplate compiled, Object context, VariableResolverFactory factory, TemplateRegistry registry, OutputStream stream) { return execute(compiled.getRoot(), compiled.getTemplate(), new StandardOutputStream(stream), context, factory, registry); } public static Object execute(CompiledTemplate compiled, Object context, VariableResolverFactory factory, TemplateRegistry registry, TemplateOutputStream stream) { return execute(compiled.getRoot(), compiled.getTemplate(), stream, context, factory, registry); } public static Object execute(Node root, char[] template, StringAppender appender, Object context, VariableResolverFactory factory, TemplateRegistry registry) { return new TemplateRuntime(template, registry, root).execute(appender, context, factory); } public static Object execute(Node root, char[] template, TemplateOutputStream appender, Object context, VariableResolverFactory factory, TemplateRegistry registry) { return new TemplateRuntime(template, registry, root).execute(appender, context, factory); } public Object execute(StringAppender appender, Object context, VariableResolverFactory factory) { return execute(new StringAppenderStream(appender), context, factory); } public Object execute(TemplateOutputStream stream, Object context, VariableResolverFactory factory) { return rootNode.eval(this, stream, context, factory); } public Node getRootNode() { return rootNode; } public void setRootNode(Node rootNode) { this.rootNode = rootNode; } public char[] getTemplate() { return template; } public void setTemplate(char[] template) { this.template = template; } public TemplateRegistry getNamedTemplateRegistry() { return namedTemplateRegistry; } public void setNamedTemplateRegistry(TemplateRegistry namedTemplateRegistry) { this.namedTemplateRegistry = namedTemplateRegistry; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/SimpleTemplateRegistry.java0000644000175000017500000000310511077457613027201 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class SimpleTemplateRegistry implements TemplateRegistry { private Map NAMED_TEMPLATES = new HashMap(); public void addNamedTemplate(String name, CompiledTemplate template) { NAMED_TEMPLATES.put(name, template); } public CompiledTemplate getNamedTemplate(String name) { CompiledTemplate t = NAMED_TEMPLATES.get(name); if (t == null) throw new TemplateError("no named template exists '" + name + "'"); return t; } public Iterator iterator() { return NAMED_TEMPLATES.keySet().iterator(); } public Set getNames() { return NAMED_TEMPLATES.keySet(); } public boolean contains(String name) { return NAMED_TEMPLATES.containsKey(name); } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/TemplateDebug.java0000644000175000017500000000207511077457613025252 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; import org.mvel2.templates.res.Node; public class TemplateDebug { public static void decompile(CompiledTemplate t, char[] template) { int i = 1; for (Node n = t.getRoot(); n != null; n = n.getNext()) { System.out.println((i++) + "> " + n.toString() + "['" + new String(template, n.getBegin(), n.getEnd() - n.getBegin()) + "']"); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/CompiledTemplate.java0000644000175000017500000000240611312502302025730 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; import org.mvel2.templates.res.Node; import java.io.Serializable; public class CompiledTemplate implements Serializable { private char[] template; private Node root; public CompiledTemplate(char[] template, Node root) { this.template = template; this.root = root; } public char[] getTemplate() { return template; } public void setTemplate(char[] template) { this.template = template; } public Node getRoot() { return root; } public void setRoot(Node root) { this.root = root; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/TemplateRuntimeError.java0000644000175000017500000000257311077457613026664 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; public class TemplateRuntimeError extends RuntimeException { public TemplateRuntimeError() { super(); //To change body of overridden methods use File | Settings | File Templates. } public TemplateRuntimeError(String s) { super(s); //To change body of overridden methods use File | Settings | File Templates. } public TemplateRuntimeError(String s, Throwable throwable) { super(s, throwable); //To change body of overridden methods use File | Settings | File Templates. } public TemplateRuntimeError(Throwable throwable) { super(throwable); //To change body of overridden methods use File | Settings | File Templates. } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/TemplateSyntaxError.java0000644000175000017500000000256611077457613026531 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; public class TemplateSyntaxError extends RuntimeException { public TemplateSyntaxError() { super(); //To change body of overridden methods use File | Settings | File Templates. } public TemplateSyntaxError(String s) { super(s); //To change body of overridden methods use File | Settings | File Templates. } public TemplateSyntaxError(String s, Throwable throwable) { super(s, throwable); //To change body of overridden methods use File | Settings | File Templates. } public TemplateSyntaxError(Throwable throwable) { super(throwable); //To change body of overridden methods use File | Settings | File Templates. } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/TemplateCompiler.java0000644000175000017500000004355311317165145025775 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; import org.mvel2.CompileException; import org.mvel2.ParserContext; import org.mvel2.compiler.AbstractParser; import org.mvel2.templates.res.*; import org.mvel2.templates.util.TemplateTools; import org.mvel2.util.ExecutionStack; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.balancedCaptureWithLineAccounting; import static org.mvel2.util.ParseTools.subset; import java.io.File; import java.io.InputStream; import java.util.HashMap; import java.util.Map; /** * The TemplateCompiler class is used for pre-compiling MVEL Templates. To execute a compiled template see * {@link TemplateRuntime} * * @author Mike Brock */ @SuppressWarnings({"ManualArrayCopy"}) public class TemplateCompiler { private char[] template; private int length; private int start; private int cursor; private int lastTextRangeEnding; private int line; private int colStart; private boolean codeCache = false; private Map> customNodes; private static final Map OPCODES = new HashMap(); static { OPCODES.put("if", Opcodes.IF); OPCODES.put("else", Opcodes.ELSE); OPCODES.put("elseif", Opcodes.ELSE); OPCODES.put("end", Opcodes.END); OPCODES.put("foreach", Opcodes.FOREACH); OPCODES.put("includeNamed", Opcodes.INCLUDE_NAMED); OPCODES.put("include", Opcodes.INCLUDE_FILE); OPCODES.put("comment", Opcodes.COMMENT); OPCODES.put("code", Opcodes.CODE); OPCODES.put("eval", Opcodes.EVAL); OPCODES.put("declare", Opcodes.DECLARE); OPCODES.put("stop", Opcodes.STOP); } public CompiledTemplate compile() { return new CompiledTemplate(template, compileFrom(null, new ExecutionStack())); } public Node compileFrom(Node root, ExecutionStack stack) { line = 1; Node n = root; if (root == null) { n = root = new TextNode(0, 0); } IfNode last; Integer opcode; String name; int x; try { while (cursor < length) { switch (template[cursor]) { case '\n': line++; colStart = cursor + 1; break; case '@': case '$': if (isNext(template[cursor])) { start = ++cursor; (n = markTextNode(n)).setEnd(n.getEnd() + 1); lastTextRangeEnding = ++cursor; continue; } if ((x = captureOrbToken()) != -1) { start = x; switch ((opcode = OPCODES.get(name = new String(capture()))) == null ? 0 : opcode) { case Opcodes.IF: /** * Capture any residual text node, and push the if statement on the nesting stack. */ stack.push(n = markTextNode(n).next = codeCache ? new CompiledIfNode(start, name, template, captureOrbInternal(), start) : new IfNode(start, name, template, captureOrbInternal(), start)); n.setTerminus(new TerminalNode()); break; case Opcodes.ELSE: if (!stack.isEmpty() && stack.peek() instanceof IfNode) { markTextNode(n).next = (last = (IfNode) stack.pop()).getTerminus(); last.demarcate(last.getTerminus(), template); last.next = n = codeCache ? new CompiledIfNode(start, name, template, captureOrbInternal(), start) : new IfNode(start, name, template, captureOrbInternal(), start); n.setTerminus(last.getTerminus()); stack.push(n); } break; case Opcodes.FOREACH: stack.push( n = markTextNode(n).next = codeCache ? new CompiledForEachNode(start, name, template, captureOrbInternal(), start) : new ForEachNode(start, name, template, captureOrbInternal(), start) ); n.setTerminus(new TerminalNode()); break; case Opcodes.INCLUDE_FILE: n = markTextNode(n).next = codeCache ? new CompiledIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1) : new IncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1); break; case Opcodes.INCLUDE_NAMED: n = markTextNode(n).next = codeCache ? new CompiledNamedIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1) : new NamedIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1); break; case Opcodes.CODE: n = markTextNode(n) .next = codeCache ? new CompiledCodeNode(start, name, template, captureOrbInternal(), start = cursor + 1) : new CodeNode(start, name, template, captureOrbInternal(), start = cursor + 1); break; case Opcodes.EVAL: n = markTextNode(n).next = codeCache ? new CompiledEvalNode(start, name, template, captureOrbInternal(), start = cursor + 1) : new EvalNode(start, name, template, captureOrbInternal(), start = cursor + 1); break; case Opcodes.COMMENT: n = markTextNode(n) .next = new CommentNode(start, name, template, captureOrbInternal(), start = cursor + 1); break; case Opcodes.DECLARE: stack.push(n = markTextNode(n).next = codeCache ? new CompiledDeclareNode(start, name, template, captureOrbInternal(), start = cursor + 1) : new DeclareNode(start, name, template, captureOrbInternal(), start = cursor + 1)); n.setTerminus(new TerminalNode()); break; case Opcodes.END: n = markTextNode(n); Node end = (Node) stack.pop(); Node terminal = end.getTerminus(); terminal.setCStart(captureOrbInternal()); terminal.setEnd((lastTextRangeEnding = start) - 1); terminal.calculateContents(template); if (end.demarcate(terminal, template)) n = n.next = terminal; else n = terminal; break; default: if (name.length() == 0) { n = markTextNode(n).next = codeCache ? new CompiledExpressionNode(start, name, template, captureOrbInternal(), start = cursor + 1) : new ExpressionNode(start, name, template, captureOrbInternal(), start = cursor + 1); } else if (customNodes != null && customNodes.containsKey(name)) { Class customNode = customNodes.get(name); try { (n = markTextNode(n).next = (customNode.newInstance())).setBegin(start); n.setName(name); n.setCStart(captureOrbInternal()); n.setCEnd(start = cursor + 1); n.setEnd(n.getCEnd()); n.setContents(subset(template, n.getCStart(), n.getCEnd() - n.getCStart() - 1)); if (n.isOpenNode()) { stack.push(n); } } catch (InstantiationException e) { throw new RuntimeException("unable to instantiate custom node class: " + customNode.getName()); } catch (IllegalAccessException e) { throw new RuntimeException("unable to instantiate custom node class: " + customNode.getName()); } } else { throw new RuntimeException("unknown token type: " + name); } } } } cursor++; } } catch (RuntimeException e) { CompileException ce = new CompileException(e.getMessage(), e); ce.setExpr(template); if (e instanceof CompileException) { CompileException ce2 = (CompileException) e; if (ce2.getCursor() != -1) { ce.setCursor(ce2.getCursor()); if (ce2.getColumn() == -1) ce.setColumn(ce.getCursor() - colStart); else ce.setColumn(ce2.getColumn()); } } ce.setLineNumber(line); throw ce; } if (!stack.isEmpty()) { CompileException ce = new CompileException("unclosed @" + ((Node) stack.peek()).getName() + "{} block. expected @end{}", template, cursor); ce.setColumn(cursor - colStart); ce.setLineNumber(line); throw ce; } if (start < template.length) { n = n.next = new TextNode(start, template.length); } n.next = new EndNode(); n = root; do { if (n.getLength() != 0) { break; } } while ((n = n.getNext()) != null); if (n != null && n.getLength() == template.length - 1) { if (n instanceof ExpressionNode) { return codeCache ? new CompiledTerminalExpressionNode(n) : new TerminalExpressionNode(n); } else { return n; } } return root; } // Parse Utilities Start Here public boolean isNext(char c) { return cursor != length && template[cursor + 1] == c; } public int captureOrbToken() { int newStart = ++cursor; while ((cursor != length) && ParseTools.isIdentifierPart(template[cursor])) cursor++; if (cursor != length && template[cursor] == '{') return newStart; return -1; } public int captureOrbInternal() { try { ParserContext pCtx = new ParserContext(); cursor = balancedCaptureWithLineAccounting(template, start = cursor, '{', pCtx); line += pCtx.getLineCount(); int ret = start + 1; start = cursor + 1; return ret; } catch (CompileException e) { e.setLineNumber(line); e.setColumn((cursor - colStart) + 1); throw e; } } public char[] capture() { char[] newChar = new char[cursor - start]; for (int i = 0; i < newChar.length; i++) { newChar[i] = template[i + start]; } return newChar; } public Node markTextNode(Node n) { int s = (n.getEnd() > lastTextRangeEnding ? n.getEnd() : lastTextRangeEnding); if (s < start) { return n.next = new TextNode(s, lastTextRangeEnding = start - 1); } return n; } public static CompiledTemplate compileTemplate(String template) { return new TemplateCompiler(template, true).compile(); } public static CompiledTemplate compileTemplate(char[] template) { return new TemplateCompiler(template, true).compile(); } public static CompiledTemplate compileTemplate(CharSequence template) { return new TemplateCompiler(template, true).compile(); } public static CompiledTemplate compileTemplate(String template, Map> customNodes) { return new TemplateCompiler(template, customNodes, true).compile(); } public static CompiledTemplate compileTemplate(char[] template, Map> customNodes) { return new TemplateCompiler(template, customNodes, true).compile(); } public static CompiledTemplate compileTemplate(CharSequence template, Map> customNodes) { return new TemplateCompiler(template, customNodes, true).compile(); } public static CompiledTemplate compileTemplate(InputStream stream) { return compileTemplate(stream, null); } public static CompiledTemplate compileTemplate(InputStream stream, Map> customNodes) { return new TemplateCompiler(TemplateTools.readStream(stream), customNodes, true).compile(); } public static CompiledTemplate compileTemplate(File file) { return compileTemplate(file, null); } public static CompiledTemplate compileTemplate(File file, Map> customNodes) { return new TemplateCompiler(TemplateTools.readInFile(file), customNodes, true).compile(); } public TemplateCompiler(String template) { this.length = (this.template = template.toCharArray()).length; } public TemplateCompiler(char[] template) { this.length = (this.template = template).length; } public TemplateCompiler(String template, boolean codeCache) { this.length = (this.template = template.toCharArray()).length; this.codeCache = codeCache; } public TemplateCompiler(char[] template, boolean codeCache) { this.length = (this.template = template).length; this.codeCache = codeCache; } public TemplateCompiler(CharSequence sequence) { this.length = (this.template = sequence.toString().toCharArray()).length; } public TemplateCompiler(CharSequence sequence, boolean codeCache) { this.length = (this.template = sequence.toString().toCharArray()).length; this.codeCache = codeCache; } public TemplateCompiler(String template, Map> customNodes) { this.length = (this.template = template.toCharArray()).length; this.customNodes = customNodes; } public TemplateCompiler(char[] template, Map> customNodes) { this.length = (this.template = template).length; this.customNodes = customNodes; } public TemplateCompiler(CharSequence sequence, Map> customNodes) { this.length = (this.template = sequence.toString().toCharArray()).length; this.customNodes = customNodes; } public TemplateCompiler(String template, Map> customNodes, boolean codeCache) { this.length = (this.template = template.toCharArray()).length; this.customNodes = customNodes; this.codeCache = codeCache; } public TemplateCompiler(char[] template, Map> customNodes, boolean codeCache) { this.length = (this.template = template).length; this.customNodes = customNodes; this.codeCache = codeCache; } public TemplateCompiler(CharSequence sequence, Map> customNodes, boolean codeCache) { this.length = (this.template = sequence.toString().toCharArray()).length; this.customNodes = customNodes; this.codeCache = codeCache; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/0000755000175000017500000000000011412747053022443 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/IncludeNode.java0000644000175000017500000001016111317165145025476 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateError; import org.mvel2.templates.TemplateRuntime; import static org.mvel2.templates.util.TemplateTools.captureToEOS; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.ExecutionStack; import static org.mvel2.util.ParseTools.subset; import org.mvel2.util.StringAppender; import java.io.*; public class IncludeNode extends Node { private static final StackThreadLocal relativePathStack; private char[] includeExpression; private char[] preExpression; private static class StackThreadLocal extends ThreadLocal { protected T initialValue() { ExecutionStack stk = new ExecutionStack(); stk.push("."); return (T) stk; } } static { relativePathStack = new StackThreadLocal(); } public IncludeNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); int mark; this.includeExpression = subset(contents, 0, mark = captureToEOS(contents, 0)); if (mark != contents.length) this.preExpression = subset(contents, ++mark, contents.length - mark); } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { String file = MVEL.eval(includeExpression, ctx, factory, String.class); if (this.preExpression != null) { MVEL.eval(preExpression, ctx, factory); } if (next != null) { return next.eval(runtime, appender.append(String.valueOf(TemplateRuntime.eval(readInFile(file), ctx, factory))), ctx, factory); } else { return appender.append(String.valueOf(MVEL.eval(readInFile(file), ctx, factory))); } } public boolean demarcate(Node terminatingNode, char[] template) { return false; } private static Object peek() { return relativePathStack.get().peek(); } public static Object pop() { return relativePathStack.get().pop(); } private static void push(String path) { relativePathStack.get().push(path); } public static String readInFile(String fileName) { File file = new File(String.valueOf(peek()) + "/" + fileName); try { FileInputStream instream = new FileInputStream(file); BufferedInputStream bufstream = new BufferedInputStream(instream); push(file.getParent()); byte[] buf = new byte[10]; int read; int i; StringAppender appender = new StringAppender(); while ((read = bufstream.read(buf)) != -1) { for (i = 0; i < read; i++) { appender.append((char) buf[i]); } } bufstream.close(); instream.close(); pop(); return appender.toString(); } catch (FileNotFoundException e) { throw new TemplateError("cannot include template '" + fileName + "': file not found."); } catch (IOException e) { throw new TemplateError("unknown I/O exception while including '" + fileName + "' (stacktrace nested)", e); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/IfNode.java0000644000175000017500000000401211317165145024447 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.PrintWriter; public class IfNode extends Node { protected Node trueNode; protected Node elseNode; public IfNode(int begin, String name, char[] template, int start, int end) { super(begin, name, template, start, end); } public Node getTrueNode() { return trueNode; } public void setTrueNode(ExpressionNode trueNode) { this.trueNode = trueNode; } public Node getElseNode() { return elseNode; } public void setElseNode(ExpressionNode elseNode) { this.elseNode = elseNode; } public boolean demarcate(Node terminatingNode, char[] template) { trueNode = next; next = terminus; return true; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { if (contents.length == 0 || MVEL.eval(contents, ctx, factory, Boolean.class)) { return trueNode.eval(runtime, appender, ctx, factory); } return next != null ? next.eval(runtime, appender, ctx, factory) : null; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/TextNode.java0000644000175000017500000000347011164527565025054 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.PrintWriter; public class TextNode extends Node { public TextNode(int begin, int end) { this.begin = begin; this.end = end; } public TextNode(int begin, int end, ExpressionNode next) { this.begin = begin; this.end = end; this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { int len = end - begin; if (len != 0) { appender.append(new String(runtime.getTemplate(), begin, len)); } return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public String toString() { return "TextNode(" + begin + "," + end + ")"; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } public void calculateContents(char[] template) { } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledIncludeNode.java0000644000175000017500000001176111317165145027162 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.CompiledTemplate; import org.mvel2.templates.TemplateCompiler; import org.mvel2.templates.TemplateError; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.ExecutionStack; import org.mvel2.util.StringAppender; import java.io.*; import static org.mvel2.templates.util.TemplateTools.captureToEOS; import static org.mvel2.util.ParseTools.subset; public class CompiledIncludeNode extends Node { private static final StackThreadLocal relativePathStack; private char[] includeExpression; private char[] preExpression; private Serializable cIncludeExpression; private Serializable cPreExpression; private long fileDateStamp; private CompiledTemplate cFileCache; private static class StackThreadLocal extends ThreadLocal { protected T initialValue() { ExecutionStack stk = new ExecutionStack(); stk.push("."); return (T) stk; } } static { relativePathStack = new StackThreadLocal(); } public CompiledIncludeNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); int mark; cIncludeExpression = MVEL.compileExpression(this.includeExpression = subset(contents, 0, mark = captureToEOS(contents, 0))); if (mark != contents.length) cPreExpression = MVEL.compileExpression(this.preExpression = subset(contents, ++mark, contents.length - mark)); } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { String file = MVEL.executeExpression(cIncludeExpression, ctx, factory, String.class); if (this.cPreExpression != null) { MVEL.executeExpression(cPreExpression, ctx, factory); } if (next != null) { return next.eval(runtime, appender.append(String.valueOf(TemplateRuntime.eval(readFile(file, ctx, factory), ctx, factory))), ctx, factory); } else { return appender.append(String.valueOf(MVEL.eval(readFile(file, ctx, factory), ctx, factory))); } } private String readFile(String fileName, Object ctx, VariableResolverFactory factory) { File file = getFile(fileName); if (fileDateStamp == 0 || fileDateStamp != file.lastModified()) { fileDateStamp = file.lastModified(); cFileCache = TemplateCompiler.compileTemplate(readInFile(file)); } return String.valueOf(TemplateRuntime.execute(cFileCache, ctx, factory)); } public boolean demarcate(Node terminatingNode, char[] template) { return false; } private static Object peek() { return relativePathStack.get().peek(); } public static Object pop() { return relativePathStack.get().pop(); } private static void push(String path) { relativePathStack.get().push(path); } public static File getFile(String fileName) { return new File(String.valueOf(peek()) + "/" + fileName); } public static String readInFile(File file) { try { FileInputStream instream = new FileInputStream(file); BufferedInputStream bufstream = new BufferedInputStream(instream); push(file.getParent()); byte[] buf = new byte[10]; int read; int i; StringAppender appender = new StringAppender(); while ((read = bufstream.read(buf)) != -1) { for (i = 0; i < read; i++) { appender.append((char) buf[i]); } } bufstream.close(); instream.close(); pop(); return appender.toString(); } catch (FileNotFoundException e) { throw new TemplateError("cannot include template '" + file.getPath() + "': file not found."); } catch (IOException e) { throw new TemplateError("unknown I/O exception while including '" + file.getPath() + "' (stacktrace nested)", e); } } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/ExpressionNode.java0000644000175000017500000000435311317165145026260 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import static org.mvel2.util.ParseTools.subset; import org.mvel2.util.StringAppender; import static java.lang.String.valueOf; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; public class ExpressionNode extends Node { public ExpressionNode() { } public ExpressionNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); } public ExpressionNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { appender.append(valueOf(MVEL.eval(contents, ctx, factory))); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } public String toString() { return "ExpressionNode:" + name + "{" + (contents == null ? "" : new String(contents)) + "} (start=" + begin + ";end=" + end + ")"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledDeclareNode.java0000644000175000017500000000434011317165145027131 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.CompiledTemplate; import org.mvel2.templates.SimpleTemplateRegistry; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import java.io.Serializable; import static org.mvel2.util.ParseTools.subset; public class CompiledDeclareNode extends Node { private Node nestedNode; private Serializable ce; public CompiledDeclareNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { if (runtime.getNamedTemplateRegistry() == null) { runtime.setNamedTemplateRegistry(new SimpleTemplateRegistry()); } runtime.getNamedTemplateRegistry() .addNamedTemplate(MVEL.executeExpression(ce, ctx, factory, String.class), new CompiledTemplate(runtime.getTemplate(), nestedNode)); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { Node n = nestedNode = next; while (n.getNext() != null) n = n.next; n.next = new EndNode(); next = terminus; return false; } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledEvalNode.java0000644000175000017500000000452011317165145026461 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.compiler.CompiledExpression; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import java.io.Serializable; import static java.lang.String.valueOf; import static org.mvel2.util.ParseTools.subset; public class CompiledEvalNode extends Node { private Serializable ce; public CompiledEvalNode() { } public CompiledEvalNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); } public CompiledEvalNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { appender.append(String.valueOf(TemplateRuntime.eval(valueOf(MVEL.executeExpression(ce, ctx, factory)), ctx, factory))); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } public String toString() { return "EvalNode:" + name + "{" + (contents == null ? "" : new String(contents)) + "} (start=" + begin + ";end=" + end + ")"; } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/Node.java0000644000175000017500000000654311164527565024213 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import static org.mvel2.util.ParseTools.subset; import org.mvel2.util.StringAppender; import java.io.Serializable; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; public abstract class Node implements Serializable { protected String name; protected char[] contents; protected int begin; protected int cStart; protected int cEnd; protected int end; public Node next; protected Node terminus; public Node() { } public Node(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); } public Node(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); this.next = next; } public abstract Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory); public String getName() { return name; } public void setName(String name) { this.name = name; } public char[] getContents() { return contents; } public void setContents(char[] contents) { this.contents = contents; } public int getBegin() { return begin; } public void setBegin(int begin) { this.begin = begin; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public int getCStart() { return cStart; } public void setCStart(int cStart) { this.cStart = cStart; } public int getCEnd() { return cEnd; } public void setCEnd(int cEnd) { this.cEnd = cEnd; } public boolean isOpenNode() { return false; } public abstract boolean demarcate(Node terminatingNode, char[] template); public Node getNext() { return next; } public Node setNext(Node next) { return this.next = next; } public Node getTerminus() { return terminus; } public void setTerminus(Node terminus) { this.terminus = terminus; } public void calculateContents(char[] template) { this.contents = subset(template, cStart, end - cStart); } public int getLength() { return this.end - this.begin; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledForEachNode.java0000644000175000017500000001250411317165145027102 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.TemplateRuntimeError; import org.mvel2.templates.util.ArrayIterator; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.ParseTools; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class CompiledForEachNode extends Node { public Node nestedNode; private Serializable[] ce; private String[] item; private String[] expression; private char[] sepExpr; private Serializable cSepExpr; public CompiledForEachNode() { } public CompiledForEachNode(int begin, String name, char[] template, int start, int end) { super(begin, name, template, start, end); configure(); } public Node getNestedNode() { return nestedNode; } public void setNestedNode(Node nestedNode) { this.nestedNode = nestedNode; } public boolean demarcate(Node terminatingnode, char[] template) { nestedNode = next; next = terminus; sepExpr = terminatingnode.getContents(); if (sepExpr.length == 0) { sepExpr = null; } else { cSepExpr = MVEL.compileExpression(sepExpr); } return false; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { Iterator[] iters = new Iterator[item.length]; Object o; for (int i = 0; i < iters.length; i++) { if ((o = MVEL.executeExpression(ce[i], ctx, factory)) instanceof Iterable) { iters[i] = ((Iterable) o).iterator(); } else if (o instanceof Object[]) { iters[i] = new ArrayIterator((Object[]) o); } else { throw new TemplateRuntimeError("cannot iterate object type: " + o.getClass().getName()); } } Map locals = new HashMap(); MapVariableResolverFactory localFactory = new MapVariableResolverFactory(locals, factory); int iterate = iters.length; while (true) { for (int i = 0; i < iters.length; i++) { if (!iters[i].hasNext()) { iterate--; locals.put(item[i], ""); } else { locals.put(item[i], iters[i].next()); } } if (iterate != 0) { nestedNode.eval(runtime, appender, ctx, localFactory); if (sepExpr != null) { for (Iterator it : iters) { if (it.hasNext()) { appender.append(String.valueOf(MVEL.executeExpression(cSepExpr, ctx, factory))); break; } } } } else break; } return next != null ? next.eval(runtime, appender, ctx, factory) : null; } private void configure() { ArrayList items = new ArrayList(); ArrayList expr = new ArrayList(); int start = 0; for (int i = 0; i < contents.length; i++) { switch (contents[i]) { case ':': items.add(ParseTools.createStringTrimmed(contents, start, i - start)); start = i + 1; break; case ',': if (expr.size() != (items.size() - 1)) { throw new CompileException("unexpected character ',' in foreach tag", cStart + i); } expr.add(ParseTools.createStringTrimmed(contents, start, i - start)); start = i + 1; break; } } if (start < contents.length) { if (expr.size() != (items.size() - 1)) { throw new CompileException("expected character ':' in foreach tag", cEnd); } expr.add(ParseTools.createStringTrimmed(contents, start, contents.length - start)); } item = new String[items.size()]; int i = 0; for (String s : items) item[i++] = s; ce = new Serializable[(expression = new String[expr.size()]).length]; i = 0; for (String s : expr) { ce[i] = MVEL.compileExpression(expression[i++] = s); } } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/EndNode.java0000644000175000017500000000251011164527565024630 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; public class EndNode extends Node { public Object eval(TemplateRuntime runtie, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { return appender.toString(); } public String toString() { return "EndNode"; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CodeNode.java0000644000175000017500000000421311164527565024776 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import static org.mvel2.util.ParseTools.subset; import org.mvel2.util.StringAppender; import java.io.PrintWriter; import java.io.PrintStream; import java.io.OutputStream; public class CodeNode extends Node { public CodeNode() { } public CodeNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); } public CodeNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { MVEL.eval(contents, ctx, factory); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } public String toString() { return "CodeNode:" + name + "{" + (contents == null ? "" : new String(contents)) + "} (start=" + begin + ";end=" + end + ")"; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledExpressionNode.java0000644000175000017500000000426311317165145027735 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import java.io.Serializable; import static java.lang.String.valueOf; import static org.mvel2.util.ParseTools.subset; public class CompiledExpressionNode extends ExpressionNode { private Serializable ce; public CompiledExpressionNode() { } public CompiledExpressionNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); } public CompiledExpressionNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { appender.append(valueOf(MVEL.executeExpression(ce, ctx, factory))); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public String toString() { return "ExpressionNode:" + name + "{" + (contents == null ? "" : new String(contents)) + "} (start=" + begin + ";end=" + end + ")"; } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/TerminalNode.java0000644000175000017500000000265211164527565025704 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.PrintWriter; public class TerminalNode extends Node { public TerminalNode() { } public TerminalNode(int begin, int end) { this.begin = begin; this.end = end; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/EvalNode.java0000644000175000017500000000420511312023501024764 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import static java.lang.String.valueOf; import static org.mvel2.util.ParseTools.subset; public class EvalNode extends Node { public EvalNode() { } public EvalNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); } public EvalNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { appender.append(String.valueOf(TemplateRuntime.eval(valueOf(MVEL.eval(contents, ctx, factory)), ctx, factory))); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } public String toString() { return "EvalNode:" + name + "{" + (contents == null ? "" : new String(contents)) + "} (start=" + begin + ";end=" + end + ")"; } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/Opcodes.java0000644000175000017500000000214211312023501024661 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; public interface Opcodes { public static int IF = 1; public static int ELSE = 2; public static int FOREACH = 3; public static int END = 10; public static int INCLUDE_FILE = 50; public static int INCLUDE_NAMED = 51; public static int COMMENT = 52; public static int CODE = 53; public static int EVAL = 55; public static int DECLARE = 54; public static int STOP = 70; } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/NamedIncludeNode.java0000644000175000017500000000475111164527565026463 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import static org.mvel2.templates.util.TemplateTools.captureToEOS; import org.mvel2.templates.util.TemplateOutputStream; import static org.mvel2.util.ParseTools.subset; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.PrintWriter; public class NamedIncludeNode extends Node { private char[] includeExpression; private char[] preExpression; public NamedIncludeNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); int mark; this.includeExpression = subset(contents, 0, mark = captureToEOS(contents, 0)); if (mark != contents.length) this.preExpression = subset(contents, ++mark, contents.length - mark); } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { if (preExpression != null) { MVEL.eval(preExpression, ctx, factory); } if (next != null) { return next.eval(runtime, appender.append(String.valueOf(TemplateRuntime.execute(runtime.getNamedTemplateRegistry().getNamedTemplate(MVEL.eval(includeExpression, ctx, factory, String.class)), ctx, factory))), ctx, factory); } else { return appender.append(String.valueOf(TemplateRuntime.execute(runtime.getNamedTemplateRegistry().getNamedTemplate(MVEL.eval(includeExpression, ctx, factory, String.class)), ctx, factory))); } } public boolean demarcate(Node terminatingNode, char[] template) { return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledCodeNode.java0000644000175000017500000000425411317165145026450 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import java.io.Serializable; import static org.mvel2.util.ParseTools.subset; public class CompiledCodeNode extends Node { private Serializable ce; public CompiledCodeNode() { } public CompiledCodeNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); } public CompiledCodeNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { MVEL.executeExpression(ce, ctx, factory); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } public String toString() { return "CodeNode:" + name + "{" + (contents == null ? "" : new String(contents)) + "} (start=" + begin + ";end=" + end + ")"; } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CommentNode.java0000644000175000017500000000334711164527565025535 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; public class CommentNode extends Node { public CommentNode() { } public CommentNode(int begin, String name, char[] template, int start, int end) { this.name = name; this.end = this.cEnd = end; } public CommentNode(int begin, String name, char[] template, int start, int end, Node next) { this.begin = begin; this.end = this.cEnd = end; this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { if (next != null) return next.eval(runtime, appender, ctx, factory); else return null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/DeclareNode.java0000644000175000017500000000435511164527565025472 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.CompiledTemplate; import org.mvel2.templates.SimpleTemplateRegistry; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import static org.mvel2.util.ParseTools.subset; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; public class DeclareNode extends Node { private Node nestedNode; public DeclareNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { if (runtime.getNamedTemplateRegistry() == null) { runtime.setNamedTemplateRegistry(new SimpleTemplateRegistry()); } runtime.getNamedTemplateRegistry() .addNamedTemplate(MVEL.eval(contents, ctx, factory, String.class), new CompiledTemplate(runtime.getTemplate(), nestedNode)); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { Node n = nestedNode = next; while (n.getNext() != null) n = n.next; n.next = new EndNode(); next = terminus; return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/ForEachNode.java0000644000175000017500000001200511164527565025431 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.TemplateRuntimeError; import org.mvel2.templates.util.ArrayIterator; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.ParseTools; import org.mvel2.util.StringAppender; import java.util.*; import java.io.PrintStream; import java.io.PrintWriter; public class ForEachNode extends Node { public Node nestedNode; private String[] item; private String[] expression; private char[] sepExpr; public ForEachNode() { } public ForEachNode(int begin, String name, char[] template, int start, int end) { super(begin, name, template, start, end); configure(); } public Node getNestedNode() { return nestedNode; } public void setNestedNode(Node nestedNode) { this.nestedNode = nestedNode; } public boolean demarcate(Node terminatingnode, char[] template) { nestedNode = next; next = terminus; sepExpr = terminatingnode.getContents(); if (sepExpr.length == 0) sepExpr = null; return false; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { Iterator[] iters = new Iterator[item.length]; Object o; for (int i = 0; i < iters.length; i++) { if ((o = MVEL.eval(expression[i], ctx, factory)) instanceof Iterable) { iters[i] = ((Iterable) o).iterator(); } else if (o instanceof Object[]) { iters[i] = new ArrayIterator((Object[]) o); } else { throw new TemplateRuntimeError("cannot iterate object type: " + o.getClass().getName()); } } Map locals = new HashMap(); MapVariableResolverFactory localFactory = new MapVariableResolverFactory(locals, factory); int iterate = iters.length; while (true) { for (int i = 0; i < iters.length; i++) { if (!iters[i].hasNext()) { iterate--; locals.put(item[i], ""); } else { locals.put(item[i], iters[i].next()); } } if (iterate != 0) { nestedNode.eval(runtime, appender, ctx, localFactory); if (sepExpr != null) { for (Iterator it : iters) { if (it.hasNext()) { appender.append(String.valueOf(MVEL.eval(sepExpr, ctx, factory))); break; } } } } else break; } return next != null ? next.eval(runtime, appender, ctx, factory) : null; } private void configure() { ArrayList items = new ArrayList(); ArrayList expr = new ArrayList(); int start = 0; for (int i = 0; i < contents.length; i++) { switch (contents[i]) { case ':': items.add(ParseTools.createStringTrimmed(contents, start, i - start)); start = i + 1; break; case ',': if (expr.size() != (items.size() - 1)) { throw new CompileException("unexpected character ',' in foreach tag", cStart + i); } expr.add(ParseTools.createStringTrimmed(contents, start, i - start)); start = i + 1; break; } } if (start < contents.length) { if (expr.size() != (items.size() - 1)) { throw new CompileException("expected character ':' in foreach tag", cEnd); } expr.add(ParseTools.createStringTrimmed(contents, start, contents.length - start)); } item = new String[items.size()]; int i = 0; for (String s : items) item[i++] = s; expression = new String[expr.size()]; i = 0; for (String s : expr) expression[i++] = s; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledNamedIncludeNode.java0000644000175000017500000000523511317165145030126 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import java.io.Serializable; import static org.mvel2.templates.util.TemplateTools.captureToEOS; import static org.mvel2.util.ParseTools.subset; public class CompiledNamedIncludeNode extends Node { private char[] includeExpression; private char[] preExpression; private Serializable cIncludeExpression; private Serializable cPreExpression; public CompiledNamedIncludeNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); int mark; this.cIncludeExpression = MVEL.compileExpression(this.includeExpression = subset(contents, 0, mark = captureToEOS(contents, 0))); if (mark != contents.length) this.cPreExpression = MVEL.compileExpression(this.preExpression = subset(contents, ++mark, contents.length - mark)); } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { if (preExpression != null) { MVEL.executeExpression(cPreExpression, ctx, factory); } if (next != null) { return next.eval(runtime, appender.append(String.valueOf(TemplateRuntime.execute(runtime.getNamedTemplateRegistry().getNamedTemplate(MVEL.executeExpression(cIncludeExpression, ctx, factory, String.class)), ctx, factory))), ctx, factory); } else { return appender.append(String.valueOf(TemplateRuntime.execute(runtime.getNamedTemplateRegistry().getNamedTemplate(MVEL.executeExpression(cIncludeExpression, ctx, factory, String.class)), ctx, factory))); } } public boolean demarcate(Node terminatingNode, char[] template) { return false; } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/TerminalExpressionNode.java0000644000175000017500000000411511164527565027760 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import static org.mvel2.util.ParseTools.subset; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.PrintWriter; public class TerminalExpressionNode extends Node { public TerminalExpressionNode() { } public TerminalExpressionNode(Node node) { this.begin = node.begin; this.name = node.name; this.contents = node.contents; } public TerminalExpressionNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); } public TerminalExpressionNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { return MVEL.eval(contents, ctx, factory); } public boolean demarcate(Node terminatingNode, char[] template) { return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledTerminalExpressionNode.java0000644000175000017500000000430211317165145031423 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import java.io.Serializable; import static org.mvel2.util.ParseTools.subset; public class CompiledTerminalExpressionNode extends TerminalExpressionNode { private Serializable ce; public CompiledTerminalExpressionNode() { } public CompiledTerminalExpressionNode(Node node) { this.begin = node.begin; this.name = node.name; ce = MVEL.compileExpression(this.contents = node.contents); } public CompiledTerminalExpressionNode(int begin, String name, char[] template, int start, int end) { this.begin = begin; this.name = name; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); } public CompiledTerminalExpressionNode(int begin, String name, char[] template, int start, int end, Node next) { this.name = name; this.begin = begin; ce = MVEL.compileExpression(this.contents = subset(template, this.cStart = start, (this.end = this.cEnd = end) - start - 1)); this.next = next; } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { return MVEL.executeExpression(ce, ctx, factory); } public boolean demarcate(Node terminatingNode, char[] template) { return false; } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/res/CompiledIfNode.java0000644000175000017500000000304011317165145026124 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.res; import org.mvel2.MVEL; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import java.io.Serializable; public class CompiledIfNode extends IfNode { private Serializable ce; public CompiledIfNode(int begin, String name, char[] template, int start, int end) { super(begin, name, template, start, end); ce = MVEL.compileExpression(contents); } public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { if (contents.length == 0 || MVEL.executeExpression(ce, ctx, factory, Boolean.class)) { return trueNode.eval(runtime, appender, ctx, factory); } return next != null ? next.eval(runtime, appender, ctx, factory) : null; } }mvel-2.0.18.orig/src/main/java/org/mvel2/templates/util/0000755000175000017500000000000011412747053022627 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/templates/util/TemplateTools.java0000644000175000017500000000732011301035750026257 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.util; import org.mvel2.templates.TemplateError; import org.mvel2.templates.res.Node; import org.mvel2.templates.res.TerminalNode; import static org.mvel2.util.ParseTools.balancedCapture; import org.mvel2.util.StringAppender; import java.io.*; import java.nio.ByteBuffer; import static java.nio.ByteBuffer.allocateDirect; import java.nio.channels.FileChannel; public class TemplateTools { public static Node getLastNode(Node node) { Node n = node; while (true) { if (n.getNext() instanceof TerminalNode) return n; n = n.getNext(); } } public static int captureToEOS(char[] expression, int cursor) { int length = expression.length; while (cursor != length) { switch (expression[cursor]) { case '(': case '[': case '{': cursor = balancedCapture(expression, cursor, expression[cursor]); break; case ';': case '}': return cursor; } cursor++; } return cursor; } public static String readInFile(String file) { return readInFile(new File(file)); } public static String readInFile(File file) { try { FileChannel fc = new FileInputStream(file).getChannel(); ByteBuffer buf = allocateDirect(10); StringAppender appender = new StringAppender(); int read; while (true) { buf.rewind(); if ((read = fc.read(buf)) != -1) { buf.rewind(); for (; read != 0; read--) { appender.append((char) buf.get()); } } else { break; } } fc.close(); return appender.toString(); } catch (FileNotFoundException e) { throw new TemplateError("cannot include template '" + file.getName() + "': file not found."); } catch (IOException e) { throw new TemplateError("unknown I/O exception while including '" + file.getName() + "' (stacktrace nested)", e); } } public static String readStream(InputStream instream) { try { byte[] buf = new byte[10]; StringAppender appender = new StringAppender(); int read; while ((read = instream.read(buf)) != -1) { for (int i = 0; i < read; i++) { appender.append((char) buf[i]); } } return appender.toString(); } catch (NullPointerException e) { if (instream == null) { throw new TemplateError("null input stream", e); } else { throw e; } } catch (IOException e) { throw new TemplateError("unknown I/O exception while including (stacktrace nested)", e); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/util/io/0000755000175000017500000000000011412747053023236 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/templates/util/io/StringAppenderStream.java0000644000175000017500000000145711164527565030221 0ustar drazzibdrazzibpackage org.mvel2.templates.util.io; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.util.StringAppender; /** * Created by IntelliJ IDEA. * User: christopherbrock * Date: 31-Mar-2009 * Time: 7:36:24 PM * To change this template use File | Settings | File Templates. */ public class StringAppenderStream implements TemplateOutputStream { private StringAppender appender; public StringAppenderStream(StringAppender appender) { this.appender = appender; } public TemplateOutputStream append(CharSequence c) { appender.append(c); return this; } public TemplateOutputStream append(char[] c) { appender.append(c); return this; } @Override public String toString() { return appender.toString(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/util/io/StandardOutputStream.java0000644000175000017500000000141711164527565030251 0ustar drazzibdrazzibpackage org.mvel2.templates.util.io; import org.mvel2.templates.util.TemplateOutputStream; import java.io.OutputStream; import java.io.PrintWriter; public class StandardOutputStream implements TemplateOutputStream { private OutputStream outputStream; private PrintWriter printWriter; public StandardOutputStream(OutputStream outputStream) { this.printWriter = new PrintWriter(this.outputStream = outputStream); } public TemplateOutputStream append(CharSequence c) { printWriter.append(c); return this; } public TemplateOutputStream append(char[] c) { for (char i : c) { printWriter.append(i); } return this; } @Override public String toString() { return null; } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/util/ArrayIterator.java0000644000175000017500000000211211077457613026265 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates.util; import java.util.Iterator; public class ArrayIterator implements Iterator { private Object[] array; private int cursor = 0; public ArrayIterator(Object[] array) { this.array = array; } public boolean hasNext() { return cursor != array.length; } public Object next() { return array[cursor++]; } public void remove() { } } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/util/TemplateOutputStream.java0000644000175000017500000000026711164527565027657 0ustar drazzibdrazzibpackage org.mvel2.templates.util; public interface TemplateOutputStream { public TemplateOutputStream append(CharSequence c); public TemplateOutputStream append(char[] c); } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/TemplateRegistry.java0000644000175000017500000000175211077457613026035 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; import java.util.Iterator; import java.util.Set; public interface TemplateRegistry { Iterator iterator(); Set getNames(); boolean contains(String name); void addNamedTemplate(String name, CompiledTemplate template); CompiledTemplate getNamedTemplate(String name); } mvel-2.0.18.orig/src/main/java/org/mvel2/templates/TemplateError.java0000644000175000017500000000253011077457613025311 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.templates; public class TemplateError extends RuntimeException { public TemplateError() { super(); //To change body of overridden methods use File | Settings | File Templates. } public TemplateError(String s) { super(s); //To change body of overridden methods use File | Settings | File Templates. } public TemplateError(String s, Throwable throwable) { super(s, throwable); //To change body of overridden methods use File | Settings | File Templates. } public TemplateError(Throwable throwable) { super(throwable); //To change body of overridden methods use File | Settings | File Templates. } } mvel-2.0.18.orig/src/main/java/org/mvel2/CompileException.java0000644000175000017500000001124411301035750023757 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import static org.mvel2.util.ParseTools.isWhitespace; import static org.mvel2.util.ParseTools.repeatChar; import org.mvel2.util.StringAppender; import static java.lang.String.copyValueOf; import java.util.ArrayList; import java.util.List; /** * Standard exception thrown for all general compile and some runtime failures. */ public class CompileException extends RuntimeException { private char[] expr; private int cursor = 0; private int msgOffset = 0; private int lineNumber = 1; private int column = 0; private int lastLineStart = 0; private List errors; public CompileException() { super(); } public CompileException(String message) { super(message); } public CompileException(String message, List errors) { super(message); this.errors = errors; } public CompileException(String message, int cursor) { super(message); this.cursor = cursor; } public String toString() { return generateErrorMessage(); } public CompileException(String message, char[] expr, int cursor, Throwable e) { super(message, e); this.expr = expr; this.cursor = cursor; } public CompileException(String message, char[] expr, int cursor) { super(message); this.expr = expr; this.cursor = cursor; } public CompileException(String message, Throwable cause) { super(message, cause); } public CompileException(Throwable cause) { super(cause); } @Override public String getMessage() { return generateErrorMessage(); } private CharSequence showCodeNearError(char[] expr, int cursor) { if (expr == null) return "Unknown"; int start = cursor - 10; int end = (cursor + 20); if (end > expr.length) { end = expr.length - 1; start -= 20; } if (start < 0) { start = 0; } while (start < end && isWhitespace(expr[start])) start++; CharSequence cs = null; try { cs = copyValueOf(expr, start, end - start); } catch (StringIndexOutOfBoundsException e) { System.out.println(""); throw e; } msgOffset = start; return cs; } private String generateErrorMessage() { StringAppender appender = new StringAppender().append("[Error: " + super.getMessage() + "]\n"); int offset = appender.length(); appender.append("[Near : {... "); offset = appender.length() - offset; appender.append(showCodeNearError(expr, cursor)) .append(" ....}]\n") .append(repeatChar(' ', offset)); if ((offset = cursor - msgOffset - 1) < 0) offset = 0; appender.append(repeatChar(' ', offset)).append("^"); if (lineNumber != -1) { appender.append('\n') .append("[Line: " + lineNumber + ", Column: " + column + "]"); } return appender.toString(); } public char[] getExpr() { return expr; } public int getCursor() { return cursor; } public List getErrors() { return errors != null ? errors : new ArrayList(0); } public void setErrors(List errors) { this.errors = errors; } public int getLineNumber() { return lineNumber; } public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } public int getColumn() { return column; } public void setColumn(int column) { this.column = column; } public void setExpr(char[] expr) { this.expr = expr; } public void setCursor(int cursor) { this.cursor = cursor; } public int getLastLineStart() { return lastLineStart; } public void setLastLineStart(int lastLineStart) { this.lastLineStart = lastLineStart; } } mvel-2.0.18.orig/src/main/java/org/mvel2/PropertyAccessor.java0000644000175000017500000012240111324125240024014 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import static org.mvel2.MVEL.eval; import org.mvel2.ast.Function; import org.mvel2.ast.Proto; import org.mvel2.ast.TypeDescriptor; import static org.mvel2.ast.TypeDescriptor.getClassReference; import static org.mvel2.compiler.AbstractParser.LITERALS; import static org.mvel2.compiler.AbstractParser.getCurrentThreadParserContext; import org.mvel2.integration.GlobalListenerFactory; import static org.mvel2.integration.GlobalListenerFactory.notifySetListeners; import static org.mvel2.integration.PropertyHandlerFactory.*; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.MethodStub; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.*; import static org.mvel2.util.PropertyTools.getFieldOrAccessor; import static org.mvel2.util.PropertyTools.getFieldOrWriteAccessor; import org.mvel2.util.StringAppender; import static java.lang.Character.isJavaIdentifierPart; import static java.lang.Thread.currentThread; import java.lang.ref.WeakReference; import java.lang.reflect.*; import static java.lang.reflect.Array.getLength; import java.util.*; @SuppressWarnings({"unchecked"}) /** * The property accessor class is used for extracting properties from objects instances. */ public class PropertyAccessor { private int start = 0; private int cursor = 0; private char[] property; private int length; private Object thisReference; private Object ctx; private Object curr; private boolean first = true; private boolean nullHandle = false; private VariableResolverFactory variableFactory; private static final int DONE = -1; private static final int NORM = 0; private static final int METH = 1; private static final int COL = 2; private static final int WITH = 3; private static final Object[] EMPTYARG = new Object[0]; private static final WeakHashMap>> READ_PROPERTY_RESOLVER_CACHE; private static final WeakHashMap>> WRITE_PROPERTY_RESOLVER_CACHE; private static final WeakHashMap>> METHOD_RESOLVER_CACHE; private static final WeakHashMap> METHOD_PARMTYPES_CACHE; static { READ_PROPERTY_RESOLVER_CACHE = (new WeakHashMap>>(10)); WRITE_PROPERTY_RESOLVER_CACHE = (new WeakHashMap>>(10)); METHOD_RESOLVER_CACHE = (new WeakHashMap>>(10)); METHOD_PARMTYPES_CACHE = new WeakHashMap>(10); } public PropertyAccessor(char[] property, Object ctx) { this.property = property; this.length = property.length; this.ctx = ctx; } public PropertyAccessor(char[] property, Object ctx, VariableResolverFactory resolver, Object thisReference) { this.length = (this.property = property).length; this.ctx = ctx; this.variableFactory = resolver; this.thisReference = thisReference; } public PropertyAccessor(char[] property, Object ctx, Object thisRef, VariableResolverFactory resolver, Object thisReference) { this.length = (this.property = property).length; this.ctx = ctx; this.thisReference = thisRef; this.variableFactory = resolver; this.thisReference = thisReference; } public PropertyAccessor(VariableResolverFactory resolver, Object thisReference) { this.variableFactory = resolver; this.thisReference = thisReference; } public PropertyAccessor(char[] property, int offset, int end, Object ctx, VariableResolverFactory resolver) { this.property = property; this.cursor = offset; this.length = end; this.ctx = ctx; this.variableFactory = resolver; } public PropertyAccessor(String property, Object ctx) { this.length = (this.property = property.toCharArray()).length; this.ctx = ctx; } public static Object get(String property, Object ctx) { return new PropertyAccessor(property, ctx).get(); } public static Object get(char[] property, Object ctx, VariableResolverFactory resolver, Object thisReference) { return new PropertyAccessor(property, ctx, resolver, thisReference).get(); } public static Object get(char[] property, int offset, int end, Object ctx, VariableResolverFactory resolver) { return new PropertyAccessor(property, offset, end, ctx, resolver).get(); } public static Object get(String property, Object ctx, VariableResolverFactory resolver, Object thisReference) { return new PropertyAccessor(property.toCharArray(), ctx, resolver, thisReference).get(); } public static void set(Object ctx, String property, Object value) { new PropertyAccessor(property, ctx).set(value); } public static void set(Object ctx, VariableResolverFactory resolver, String property, Object value) { new PropertyAccessor(property.toCharArray(), ctx, resolver, null).set(value); } private Object get() { curr = ctx; try { if (!MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING) { while (cursor < length) { switch (nextToken()) { case NORM: curr = getBeanProperty(curr, capture()); break; case METH: curr = getMethod(curr, capture()); break; case COL: curr = getCollectionProperty(curr, capture()); break; case WITH: curr = getWithProperty(curr); break; case DONE: } if (nullHandle) { if (curr == null) { return null; } else { nullHandle = false; } } first = false; } return curr; } else { while (cursor < length) { switch (nextToken()) { case NORM: if ((curr = getBeanPropertyAO(curr, capture())) == null && hasNullPropertyHandler()) { curr = getNullPropertyHandler().getProperty(capture(), ctx, variableFactory); } break; case METH: if ((curr = getMethod(curr, capture())) == null && hasNullMethodHandler()) { curr = getNullMethodHandler().getProperty(capture(), ctx, variableFactory); } break; case COL: curr = getCollectionPropertyAO(curr, capture()); break; case WITH: curr = getWithProperty(curr); break; case DONE: } if (nullHandle) { if (curr == null) { return null; } else { nullHandle = false; } } first = false; } return curr; } } catch (InvocationTargetException e) { throw new PropertyAccessException("could not access property", e); } catch (IllegalAccessException e) { throw new PropertyAccessException("could not access property", e); } catch (IndexOutOfBoundsException e) { throw new PropertyAccessException("array or collections index out of bounds in property: " + new String(property), e); } catch (PropertyAccessException e) { throw new PropertyAccessException("failed to access property: " + new String(property) + ": " + e.getMessage(), e); } catch (CompileException e) { throw e; } catch (NullPointerException e) { throw new PropertyAccessException("null pointer exception in property: " + new String(property), e); } catch (Exception e) { throw new PropertyAccessException("unknown exception in expression: " + new String(property), e); } } private void set(Object value) { curr = ctx; try { int oLength = length; length = findAbsoluteLast(property); if ((curr = get()) == null) throw new PropertyAccessException("cannot bind to null context: " + new String(property)); length = oLength; if (nextToken() == COL) { int start = ++cursor; whiteSpaceSkip(); if (cursor == length || scanTo(']')) throw new PropertyAccessException("unterminated '['"); String ex = new String(property, start, cursor - start); if (!MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING) { if (curr instanceof Map) { //noinspection unchecked ((Map) curr).put(eval(ex, this.ctx, this.variableFactory), value); } else if (curr instanceof List) { //noinspection unchecked ((List) curr).set(eval(ex, this.ctx, this.variableFactory, Integer.class), value); } else if (hasPropertyHandler(curr.getClass())) { getPropertyHandler(curr.getClass()).setProperty(ex, ctx, variableFactory, value); } else if (curr.getClass().isArray()) { Array.set(curr, eval(ex, this.ctx, this.variableFactory, Integer.class), convert(value, getBaseComponentType(curr.getClass()))); } else { throw new PropertyAccessException("cannot bind to collection property: " + new String(property) + ": not a recognized collection type: " + ctx.getClass()); } return; } else { notifySetListeners(ctx, ex, variableFactory, value); if (curr instanceof Map) { //noinspection unchecked if (hasPropertyHandler(Map.class)) getPropertyHandler(Map.class).setProperty(ex, curr, variableFactory, value); else ((Map) curr).put(eval(ex, this.ctx, this.variableFactory), value); } else if (curr instanceof List) { //noinspection unchecked if (hasPropertyHandler(List.class)) getPropertyHandler(List.class).setProperty(ex, curr, variableFactory, value); else ((List) curr).set(eval(ex, this.ctx, this.variableFactory, Integer.class), value); } else if (curr.getClass().isArray()) { if (hasPropertyHandler(Array.class)) getPropertyHandler(Array.class).setProperty(ex, curr, variableFactory, value); else Array.set(curr, eval(ex, this.ctx, this.variableFactory, Integer.class), convert(value, getBaseComponentType(curr.getClass()))); } else if (hasPropertyHandler(curr.getClass())) { getPropertyHandler(curr.getClass()).setProperty(ex, curr, variableFactory, value); } else { throw new PropertyAccessException("cannot bind to collection property: " + new String(property) + ": not a recognized collection type: " + ctx.getClass()); } return; } } else if (MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING && hasPropertyHandler(curr.getClass())) { getPropertyHandler(curr.getClass()).setProperty(capture(), curr, variableFactory, value); return; } String tk = capture(); Member member = checkWriteCache(curr.getClass(), tk == null ? 0 : tk.hashCode()); if (member == null) { addWriteCache(curr.getClass(), tk.hashCode(), (member = value != null ? getFieldOrWriteAccessor(curr.getClass(), tk, value.getClass()) : getFieldOrWriteAccessor(curr.getClass(), tk))); } if (member instanceof Method) { Method meth = (Method) member; Class[] paramaterTypes = checkParmTypesCache(meth); if (value != null && !paramaterTypes[0].isAssignableFrom(value.getClass())) { if (!canConvert(paramaterTypes[0], value.getClass())) { throw new ConversionException("cannot convert type: " + value.getClass() + ": to " + meth.getParameterTypes()[0]); } meth.invoke(curr, convert(value, paramaterTypes[0])); } else { meth.invoke(curr, value); } } else if (member != null) { Field fld = (Field) member; if (value != null && !fld.getType().isAssignableFrom(value.getClass())) { if (!canConvert(fld.getType(), value.getClass())) { throw new ConversionException("cannot convert type: " + value.getClass() + ": to " + fld.getType()); } fld.set(curr, convert(value, fld.getType())); } else { fld.set(curr, value); } } else if (curr instanceof Map) { //noinspection unchecked ((Map) curr).put(eval(tk, this.ctx, this.variableFactory), value); } else { throw new PropertyAccessException("could not access/write property (" + tk + ") in: " + (curr == null ? "Unknown" : curr.getClass().getName())); } } catch (InvocationTargetException e) { throw new PropertyAccessException("could not access property", e); } catch (IllegalAccessException e) { throw new PropertyAccessException("could not access property", e); } } private int nextToken() { switch (property[start = cursor]) { case '[': return COL; case '.': // ++cursor; while (cursor < length && isWhitespace(property[cursor])) cursor++; if ((start + 1) != length) { switch (property[cursor = ++start]) { case '?': cursor = ++start; nullHandle = true; break; case '{': return WITH; } } } while (cursor < length && isWhitespace(property[cursor])) cursor++; start = cursor; //noinspection StatementWithEmptyBody while (++cursor < length && isJavaIdentifierPart(property[cursor])) ; if (cursor < length) { while (isWhitespace(property[cursor])) cursor++; switch (property[cursor]) { case '[': return COL; case '(': return METH; default: return 0; } } return 0; } private String capture() { return new String(property, start, trimLeft(cursor) - start); } protected int trimLeft(int pos) { while (pos > 0 && isWhitespace(property[pos - 1])) pos--; return pos; } public static void clearPropertyResolverCache() { READ_PROPERTY_RESOLVER_CACHE.clear(); WRITE_PROPERTY_RESOLVER_CACHE.clear(); METHOD_RESOLVER_CACHE.clear(); } public static void reportCacheSizes() { System.out.println("read property cache: " + READ_PROPERTY_RESOLVER_CACHE.size()); for (Class cls : READ_PROPERTY_RESOLVER_CACHE.keySet()) { System.out.println(" [" + cls.getName() + "]: " + READ_PROPERTY_RESOLVER_CACHE.get(cls).size() + " entries."); } System.out.println("write property cache: " + WRITE_PROPERTY_RESOLVER_CACHE.size()); for (Class cls : WRITE_PROPERTY_RESOLVER_CACHE.keySet()) { System.out.println(" [" + cls.getName() + "]: " + WRITE_PROPERTY_RESOLVER_CACHE.get(cls).size() + " entries."); } System.out.println("method cache: " + METHOD_RESOLVER_CACHE.size()); for (Class cls : METHOD_RESOLVER_CACHE.keySet()) { System.out.println(" [" + cls.getName() + "]: " + METHOD_RESOLVER_CACHE.get(cls).size() + " entries."); } } private static void addReadCache(Class cls, Integer property, Member member) { synchronized (READ_PROPERTY_RESOLVER_CACHE) { WeakHashMap> nestedMap = READ_PROPERTY_RESOLVER_CACHE.get(cls); if (nestedMap == null) { READ_PROPERTY_RESOLVER_CACHE.put(cls, nestedMap = new WeakHashMap>()); } nestedMap.put(property, new WeakReference(member)); } } private static Member checkReadCache(Class cls, Integer property) { WeakHashMap> map = READ_PROPERTY_RESOLVER_CACHE.get(cls); if (map != null) { WeakReference member = map.get(property); if (member != null) return member.get(); } return null; } private static void addWriteCache(Class cls, Integer property, Member member) { synchronized (WRITE_PROPERTY_RESOLVER_CACHE) { WeakHashMap> map = WRITE_PROPERTY_RESOLVER_CACHE.get(cls); if (map == null) { WRITE_PROPERTY_RESOLVER_CACHE.put(cls, map = new WeakHashMap>()); } map.put(property, new WeakReference(member)); } } private static Member checkWriteCache(Class cls, Integer property) { Map> map = WRITE_PROPERTY_RESOLVER_CACHE.get(cls); if (map != null) { WeakReference member = map.get(property); if (member != null) return member.get(); } return null; } public static Class[] checkParmTypesCache(Method member) { WeakReference pt = METHOD_PARMTYPES_CACHE.get(member); Class[] ret; if (pt == null || (ret = pt.get()) == null) { METHOD_PARMTYPES_CACHE.put(member, pt = new WeakReference(ret = member.getParameterTypes())); } return ret; } private static void addMethodCache(Class cls, Integer property, Method member) { synchronized (METHOD_RESOLVER_CACHE) { WeakHashMap> map = METHOD_RESOLVER_CACHE.get(cls); if (map == null) { METHOD_RESOLVER_CACHE.put(cls, map = new WeakHashMap>()); } map.put(property, new WeakReference(new Object[]{member, member.getParameterTypes()})); } } private static Object[] checkMethodCache(Class cls, Integer property) { Map> map = METHOD_RESOLVER_CACHE.get(cls); if (map != null) { WeakReference ref = map.get(property); if (ref != null) return ref.get(); } return null; } private Object getBeanPropertyAO(Object ctx, String property) throws IllegalAccessException, InvocationTargetException { if (ctx != null && hasPropertyHandler(ctx.getClass())) return getPropertyHandler(ctx.getClass()).getProperty(property, ctx, variableFactory); GlobalListenerFactory.notifyGetListeners(ctx, property, variableFactory); return getBeanProperty(ctx, property); } private Object getBeanProperty(Object ctx, String property) throws IllegalAccessException, InvocationTargetException { if (first) { if ("this".equals(property)) { return this.ctx; } else if (LITERALS.containsKey(property)) { return LITERALS.get(property); } else if (variableFactory != null && variableFactory.isResolveable(property)) { return variableFactory.getVariableResolver(property).getValue(); } } if (ctx != null) { Class cls; Member member = checkReadCache(cls = (ctx instanceof Class ? ((Class) ctx) : ctx.getClass()), property.hashCode()); if (member == null) { addReadCache(cls, property.hashCode(), member = getFieldOrAccessor(cls, property)); } if (member instanceof Method) { try { return ((Method) member).invoke(ctx, EMPTYARG); } catch (IllegalAccessException e) { synchronized (member) { try { ((Method) member).setAccessible(true); return ((Method) member).invoke(ctx, EMPTYARG); } finally { ((Method) member).setAccessible(false); } } } } else if (member != null) { return ((Field) member).get(ctx); } else if (ctx instanceof Map && (((Map) ctx).containsKey(property) || nullHandle)) { if (ctx instanceof Proto.ProtoInstance) { return ((Proto.ProtoInstance) ctx).get(property).call(null, thisReference, variableFactory, EMPTY_OBJ_ARR); } return ((Map) ctx).get(property); } else if ("length".equals(property) && ctx.getClass().isArray()) { return getLength(ctx); } else if (ctx instanceof Class) { Class c = (Class) ctx; for (Method m : c.getMethods()) { if (property.equals(m.getName())) { if (MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) { return m.invoke(ctx, EMPTY_OBJ_ARR); } return m; } } try { return findClass(variableFactory, c.getName() + "$" + property, null); } catch (ClassNotFoundException cnfe) { // fall through. } } else if (hasPropertyHandler(cls)) { return getPropertyHandler(cls).getProperty(property, ctx, variableFactory); } } Object tryStatic = tryStaticAccess(); if (tryStatic != null) { if (tryStatic instanceof Class || tryStatic instanceof Method) return tryStatic; else { return ((Field) tryStatic).get(null); } } else if (MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) { return getMethod(ctx, property); } throw new PropertyAccessException("could not access property: " + property); } private void whiteSpaceSkip() { if (cursor < length) //noinspection StatementWithEmptyBody while (isWhitespace(property[cursor]) && ++cursor < length) ; } /** * @param c - character to scan to. * @return - returns true is end of statement is hit, false if the scan scar is countered. */ private boolean scanTo(char c) { for (; cursor < length; cursor++) { switch (property[cursor]) { case '\'': case '"': cursor = captureStringLiteral(property[cursor], property, cursor, property.length); default: if (property[cursor] == c) { return false; } } } return true; } private Object getWithProperty(Object ctx) { parseWithExpressions(new String(property, 0, cursor - 1).trim(), property, cursor + 1, cursor = balancedCaptureWithLineAccounting(property, cursor, '{', getCurrentThreadParserContext()), ctx, variableFactory); cursor++; return ctx; } /** * Handle accessing a property embedded in a collections, map, or array * * @param ctx - * @param prop - * @return - * @throws Exception - */ private Object getCollectionProperty(Object ctx, String prop) throws Exception { if (prop.length() != 0) { ctx = getBeanProperty(ctx, prop); } int start = ++cursor; whiteSpaceSkip(); if (cursor == length || scanTo(']')) throw new PropertyAccessException("unterminated '['"); prop = new String(property, start, cursor++ - start); if (ctx instanceof Map) { return ((Map) ctx).get(eval(prop, ctx, variableFactory)); } else if (ctx instanceof List) { return ((List) ctx).get((Integer) eval(prop, ctx, variableFactory)); } else if (ctx instanceof Collection) { int count = (Integer) eval(prop, ctx, variableFactory); if (count > ((Collection) ctx).size()) throw new PropertyAccessException("index [" + count + "] out of bounds on collections"); Iterator iter = ((Collection) ctx).iterator(); for (int i = 0; i < count; i++) iter.next(); return iter.next(); } else if (ctx.getClass().isArray()) { return Array.get(ctx, (Integer) eval(prop, ctx, variableFactory)); } else if (ctx instanceof CharSequence) { return ((CharSequence) ctx).charAt((Integer) eval(prop, ctx, variableFactory)); } else { // TypeDescriptor td = new TypeDescriptor(property, 0); try { return getClassReference(getCurrentThreadParserContext(), (Class) ctx, new TypeDescriptor(property, 0)); } catch (Exception e) { throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()), e); } } } private Object getCollectionPropertyAO(Object ctx, String prop) throws Exception { if (prop.length() != 0) { ctx = getBeanProperty(ctx, prop); } int start = ++cursor; whiteSpaceSkip(); if (cursor == length || scanTo(']')) throw new PropertyAccessException("unterminated '['"); prop = new String(property, start, cursor++ - start); if (ctx instanceof Map) { if (hasPropertyHandler(Map.class)) return getPropertyHandler(Map.class).getProperty(prop, ctx, variableFactory); else return ((Map) ctx).get(eval(prop, ctx, variableFactory)); } else if (ctx instanceof List) { if (hasPropertyHandler(List.class)) return getPropertyHandler(List.class).getProperty(prop, ctx, variableFactory); else return ((List) ctx).get((Integer) eval(prop, ctx, variableFactory)); } else if (ctx instanceof Collection) { if (hasPropertyHandler(Collection.class)) return getPropertyHandler(Collection.class).getProperty(prop, ctx, variableFactory); else { int count = (Integer) eval(prop, ctx, variableFactory); if (count > ((Collection) ctx).size()) throw new PropertyAccessException("index [" + count + "] out of bounds on collections"); Iterator iter = ((Collection) ctx).iterator(); for (int i = 0; i < count; i++) iter.next(); return iter.next(); } } else if (ctx.getClass().isArray()) { if (hasPropertyHandler(Array.class)) return getPropertyHandler(Array.class).getProperty(prop, ctx, variableFactory); return Array.get(ctx, (Integer) eval(prop, ctx, variableFactory)); } else if (ctx instanceof CharSequence) { if (hasPropertyHandler(CharSequence.class)) return getPropertyHandler(CharSequence.class).getProperty(prop, ctx, variableFactory); else return ((CharSequence) ctx).charAt((Integer) eval(prop, ctx, variableFactory)); } else { try { return getClassReference(getCurrentThreadParserContext(), (Class) ctx, new TypeDescriptor(property, 0)); } catch (Exception e) { throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName())); } } } /** * Find an appropriate method, execute it, and return it's response. * * @param ctx - * @param name - * @return - * @throws Exception - */ @SuppressWarnings({"unchecked"}) private Object getMethod(Object ctx, String name) { int st = cursor; String tk = cursor != length && property[cursor] == '(' && ((cursor = balancedCapture(property, cursor, '(')) - st) > 1 ? new String(property, st + 1, cursor - st - 1) : ""; cursor++; Object[] args; if (tk.length() == 0) { args = ParseTools.EMPTY_OBJ_ARR; } else { String[] subtokens = parseParameterList(tk.toCharArray(), 0, -1); args = new Object[subtokens.length]; for (int i = 0; i < subtokens.length; i++) { args[i] = eval(subtokens[i], thisReference, variableFactory); } } if (first && variableFactory != null && variableFactory.isResolveable(name)) { Object ptr = variableFactory.getVariableResolver(name).getValue(); if (ptr instanceof Method) { ctx = ((Method) ptr).getDeclaringClass(); name = ((Method) ptr).getName(); } else if (ptr instanceof MethodStub) { ctx = ((MethodStub) ptr).getClassReference(); name = ((MethodStub) ptr).getMethodName(); } else if (ptr instanceof Function) { ((Function) ptr).checkArgumentCount(args.length); return ((Function) ptr).call(null, thisReference, variableFactory, args); } else { throw new OptimizationFailure("attempt to optimize a method call for a reference that does not point to a method: " + name + " (reference is type: " + (ctx != null ? ctx.getClass().getName() : null) + ")"); } first = false; } if (ctx == null) throw new CompileException("no such method or function: " + name); /** * If the target object is an instance of java.lang.Class itself then do not * adjust the Class scope target. */ Class cls = (ctx instanceof Class ? (Class) ctx : ctx.getClass()); if (cls == Proto.ProtoInstance.class) { return ((Proto.ProtoInstance) ctx).get(name).call(null, thisReference, variableFactory, args); } /** * Check to see if we have already cached this method; */ Object[] cache = checkMethodCache(cls, createSignature(name, tk)); Method m; Class[] parameterTypes; if (cache != null) { m = (Method) cache[0]; parameterTypes = (Class[]) cache[1]; } else { m = null; parameterTypes = null; } /** * If we have not cached the method then we need to go ahead and try to resolve it. */ if (m == null) { /** * Try to find an instance method from the class target. */ if ((m = getBestCandidate(args, name, cls, cls.getMethods(), false)) != null) { addMethodCache(cls, createSignature(name, tk), m); parameterTypes = m.getParameterTypes(); } if (m == null) { /** * If we didn't find anything, maybe we're looking for the actual java.lang.Class methods. */ if ((m = getBestCandidate(args, name, cls, cls.getClass().getDeclaredMethods(), false)) != null) { addMethodCache(cls, createSignature(name, tk), m); parameterTypes = m.getParameterTypes(); } } } if (m == null) { StringAppender errorBuild = new StringAppender(); for (int i = 0; i < args.length; i++) { errorBuild.append(args[i] != null ? args[i].getClass().getName() : null); if (i < args.length - 1) errorBuild.append(", "); } if ("size".equals(name) && args.length == 0 && cls.isArray()) { return getLength(ctx); } throw new PropertyAccessException("unable to resolve method: " + cls.getName() + "." + name + "(" + errorBuild.toString() + ") [arglength=" + args.length + "]"); } else { for (int i = 0; i < args.length; i++) { args[i] = convert(args[i], parameterTypes[i]); } /** * Invoke the target method and return the response. */ try { return m.invoke(ctx, args); } catch (IllegalAccessException e) { try { addMethodCache(cls, createSignature(name, tk), (m = getWidenedTarget(m))); return m.invoke(ctx, args); } catch (Exception e2) { throw new PropertyAccessException("unable to invoke method: " + name, e2); } } catch (Exception e) { throw new PropertyAccessException("unable to invoke method: " + name, e); } } } private static int createSignature(String name, String args) { return name.hashCode() + args.hashCode(); } public int getCursorPosition() { return cursor; } /** * Try static access of the property, and return an instance of the Field, Method of Class if successful. * * @return - Field, Method or Class instance. */ protected Object tryStaticAccess() { int begin = cursor; try { /** * Try to resolve this *smartly* as a static class reference. * * This starts at the end of the token and starts to step backwards to figure out whether * or not this may be a static class reference. We search for method calls simply by * inspecting for ()'s. The first union area we come to where no brackets are present is our * test-point for a class reference. If we find a class, we pass the reference to the * property accessor along with trailing methods (if any). * */ boolean meth = false; int last = length; for (int i = length - 1; i > 0; i--) { switch (property[i]) { case '.': if (!meth) { try { return currentThread().getContextClassLoader().loadClass(new String(property, 0, cursor = last)); } catch (ClassNotFoundException e) { Class cls = currentThread().getContextClassLoader().loadClass(new String(property, 0, i)); String name = new String(property, i + 1, property.length - i - 1); try { return cls.getField(name); } catch (NoSuchFieldException nfe) { for (Method m : cls.getMethods()) { if (name.equals(m.getName())) return m; } return null; } } } meth = false; last = i; break; case '}': i--; for (int d = 1; i > 0 && d != 0; i--) { switch (property[i]) { case '}': d++; break; case '{': d--; break; case '"': case '\'': char s = property[i]; while (i > 0 && (property[i] != s && property[i - 1] != '\\')) i--; } } break; case ')': i--; for (int d = 1; i > 0 && d != 0; i--) { switch (property[i]) { case ')': d++; break; case '(': d--; break; case '"': case '\'': char s = property[i]; while (i > 0 && (property[i] != s && property[i - 1] != '\\')) i--; } } meth = true; last = i++; break; case '\'': while (--i > 0) { if (property[i] == '\'' && property[i - 1] != '\\') { break; } } break; case '"': while (--i > 0) { if (property[i] == '"' && property[i - 1] != '\\') { break; } } break; } } } catch (Exception cnfe) { cursor = begin; } return null; } } mvel-2.0.18.orig/src/main/java/org/mvel2/asm/0000755000175000017500000000000011412747047020437 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/ConversionHandler.java0000644000175000017500000000265211077457613024156 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 MVFLEX/Valhalla Project and the Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; /** * The conversion handler interface defines the basic interface for implementing conversion handlers in MVEL. * * @see org.mvel2.DataConversion */ public interface ConversionHandler { /** * Converts the passed argument to the type represented by the handler. * * @param in - the input type * @return - the converted type */ public Object convertFrom(Object in); /** * This method is used to indicate to the runtime whehter or not the handler knows how to convert * from the specified type. * * @param cls - the source type * @return - true if the converter supports converting from the specified type. */ public boolean canConvertFrom(Class cls); } mvel-2.0.18.orig/src/main/java/org/mvel2/ParserConfiguration.java0000644000175000017500000001637011326620474024513 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import org.mvel2.compiler.AbstractParser; import org.mvel2.integration.Interceptor; import org.mvel2.util.MethodStub; import org.mvel2.util.PropertyTools; import org.mvel2.ast.Proto; import java.io.Serializable; import static java.lang.Thread.currentThread; import java.lang.reflect.Method; import java.util.*; /** * The resusable parser configuration object. */ public class ParserConfiguration implements Serializable { protected Map imports; protected HashSet packageImports; protected Map interceptors; protected transient ClassLoader classLoader = currentThread().getContextClassLoader(); public ParserConfiguration() { } public ParserConfiguration(Map imports, Map interceptors) { addAllImports(imports); this.interceptors = interceptors; } public ParserConfiguration(Map imports, HashSet packageImports, Map interceptors) { addAllImports(imports); this.packageImports = packageImports; this.interceptors = interceptors; } public HashSet getPackageImports() { return packageImports; } public void setPackageImports(HashSet packageImports) { this.packageImports = packageImports; } public Class getImport(String name) { if (imports != null && imports.containsKey(name) && imports.get(name) instanceof Class) { return (Class) imports.get(name); } return (Class) (AbstractParser.LITERALS.get(name) instanceof Class ? AbstractParser.LITERALS.get(name) : null); } public MethodStub getStaticImport(String name) { return imports != null ? (MethodStub) imports.get(name) : null; } public Object getStaticOrClassImport(String name) { return (imports != null && imports.containsKey(name) ? imports.get(name) : AbstractParser.LITERALS.get(name)); } public void addPackageImport(String packageName) { if (packageImports == null) packageImports = new LinkedHashSet(); packageImports.add(packageName); } public void addAllImports(Map imports) { if (imports == null) return; if (this.imports == null) this.imports = new LinkedHashMap(); Object o; for (Map.Entry entry : imports.entrySet()) { if ((o = entry.getValue()) instanceof Method) { this.imports.put(entry.getKey(), new MethodStub((Method) o)); } else { this.imports.put(entry.getKey(), o); } } } public void setAllImports(Map imports) { this.imports = imports; } private boolean checkForDynamicImport(String className) { if (packageImports == null) return false; int found = 0; Class cls = null; for (String pkg : packageImports) { try { cls = Class.forName(pkg + "." + className, true, classLoader); found++; } catch (ClassNotFoundException e) { // do nothing. } catch (NoClassDefFoundError e) { if (PropertyTools.contains(e.getMessage(), "wrong name")) { // do nothing. this is a weirdness in the jvm. // see MVEL-43 } else { throw e; } } } if (found > 1) { throw new CompileException("ambiguous class name: " + className); } else if (found == 1) { addImport(className, cls); return true; } else { return false; } } public boolean hasImport(String name) { return (imports != null && imports.containsKey(name)) || (!"this".equals(name) && !"self".equals(name) && !"empty".equals(name) && !"null".equals(name) && !"nil".equals(name) && !"true".equals(name) && !"false".equals(name) && AbstractParser.LITERALS.containsKey(name)) || checkForDynamicImport(name); } public void addImport(Class cls) { addImport(cls.getSimpleName(), cls); } public void addImport(String name, Class cls) { if (this.imports == null) this.imports = new LinkedHashMap(); this.imports.put(name, cls); } public void addImport(String name, Proto proto) { if (this.imports == null) this.imports = new LinkedHashMap(); this.imports.put(name, proto); } public void addImport(String name, Method method) { addImport(name, new MethodStub(method)); } public void addImport(String name, MethodStub method) { if (this.imports == null) this.imports = new LinkedHashMap(); this.imports.put(name, method); } public Map getInterceptors() { return interceptors; } public void setInterceptors(Map interceptors) { this.interceptors = interceptors; } public Map getImports() { return imports; } public void setImports(Map imports) { if (imports == null) return; Object val; for (Map.Entry entry : imports.entrySet()) { if ((val = entry.getValue()) instanceof Class) { addImport(entry.getKey(), (Class) val); } else if (val instanceof Method) { addImport(entry.getKey(), (Method) val); } else if (val instanceof MethodStub) { addImport(entry.getKey(), (MethodStub) val); } else if (val instanceof Proto) { addImport(entry.getKey(), (Proto) entry.getValue()); } else { throw new RuntimeException("invalid element in imports map: " + entry.getKey() + " (" + val + ")"); } } } public boolean hasImports() { return (imports != null && imports.size() != 0) || (packageImports != null && packageImports.size() != 0); } public ClassLoader getClassLoader() { return classLoader == null ? classLoader = Thread.currentThread().getContextClassLoader() : classLoader; } public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } public void setImports(HashMap imports) { this.imports = imports; } } mvel-2.0.18.orig/src/main/java/org/mvel2/math/0000755000175000017500000000000011412747041020602 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/math/MathProcessor.java0000644000175000017500000006612711225147020024243 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.math; import org.mvel2.CompileException; import org.mvel2.ConversionException; import static org.mvel2.DataConversion.convert; import org.mvel2.DataTypes; import static org.mvel2.DataTypes.BIG_DECIMAL; import static org.mvel2.DataTypes.EMPTY; import static org.mvel2.Operator.*; import org.mvel2.Unit; import org.mvel2.debug.DebugTools; import org.mvel2.util.InternalNumber; import static org.mvel2.util.ParseTools.*; import static org.mvel2.util.Soundex.soundex; import static java.lang.String.valueOf; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; /** * @author Christopher Brock */ public strictfp class MathProcessor { private static final MathContext MATH_CONTEXT = MathContext.DECIMAL128; public static Object doOperations(Object val1, int operation, Object val2) { return doOperations(val1 == null ? DataTypes.OBJECT : __resolveType(val1.getClass()), val1, operation, val2 == null ? DataTypes.NULL : __resolveType(val2.getClass()), val2); } public static Object doOperations(Object val1, int operation, int type2, Object val2) { return doOperations(val1 == null ? DataTypes.OBJECT : __resolveType(val1.getClass()), val1, operation, type2, val2); } public static Object doOperations(int type1, Object val1, int operation, int type2, Object val2) { if (type1 == -1) type1 = val1 == null ? DataTypes.OBJECT : __resolveType(val1.getClass()); if (type2 == -1) type2 = val2 == null ? DataTypes.OBJECT : __resolveType(val2.getClass()); // System.out.println("{" + val1 + " " + DebugTools.getOperatorSymbol(operation) + " " + val2 + "}"); switch (type1) { case BIG_DECIMAL: switch (type2) { case BIG_DECIMAL: return doBigDecimalArithmetic((BigDecimal) val1, operation, (BigDecimal) val2, false, -1); default: if (type2 > 99) { return doBigDecimalArithmetic((BigDecimal) val1, operation, getInternalNumberFromType(val2, type2), false, -1); } else { return _doOperations(type1, val1, operation, type2, val2); } } default: return _doOperations(type1, val1, operation, type2, val2); } } private static Object doBigDecimalArithmetic(final BigDecimal val1, final int operation, final BigDecimal val2, boolean iNumber, int returnTarget) { switch (operation) { case ADD: if (iNumber) { return narrowType(val1.add(val2, MATH_CONTEXT), returnTarget); } else { return val1.add(val2, MATH_CONTEXT); } case DIV: if (iNumber) { return narrowType(val1.divide(val2, MATH_CONTEXT), returnTarget); } else { return val1.divide(val2, MATH_CONTEXT); } case SUB: if (iNumber) { return narrowType(val1.subtract(val2, MATH_CONTEXT), returnTarget); } else { return val1.subtract(val2, MATH_CONTEXT); } case MULT: if (iNumber) { return narrowType(val1.multiply(val2, MATH_CONTEXT), returnTarget); } else { return val1.multiply(val2, MATH_CONTEXT); } case POWER: if (iNumber) { return narrowType(val1.pow(val2.intValue(), MATH_CONTEXT), returnTarget); } else { return val1.pow(val2.intValue(), MATH_CONTEXT); } case MOD: if (iNumber) { return narrowType(val1.remainder(val2), returnTarget); } else { return val1.remainder(val2); } case GTHAN: return val1.compareTo(val2) == 1 ? Boolean.TRUE : Boolean.FALSE; case GETHAN: return val1.compareTo(val2) >= 0 ? Boolean.TRUE : Boolean.FALSE; case LTHAN: return val1.compareTo(val2) == -1 ? Boolean.TRUE : Boolean.FALSE; case LETHAN: return val1.compareTo(val2) <= 0 ? Boolean.TRUE : Boolean.FALSE; case EQUAL: return val1.compareTo(val2) == 0 ? Boolean.TRUE : Boolean.FALSE; case NEQUAL: return val1.compareTo(val2) != 0 ? Boolean.TRUE : Boolean.FALSE; } return null; } private static Object _doOperations(int type1, Object val1, int operation, int type2, Object val2) { if (operation < 20) { if (type1 > 99 && type1 == type2) { return doOperationsSameType(type1, val1, operation, val2); } else if ((type1 > 99 && (type2 > 99)) || (operation != 0 && isNumber(val1) && isNumber(val2))) { return doBigDecimalArithmetic(getInternalNumberFromType(val1, type1), operation, getInternalNumberFromType(val2, type2), true, box(type2) > box(type1) ? box(type2) : box(type1)); } else if (operation != ADD && (type1 == 15 || type2 == 15) && type1 != type2 && type1 != EMPTY && type2 != EMPTY) { return doOperationNonNumeric(convert(val1, Boolean.class), operation, convert(val2, Boolean.class)); } // Fix for: MVEL-56 else if ((type1 == 1 || type2 == 1) && (type1 == 8 || type1 == 112 || type2 == 8 || type2 == 112)) { if (type1 == 1) { return doOperationNonNumeric(val1, operation, valueOf(val2)); } else { return doOperationNonNumeric(valueOf(val1), operation, val2); } } } return doOperationNonNumeric(val1, operation, val2); } private static Object doOperationNonNumeric(final Object val1, final int operation, final Object val2) { switch (operation) { case ADD: return valueOf(val1) + valueOf(val2); case EQUAL: return safeEquals(val2, val1) ? Boolean.TRUE : Boolean.FALSE; case NEQUAL: return safeNotEquals(val2, val1) ? Boolean.TRUE : Boolean.FALSE; case SUB: case DIV: case MULT: case MOD: case GTHAN: if (val1 instanceof Comparable) { try { return val2 != null && (((Comparable) val1).compareTo(val2) >= 1 ? Boolean.TRUE : Boolean.FALSE); } catch (ClassCastException e) { throw new CompileException("uncomparable values <<" + val1 + ">> and <<" + val2 + ">>", e); } } else { return Boolean.FALSE; } // break; case GETHAN: if (val1 instanceof Comparable) { //noinspection unchecked try { return val2 != null && ((Comparable) val1).compareTo(val2) >= 0 ? Boolean.TRUE : Boolean.FALSE; } catch (ClassCastException e) { throw new CompileException("uncomparable values <<" + val1 + ">> and <<" + val2 + ">>", e); } } else { return Boolean.FALSE; } case LTHAN: if (val1 instanceof Comparable) { //noinspection unchecked try { return val2 != null && ((Comparable) val1).compareTo(val2) <= -1 ? Boolean.TRUE : Boolean.FALSE; } catch (ClassCastException e) { throw new CompileException("uncomparable values <<" + val1 + ">> and <<" + val2 + ">>", e); } } else { return Boolean.FALSE; } case LETHAN: if (val1 instanceof Comparable) { //noinspection unchecked try { return val2 != null && ((Comparable) val1).compareTo(val2) <= 0 ? Boolean.TRUE : Boolean.FALSE; } catch (ClassCastException e) { throw new CompileException("uncomparable values <<" + val1 + ">> and <<" + val2 + ">>", e); } } else { return Boolean.FALSE; } case SOUNDEX: return soundex(String.valueOf(val1)).equals(soundex(String.valueOf(val2))); case STR_APPEND: return valueOf(val1) + valueOf(val2); } throw new CompileException("could not perform numeric operation on non-numeric types: left-type=" + (val1 != null ? val1.getClass().getName() : "null") + "; right-type=" + (val2 != null ? val2.getClass().getName() : "null") + " [vals (" + valueOf(val1) + ", " + valueOf(val2) + ") operation=" + DebugTools.getOperatorName(operation) + " (opcode:" + operation + ") ]"); } private static Boolean safeEquals(final Object val1, final Object val2) { if (val1 != null) { return val1.equals(val2) ? Boolean.TRUE : Boolean.FALSE; } else return val2 == null || (val2.equals(val1) ? Boolean.TRUE : Boolean.FALSE); } private static Boolean safeNotEquals(final Object val1, final Object val2) { if (val1 != null) { return !val1.equals(val2) ? Boolean.TRUE : Boolean.FALSE; } else return (val2 != null && !val2.equals(val1)) ? Boolean.TRUE : Boolean.FALSE; } private static Object doOperationsSameType(int type1, Object val1, int operation, Object val2) { switch (type1) { case DataTypes.INTEGER: case DataTypes.W_INTEGER: switch (operation) { case ADD: return ((Integer) val1) + ((Integer) val2); case SUB: return ((Integer) val1) - ((Integer) val2); case DIV: return ((Integer) val1).doubleValue() / ((Integer) val2).doubleValue(); case MULT: return ((Integer) val1) * ((Integer) val2); case POWER: double d = Math.pow((Integer) val1, (Integer) val2); if (d > Integer.MAX_VALUE) return d; else return (int) d; case MOD: return ((Integer) val1) % ((Integer) val2); case GTHAN: return ((Integer) val1) > ((Integer) val2) ? Boolean.TRUE : Boolean.FALSE; case GETHAN: return ((Integer) val1) >= ((Integer) val2) ? Boolean.TRUE : Boolean.FALSE; case LTHAN: return ((Integer) val1) < ((Integer) val2) ? Boolean.TRUE : Boolean.FALSE; case LETHAN: return ((Integer) val1) <= ((Integer) val2) ? Boolean.TRUE : Boolean.FALSE; case EQUAL: return ((Integer) val1).intValue() == ((Integer) val2).intValue() ? Boolean.TRUE : Boolean.FALSE; case NEQUAL: return ((Integer) val1).intValue() != ((Integer) val2).intValue() ? Boolean.TRUE : Boolean.FALSE; case BW_AND: return (Integer) val1 & (Integer) val2; case BW_OR: return (Integer) val1 | (Integer) val2; case BW_SHIFT_LEFT: return (Integer) val1 << (Integer) val2; case BW_SHIFT_RIGHT: return (Integer) val1 >> (Integer) val2; case BW_USHIFT_RIGHT: return (Integer) val1 >>> (Integer) val2; case BW_XOR: return (Integer) val1 ^ (Integer) val2; } case DataTypes.SHORT: case DataTypes.W_SHORT: switch (operation) { case ADD: return ((Short) val1) + ((Short) val2); case SUB: return ((Short) val1) - ((Short) val2); case DIV: return ((Short) val1).doubleValue() / ((Short) val2).doubleValue(); case MULT: return ((Short) val1) * ((Short) val2); case POWER: double d = Math.pow((Short) val1, (Short) val2); if (d > Short.MAX_VALUE) return d; else return (short) d; case MOD: return ((Short) val1) % ((Short) val2); case GTHAN: return ((Short) val1) > ((Short) val2) ? Boolean.TRUE : Boolean.FALSE; case GETHAN: return ((Short) val1) >= ((Short) val2) ? Boolean.TRUE : Boolean.FALSE; case LTHAN: return ((Short) val1) < ((Short) val2) ? Boolean.TRUE : Boolean.FALSE; case LETHAN: return ((Short) val1) <= ((Short) val2) ? Boolean.TRUE : Boolean.FALSE; case EQUAL: return ((Short) val1).shortValue() == ((Short) val2).shortValue() ? Boolean.TRUE : Boolean.FALSE; case NEQUAL: return ((Short) val1).shortValue() != ((Short) val2).shortValue() ? Boolean.TRUE : Boolean.FALSE; case BW_AND: return (Short) val1 & (Short) val2; case BW_OR: return (Short) val1 | (Short) val2; case BW_SHIFT_LEFT: return (Short) val1 << (Short) val2; case BW_SHIFT_RIGHT: return (Short) val1 >> (Short) val2; case BW_USHIFT_RIGHT: return (Short) val1 >>> (Short) val2; case BW_XOR: return (Short) val1 ^ (Short) val2; } case DataTypes.LONG: case DataTypes.W_LONG: switch (operation) { case ADD: return ((Long) val1) + ((Long) val2); case SUB: return ((Long) val1) - ((Long) val2); case DIV: return ((Long) val1).doubleValue() / ((Long) val2).doubleValue(); case MULT: return ((Long) val1) * ((Long) val2); case POWER: double d = Math.pow((Long) val1, (Long) val2); if (d > Long.MAX_VALUE) return d; else return (long) d; case MOD: return ((Long) val1) % ((Long) val2); case GTHAN: return ((Long) val1) > ((Long) val2) ? Boolean.TRUE : Boolean.FALSE; case GETHAN: return ((Long) val1) >= ((Long) val2) ? Boolean.TRUE : Boolean.FALSE; case LTHAN: return ((Long) val1) < ((Long) val2) ? Boolean.TRUE : Boolean.FALSE; case LETHAN: return ((Long) val1) <= ((Long) val2) ? Boolean.TRUE : Boolean.FALSE; case EQUAL: return ((Long) val1).longValue() == ((Long) val2).longValue() ? Boolean.TRUE : Boolean.FALSE; case NEQUAL: return ((Long) val1).longValue() != ((Long) val2).longValue() ? Boolean.TRUE : Boolean.FALSE; case BW_AND: return (Long) val1 & (Long) val2; case BW_OR: return (Long) val1 | (Long) val2; case BW_SHIFT_LEFT: return (Long) val1 << (Long) val2; case BW_USHIFT_LEFT: throw new UnsupportedOperationException("unsigned left-shift not supported"); case BW_SHIFT_RIGHT: return (Long) val1 >> (Long) val2; case BW_USHIFT_RIGHT: return (Long) val1 >>> (Long) val2; case BW_XOR: return (Long) val1 ^ (Long) val2; } case DataTypes.UNIT: val2 = ((Unit) val1).convertFrom(val2); val1 = ((Unit) val1).getValue(); case DataTypes.DOUBLE: case DataTypes.W_DOUBLE: switch (operation) { case ADD: return ((Double) val1) + ((Double) val2); case SUB: return ((Double) val1) - ((Double) val2); case DIV: return ((Double) val1) / ((Double) val2); case MULT: return ((Double) val1) * ((Double) val2); case POWER: return Math.pow((Double) val1, (Double) val2); case MOD: return ((Double) val1) % ((Double) val2); case GTHAN: return ((Double) val1) > ((Double) val2) ? Boolean.TRUE : Boolean.FALSE; case GETHAN: return ((Double) val1) >= ((Double) val2) ? Boolean.TRUE : Boolean.FALSE; case LTHAN: return ((Double) val1) < ((Double) val2) ? Boolean.TRUE : Boolean.FALSE; case LETHAN: return ((Double) val1) <= ((Double) val2) ? Boolean.TRUE : Boolean.FALSE; case EQUAL: return ((Double) val1).doubleValue() == ((Double) val2).doubleValue() ? Boolean.TRUE : Boolean.FALSE; case NEQUAL: return ((Double) val1).doubleValue() != ((Double) val2).doubleValue() ? Boolean.TRUE : Boolean.FALSE; case BW_AND: case BW_OR: case BW_SHIFT_LEFT: case BW_SHIFT_RIGHT: case BW_USHIFT_RIGHT: case BW_XOR: throw new CompileException("bitwise operation on a non-fixed-point number."); } case DataTypes.FLOAT: case DataTypes.W_FLOAT: switch (operation) { case ADD: return ((Float) val1) + ((Float) val2); case SUB: return ((Float) val1) - ((Float) val2); case DIV: return ((Float) val1).doubleValue() / ((Float) val2).doubleValue(); case MULT: return ((Float) val1) * ((Float) val2); case POWER: return narrowType(new InternalNumber((Float) val1, MATH_CONTEXT).pow(new InternalNumber((Float) val2).intValue(), MATH_CONTEXT), -1); case MOD: return ((Float) val1) % ((Float) val2); case GTHAN: return ((Float) val1) > ((Float) val2) ? Boolean.TRUE : Boolean.FALSE; case GETHAN: return ((Float) val1) >= ((Float) val2) ? Boolean.TRUE : Boolean.FALSE; case LTHAN: return ((Float) val1) < ((Float) val2) ? Boolean.TRUE : Boolean.FALSE; case LETHAN: return ((Float) val1) <= ((Float) val2) ? Boolean.TRUE : Boolean.FALSE; case EQUAL: return ((Float) val1).floatValue() == ((Float) val2).floatValue() ? Boolean.TRUE : Boolean.FALSE; case NEQUAL: return ((Float) val1).floatValue() != ((Float) val2).floatValue() ? Boolean.TRUE : Boolean.FALSE; case BW_AND: case BW_OR: case BW_SHIFT_LEFT: case BW_SHIFT_RIGHT: case BW_USHIFT_RIGHT: case BW_XOR: throw new CompileException("bitwise operation on a non-fixed-point number."); } case DataTypes.BIG_INTEGER: switch (operation) { case ADD: return ((BigInteger) val1).add(((BigInteger) val2)); case SUB: return ((BigInteger) val1).subtract(((BigInteger) val2)); case DIV: return ((BigInteger) val1).divide(((BigInteger) val2)); case MULT: return ((BigInteger) val1).multiply(((BigInteger) val2)); case POWER: return ((BigInteger) val1).pow(((BigInteger) val2).intValue()); case MOD: return ((BigInteger) val1).remainder(((BigInteger) val2)); case GTHAN: return ((BigInteger) val1).compareTo(((BigInteger) val2)) == 1 ? Boolean.TRUE : Boolean.FALSE; case GETHAN: return ((BigInteger) val1).compareTo(((BigInteger) val2)) >= 0 ? Boolean.TRUE : Boolean.FALSE; case LTHAN: return ((BigInteger) val1).compareTo(((BigInteger) val2)) == -1 ? Boolean.TRUE : Boolean.FALSE; case LETHAN: return ((BigInteger) val1).compareTo(((BigInteger) val2)) <= 0 ? Boolean.TRUE : Boolean.FALSE; case EQUAL: return ((BigInteger) val1).compareTo(((BigInteger) val2)) == 0 ? Boolean.TRUE : Boolean.FALSE; case NEQUAL: return ((BigInteger) val1).compareTo(((BigInteger) val2)) != 0 ? Boolean.TRUE : Boolean.FALSE; case BW_AND: case BW_OR: case BW_SHIFT_LEFT: case BW_SHIFT_RIGHT: case BW_USHIFT_RIGHT: case BW_XOR: throw new CompileException("bitwise operation on a number greater than 32-bits not possible"); } default: switch (operation) { case EQUAL: return safeEquals(val2, val1); case NEQUAL: return safeNotEquals(val2, val1); case ADD: return valueOf(val1) + valueOf(val2); } } return null; } private static int box(int type) { switch (type) { case DataTypes.INTEGER: return DataTypes.W_INTEGER; case DataTypes.DOUBLE: return DataTypes.W_DOUBLE; case DataTypes.LONG: return DataTypes.W_LONG; case DataTypes.SHORT: return DataTypes.W_SHORT; case DataTypes.BYTE: return DataTypes.W_BYTE; case DataTypes.FLOAT: return DataTypes.W_FLOAT; case DataTypes.CHAR: return DataTypes.W_CHAR; case DataTypes.BOOLEAN: return DataTypes.W_BOOLEAN; } return type; } private static InternalNumber getInternalNumberFromType(Object in, int type) { if (in == null) return new InternalNumber(0, MATH_CONTEXT); switch (type) { case BIG_DECIMAL: return new InternalNumber(((BigDecimal) in).doubleValue()); case DataTypes.BIG_INTEGER: return new InternalNumber((BigInteger) in, MathContext.DECIMAL128); case DataTypes.INTEGER: case DataTypes.W_INTEGER: return new InternalNumber((Integer) in, MathContext.DECIMAL32); case DataTypes.LONG: case DataTypes.W_LONG: return new InternalNumber((Long) in, MathContext.DECIMAL64); case DataTypes.STRING: return new InternalNumber((String) in, MathContext.DECIMAL64); case DataTypes.FLOAT: case DataTypes.W_FLOAT: return new InternalNumber((Float) in, MathContext.DECIMAL64); case DataTypes.DOUBLE: case DataTypes.W_DOUBLE: return new InternalNumber((Double) in, MathContext.DECIMAL64); case DataTypes.SHORT: case DataTypes.W_SHORT: return new InternalNumber((Short) in, MathContext.DECIMAL32); case DataTypes.CHAR: case DataTypes.W_CHAR: return new InternalNumber((Character) in, MathContext.DECIMAL32); case DataTypes.BOOLEAN: case DataTypes.W_BOOLEAN: return new InternalNumber(((Boolean) in) ? 1 : 0); case DataTypes.UNIT: return new InternalNumber(((Unit) in).getValue(), MathContext.DECIMAL64); case DataTypes.W_BYTE: case DataTypes.BYTE: return new InternalNumber(((Byte) in).intValue()); } throw new ConversionException("cannot convert <" + in + "> to a numeric type: " + in.getClass() + " [" + type + "]"); } } mvel-2.0.18.orig/src/main/java/org/mvel2/PropertyAccessException.java0000644000175000017500000000211311077457613025350 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; public class PropertyAccessException extends CompileException { public PropertyAccessException() { super(); } public PropertyAccessException(String message) { super( message); } public PropertyAccessException(String message, Throwable cause) { super( message, cause); } public PropertyAccessException(Throwable cause) { super(cause); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/0000755000175000017500000000000011412747041022036 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/conversion/BigIntegerCH.java0000644000175000017500000000716111077457613025152 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class BigIntegerCH implements ConversionHandler { private static final Map CNV = new HashMap(); public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Integer.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(Object.class, new Converter() { public BigInteger convert(Object o) { return new BigInteger(String.valueOf(o)); } } ); CNV.put(BigInteger.class, new Converter() { public BigInteger convert(Object o) { return (BigInteger) o; } } ); CNV.put(BigDecimal.class, new Converter() { public BigInteger convert(Object o) { return ((BigDecimal) o).toBigInteger(); } } ); CNV.put(String.class, new Converter() { public BigInteger convert(Object o) { return new BigInteger((String) o); } } ); CNV.put(Short.class, new Converter() { public BigInteger convert(Object o) { return new BigInteger(String.valueOf(o)); } } ); CNV.put(Long.class, new Converter() { public BigInteger convert(Object o) { return new BigInteger(String.valueOf(o)); } } ); CNV.put(Integer.class, new Converter() { public BigInteger convert(Object o) { return new BigInteger(String.valueOf(o)); } } ); CNV.put(String.class, new Converter() { public BigInteger convert(Object o) { return new BigInteger((String) o); } } ); CNV.put(char[].class, new Converter() { public BigInteger convert(Object o) { return new BigInteger(new String((char[]) o)); } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/IntArrayCH.java0000644000175000017500000000444311077457613024664 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import java.util.HashMap; import java.util.Map; public class IntArrayCH implements ConversionHandler { private static final Map CNV = new HashMap(); public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Boolean.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String[].class, new Converter() { public Object convert(Object o) { String[] old = (String[]) o; Integer[] n = new Integer[old.length]; for (int i = 0; i < old.length; i++) { n[i] = Integer.parseInt(old[i]); } return n; } } ); CNV.put(Object[].class, new Converter() { public Object convert(Object o) { Object[] old = (Object[]) o; Integer[] n = new Integer[old.length]; for (int i = 0; i < old.length; i++) { n[i] = Integer.parseInt(String.valueOf(old[i])); } return n; } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/DoubleCH.java0000644000175000017500000001036111363352207024330 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.String.valueOf; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class DoubleCH implements ConversionHandler { private static final Map CNV = new HashMap(); private static Converter stringConverter = new Converter() { public Object convert(Object o) { if (((String) o).length() == 0) return (double) 0; return Double.parseDouble(((String) o)); } }; public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Integer.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String.class, stringConverter ); CNV.put(Object.class, new Converter() { public Object convert(Object o) { return stringConverter.convert(valueOf(o)); } } ); CNV.put(BigDecimal.class, new Converter() { public Double convert(Object o) { return ((BigDecimal) o).doubleValue(); } } ); CNV.put(BigInteger.class, new Converter() { public Double convert(Object o) { return ((BigInteger) o).doubleValue(); } } ); CNV.put(Double.class, new Converter() { public Object convert(Object o) { return o; } } ); CNV.put(Float.class, new Converter() { public Double convert(Object o) { if (((Float) o) > Double.MAX_VALUE) { throw new ConversionException("cannot coerce Float to Double since the value (" + valueOf(o) + ") exceeds that maximum precision of Double."); } return ((Float) o).doubleValue(); } }); CNV.put(Integer.class, new Converter() { public Double convert(Object o) { //noinspection UnnecessaryBoxing return ((Integer) o).doubleValue(); } } ); CNV.put(Short.class, new Converter() { public Double convert(Object o) { //noinspection UnnecessaryBoxing return ((Short) o).doubleValue(); } } ); CNV.put(Long.class, new Converter() { public Double convert(Object o) { //noinspection UnnecessaryBoxing return ((Long) o).doubleValue(); } } ); CNV.put(Boolean.class, new Converter() { public Double convert(Object o) { if ((Boolean) o) return 1d; else return 0d; } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/PrimArrayHandler.java0000644000175000017500000000520411077457613026120 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import org.mvel2.util.ParseTools; import static org.mvel2.util.ParseTools.getBaseComponentType; import static java.lang.reflect.Array.newInstance; import static java.lang.reflect.Array.set; import static java.lang.reflect.Array.getLength; import static java.lang.reflect.Array.get; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; public class PrimArrayHandler implements ConversionHandler { private final Map CNV = new HashMap(); private final Class primitiveType; public PrimArrayHandler(Class type) { this.primitiveType = getBaseComponentType(type); } public Object convertFrom(Object in) { return handleLooseTypeConversion(in.getClass(), in, primitiveType); } public boolean canConvertFrom(Class cls) { return cls.isArray(); } /** * Messy method to handle primitive boxing for conversion. If someone can re-write this more * elegantly, be my guest. * * @param sourceType * @param input * @param targetType * @return */ private static Object handleLooseTypeConversion(Class sourceType, Object input, Class targetType) { Class targType = getBaseComponentType(targetType); int len = getLength(input); Object target = newInstance(targType, len); if (len > 0 && canConvert(targetType, getBaseComponentType(sourceType))) { for (int i = 0; i < len; i++) { set(target, i, convert(get(input,i), targType)); } } else { throw new ConversionException("cannot convert to type: " + targetType.getComponentType().getName() + "[] from " + getBaseComponentType(sourceType).getName()); } return target; } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/FloatCH.java0000644000175000017500000000752111077457613024200 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.String.valueOf; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class FloatCH implements ConversionHandler { private static final Map CNV = new HashMap(); private static Converter stringConverter = new Converter() { public Object convert(Object o) { if (((String) o).length() == 0) return (float) 0; return Float.parseFloat(((String) o)); } }; public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Integer.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String.class, stringConverter ); CNV.put(Object.class, new Converter() { public Object convert(Object o) { return stringConverter.convert(valueOf(o)); } } ); CNV.put(BigDecimal.class, new Converter() { public Float convert(Object o) { return ((BigDecimal) o).floatValue(); } } ); CNV.put(BigInteger.class, new Converter() { public Float convert(Object o) { return ((BigInteger) o).floatValue(); } } ); CNV.put(Float.class, new Converter() { public Object convert(Object o) { return o; } } ); CNV.put(Integer.class, new Converter() { public Float convert(Object o) { //noinspection UnnecessaryBoxing return ((Integer) o).floatValue(); } } ); CNV.put(Double.class, new Converter() { public Float convert(Object o) { return ((Double) o).floatValue(); } } ); CNV.put(Long.class, new Converter() { public Float convert(Object o) { return ((Long) o).floatValue(); } } ); CNV.put(Short.class, new Converter() { public Float convert(Object o) { return ((Short) o).floatValue(); } } ); CNV.put(Boolean.class, new Converter() { public Float convert(Object o) { if ((Boolean) o) return 1f; else return 0f; } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/CharCH.java0000644000175000017500000000553011077457613024006 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.String.valueOf; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; public class CharCH implements ConversionHandler { private static final Map CNV = new HashMap(); private static final Converter stringConverter = new Converter() { public Object convert(Object o) { if ((((String) o).length()) > 1) throw new ConversionException("cannot convert a string with a length greater than 1 to java.lang.Character"); return (((String) o)).charAt(0); } }; public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Integer.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String.class, stringConverter); CNV.put(Object.class, new Converter() { public Object convert(Object o) { return stringConverter.convert(valueOf(o)); } } ); CNV.put(Character.class, new Converter() { public Object convert(Object o) { //noinspection UnnecessaryBoxing return new Character(((Character) o)); } } ); CNV.put(BigDecimal.class, new Converter() { public Object convert(Object o) { return (char) ((BigDecimal) o).intValue(); } } ); CNV.put(Integer.class, new Converter() { public Object convert(Object o) { return (char) ((Integer) o).intValue(); } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/Converter.java0000644000175000017500000000140511077457613024662 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; public interface Converter { public Object convert(Object o); } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/ShortCH.java0000644000175000017500000001267511077457613024240 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.Short.parseShort; import static java.lang.String.valueOf; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class ShortCH implements ConversionHandler { /** * This is purely because Eclipse sucks, and has a serious bug with * it's java parser. */ private static final Short TRUE = (short) 1; private static final Short FALSE = (short) 0; private static Converter stringConverter = new Converter() { public Short convert(Object o) { return parseShort(((String) o)); } }; private static final Map CNV = new HashMap(); public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Short.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String.class, stringConverter ); CNV.put(Object.class, new Converter() { public Object convert(Object o) { return stringConverter.convert(valueOf(o)); } } ); CNV.put(BigDecimal.class, new Converter() { public Short convert(Object o) { return ((BigDecimal) o).shortValue(); } } ); CNV.put(BigInteger.class, new Converter() { public Short convert(Object o) { return ((BigInteger) o).shortValue(); } } ); CNV.put(Short.class, new Converter() { public Object convert(Object o) { return o; } } ); CNV.put(Integer.class, new Converter() { public Short convert(Object o) { if (((Integer) o) > Short.MAX_VALUE) { throw new ConversionException("cannot coerce Integer to Short since the value (" + valueOf(o) + ") exceeds that maximum precision of Integer."); } else { return ((Integer) o).shortValue(); } } } ); CNV.put(Float.class, new Converter() { public Short convert(Object o) { if (((Float) o) > Short.MAX_VALUE) { throw new ConversionException("cannot coerce Float to Short since the value (" + valueOf(o) + ") exceeds that maximum precision of Integer."); } else { return ((Float) o).shortValue(); } } } ); CNV.put(Double.class, new Converter() { public Short convert(Object o) { if (((Double) o) > Short.MAX_VALUE) { throw new ConversionException("cannot coerce Double to Short since the value (" + valueOf(o) + ") exceeds that maximum precision of Integer."); } else { return ((Double) o).shortValue(); } } } ); CNV.put(Long.class, new Converter() { public Short convert(Object o) { if (((Long) o) > Short.MAX_VALUE) { throw new ConversionException("cannot coerce Integer to Short since the value (" + valueOf(o) + ") exceeds that maximum precision of Integer."); } else { return ((Long) o).shortValue(); } } } ); CNV.put(Boolean.class, new Converter() { public Short convert(Object o) { if ((Boolean) o) return TRUE; else { return FALSE; } } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/BooleanCH.java0000644000175000017500000000755111077457613024515 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.String.valueOf; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; public class BooleanCH implements ConversionHandler { private static final Map CNV = new HashMap(); private static Converter stringConverter = new Converter() { public Object convert(Object o) { return !(((String) o).equalsIgnoreCase("false") || (((String) o).equalsIgnoreCase("no")) || (((String) o).equalsIgnoreCase("off")) || ("0".equals(o)) || ("".equals(o))); } }; public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Boolean.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String.class, stringConverter ); CNV.put(Object.class, new Converter() { public Object convert(Object o) { return stringConverter.convert(valueOf(o)); } } ); CNV.put(Boolean.class, new Converter() { public Object convert(Object o) { return o; } } ); CNV.put(Integer.class, new Converter() { public Boolean convert(Object o) { return (((Integer) o) > 0); } } ); CNV.put(Float.class, new Converter() { public Boolean convert(Object o) { return (((Float) o) > 0); } } ); CNV.put(Double.class, new Converter() { public Boolean convert(Object o) { return (((Double) o) > 0); } } ); CNV.put(Short.class, new Converter() { public Boolean convert(Object o) { return (((Short) o) > 0); } } ); CNV.put(Long.class, new Converter() { public Boolean convert(Object o) { return (((Long) o) > 0); } } ); CNV.put(boolean.class, new Converter() { public Boolean convert(Object o) { return Boolean.valueOf((Boolean) o); } } ); CNV.put(BigDecimal.class, new Converter() { public Boolean convert(Object o) { return Boolean.valueOf(((BigDecimal) o).doubleValue() > 0); } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/ListCH.java0000644000175000017500000000306711272124620024031 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class ListCH implements ConversionHandler { public Object convertFrom(Object in) { Class type = in.getClass(); List newList = new ArrayList(); if (type.isArray()) { newList.addAll(Arrays.asList(((Object[]) in))); } else if (Collection.class.isAssignableFrom(type)) { newList.addAll((Collection) in); } else if (Iterable.class.isAssignableFrom(type)) { for (Object o : (Iterable) in) { newList.add(o); } } return newList; } public boolean canConvertFrom(Class cls) { return cls.isArray() || Collection.class.isAssignableFrom(cls) || Iterable.class.isAssignableFrom(cls); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/LongCH.java0000644000175000017500000000766611357161555024042 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.String.valueOf; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class LongCH implements ConversionHandler { private static final Map CNV = new HashMap(); private static Converter stringConverter = new Converter() { public Object convert(Object o) { if (((String) o).length() == 0) return (long) 0; return Long.parseLong(((String) o)); } }; public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Long.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String.class, stringConverter ); CNV.put(Object.class, new Converter() { public Object convert(Object o) { return stringConverter.convert(valueOf(o)); } } ); CNV.put(BigDecimal.class, new Converter() { public Long convert(Object o) { return ((BigDecimal) o).longValue(); } } ); CNV.put(BigInteger.class, new Converter() { public Long convert(Object o) { return ((BigInteger) o).longValue(); } } ); CNV.put(Short.class, new Converter() { public Object convert(Object o) { //noinspection UnnecessaryBoxing return ((Short) o).longValue(); } } ); CNV.put(Long.class, new Converter() { public Object convert(Object o) { //noinspection UnnecessaryBoxing return new Long(((Long) o)); } } ); CNV.put(Integer.class, new Converter() { public Object convert(Object o) { //noinspection UnnecessaryBoxing return ((Integer) o).longValue(); } } ); CNV.put(Double.class, new Converter() { public Object convert(Object o) { return ((Double) o).longValue(); } }); CNV.put(Float.class, new Converter() { public Object convert(Object o) { return ((Float) o).longValue(); } }); CNV.put(Boolean.class, new Converter() { public Long convert(Object o) { if ((Boolean) o) return 1l; else return 0l; } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/ObjectCH.java0000644000175000017500000000165411077457613024342 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionHandler; public class ObjectCH implements ConversionHandler { public Object convertFrom(Object in) { return in; } public boolean canConvertFrom(Class cls) { return true; } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/CharArrayCH.java0000644000175000017500000000310611077457613025002 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import java.util.HashMap; import java.util.Map; public class CharArrayCH implements ConversionHandler { private static final Map CNV = new HashMap(); public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Boolean.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String.class, new Converter() { public Object convert(Object o) { return ((String) o).toCharArray(); } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/ByteCH.java0000644000175000017500000000455211217722234024025 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.String.valueOf; import java.util.HashMap; import java.util.Map; public class ByteCH implements ConversionHandler { private static final Map CNV = new HashMap(); private static Converter stringConverter = new Converter() { public Object convert(Object o) { return Byte.parseByte(((String) o)); } }; public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Integer.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String.class, stringConverter ); CNV.put(Object.class, new Converter() { public Object convert(Object o) { return stringConverter.convert(valueOf(o)); } } ); CNV.put(Byte.class, new Converter() { public Object convert(Object o) { //noinspection UnnecessaryBoxing return new Byte(((Byte) o)); } } ); CNV.put(Integer.class, new Converter() { public Object convert(Object o) { return (byte) ((Integer)o).intValue(); } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/StringCH.java0000644000175000017500000000203311077457613024372 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionHandler; import org.mvel2.compiler.BlankLiteral; import static java.lang.String.valueOf; public class StringCH implements ConversionHandler { public Object convertFrom(Object in) { return valueOf(in); } public boolean canConvertFrom(Class cls) { return cls != BlankLiteral.class; } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/PrimIntArrayCH.java0000644000175000017500000000533111077457613025511 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import java.util.HashMap; import java.util.Map; public class PrimIntArrayCH implements ConversionHandler { private static final Map CNV = new HashMap(); public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Boolean.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String[].class, new Converter() { public Object convert(Object o) { String[] old = (String[]) o; int[] n = new int[old.length]; for (int i = 0; i < old.length; i++) { n[i] = Integer.parseInt(old[i]); } return n; } } ); CNV.put(Object[].class, new Converter() { public Object convert(Object o) { Object[] old = (Object[]) o; int[] n = new int[old.length]; for (int i = 0; i < old.length; i++) { n[i] = Integer.parseInt(String.valueOf(old[i])); } return n; } } ); CNV.put(Integer[].class, new Converter() { public Object convert(Object o) { Integer[] old = (Integer[]) o; int[] n = new int[old.length]; for (int i = 0; i < old.length; i++) { n[i] = old[i]; } return n; } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/UnitConversion.java0000644000175000017500000000312611077457613025702 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionHandler; import org.mvel2.Unit; public class UnitConversion implements ConversionHandler { public Object convertFrom(Object in) { try { return Unit.class.newInstance().convertFrom(in); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } public boolean canConvertFrom(Class cls) { if (Unit.class.isAssignableFrom(cls) || Number.class.isAssignableFrom(cls)) { try { return Unit.class.newInstance().canConvertFrom(cls); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/StringArrayCH.java0000644000175000017500000000371111077457613025375 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionHandler; import java.util.HashMap; import java.util.Map; public class StringArrayCH implements ConversionHandler { private static final Map CNV = new HashMap(); public Object convertFrom(Object in) { if (in.getClass().isArray()) { Object[] old = (Object[]) in; String[] n = new String[old.length]; for (int i = 0; i < old.length; i++) { n[i] = String.valueOf(old[i]); } return n; } else { return new String[]{String.valueOf(in)}; } // return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(Object[].class, new Converter() { public Object convert(Object o) { Object[] old = (Object[]) o; String[] n = new String[old.length]; for (int i = 0; i < old.length; i++) { n[i] = String.valueOf(old[i]); } return n; } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/IntegerCH.java0000644000175000017500000001240211105441054024502 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.Integer.parseInt; import static java.lang.String.valueOf; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class IntegerCH implements ConversionHandler { private static final Map CNV = new HashMap(10); public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Integer.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(Object.class, new Converter() { public Object convert(Object o) { if (((String) o).length() == 0) return 0; return parseInt(valueOf(o)); } } ); CNV.put(BigDecimal.class, new Converter() { public Integer convert(Object o) { return ((BigDecimal) o).intValue(); } } ); CNV.put(BigInteger.class, new Converter() { public Integer convert(Object o) { return ((BigInteger) o).intValue(); } } ); CNV.put(String.class, new Converter() { public Object convert(Object o) { return parseInt(((String) o)); } } ); CNV.put(Short.class, new Converter() { public Object convert(Object o) { return ((Short) o).intValue(); } } ); CNV.put(Long.class, new Converter() { public Object convert(Object o) { //noinspection UnnecessaryBoxing if (((Long) o) > Integer.MAX_VALUE) { throw new ConversionException("cannot coerce Long to Integer since the value (" + valueOf(o) + ") exceeds that maximum precision of Integer."); } else { return ((Long) o).intValue(); } } } ); CNV.put(Float.class, new Converter() { public Object convert(Object o) { //noinspection UnnecessaryBoxing if (((Float) o) > Integer.MAX_VALUE) { throw new ConversionException("cannot coerce Float to Integer since the value (" + valueOf(o) + ") exceeds that maximum precision of Integer."); } else { return ((Float) o).intValue(); } } } ); CNV.put(Double.class, new Converter() { public Object convert(Object o) { //noinspection UnnecessaryBoxing if (((Double) o) > Integer.MAX_VALUE) { throw new ConversionException("cannot coerce Long to Integer since the value (" + valueOf(o) + ") exceeds that maximum precision of Integer."); } else { return ((Double) o).intValue(); } } } ); CNV.put(Integer.class, new Converter() { public Object convert(Object o) { return o; } } ); CNV.put(Boolean.class, new Converter() { public Integer convert(Object o) { if ((Boolean) o) return 1; else return 0; } } ); CNV.put(Character.class, new Converter() { public Integer convert(Object o) { return (int) ((Character) o).charValue(); } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/ArrayCH.java0000644000175000017500000000542611077457613024213 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import static java.lang.Integer.parseInt; import static java.lang.String.valueOf; import java.util.HashMap; import java.util.Map; public class ArrayCH implements ConversionHandler { private static final Map CNV = new HashMap(); public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Boolean.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(String[].class, new Converter() { public Object convert(Object o) { Object[] old = (Object[]) o; String[] n = new String[old.length]; for (int i = 0; i < old.length; i++) { n[i] = valueOf(old[i]); } return n; } } ); CNV.put(Integer[].class, new Converter() { public Object convert(Object o) { Object[] old = (Object[]) o; Integer[] n = new Integer[old.length]; for (int i = 0; i < old.length; i++) { n[i] = parseInt(valueOf(old[i])); } return n; } }); CNV.put(int[].class, new Converter() { public Object convert(Object o) { Object[] old = (Object[]) o; int[] n = new int[old.length]; for (int i = 0; i < old.length; i++) { n[i] = parseInt(valueOf(old[i])); } return n; } }); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/SetCH.java0000644000175000017500000000306611272124620023650 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionHandler; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; public class SetCH implements ConversionHandler { public Object convertFrom(Object in) { Class type = in.getClass(); Set newSet = new LinkedHashSet(); if (type.isArray()) { newSet.addAll(Arrays.asList(((Object[]) in))); } else if (Collection.class.isAssignableFrom(type)) { newSet.addAll((Collection) in); } else if (Iterable.class.isAssignableFrom(type)) { for (Object o : (Iterable) in) { newSet.add(o); } } return newSet; } public boolean canConvertFrom(Class cls) { return cls.isArray() || Collection.class.isAssignableFrom(cls) || Iterable.class.isAssignableFrom(cls); } } mvel-2.0.18.orig/src/main/java/org/mvel2/conversion/BigDecimalCH.java0000644000175000017500000001042111077457613025104 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.conversion; import org.mvel2.ConversionException; import org.mvel2.ConversionHandler; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.HashMap; import java.util.Map; public class BigDecimalCH implements ConversionHandler { private static final Map CNV = new HashMap(); public Object convertFrom(Object in) { if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: " + in.getClass().getName() + " to: " + Integer.class.getName()); return CNV.get(in.getClass()).convert(in); } public boolean canConvertFrom(Class cls) { return CNV.containsKey(cls); } static { CNV.put(Object.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal(String.valueOf(o), MathContext.DECIMAL128); } } ); CNV.put(BigDecimal.class, new Converter() { public BigDecimal convert(Object o) { return (BigDecimal) o; } } ); CNV.put(BigInteger.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal(((BigInteger) o).doubleValue(), MathContext.DECIMAL128); } } ); CNV.put(String.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal((String) o, MathContext.DECIMAL128); } } ); CNV.put(Double.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal(((Double) o).doubleValue(), MathContext.DECIMAL128); } } ); CNV.put(Float.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal(((Float) o).doubleValue(), MathContext.DECIMAL128); } } ); CNV.put(Short.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal(((Short) o).doubleValue(), MathContext.DECIMAL128); } } ); CNV.put(Long.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal(((Long) o).doubleValue(), MathContext.DECIMAL128); } } ); CNV.put(Integer.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal(((Integer) o).doubleValue(), MathContext.DECIMAL128); } } ); CNV.put(String.class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal((String) o, MathContext.DECIMAL128); } } ); CNV.put(char[].class, new Converter() { public BigDecimal convert(Object o) { return new BigDecimal((char[]) o, MathContext.DECIMAL128); } } ); } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/0000755000175000017500000000000011412747050022174 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/integration/VariableResolver.java0000644000175000017500000000450111077457613026320 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration; import java.io.Serializable; /** * A variable resolver is responsible for physically accessing a variable, for either read or write. VariableResolver's * are obtained via a {@link org.mvel2.integration.VariableResolverFactory}. */ public interface VariableResolver extends Serializable { /** * Returns the name of external variable. * * @return A string representing the variable name. */ public String getName(); /** * This should return the type of the variable. However, this is not completely necessary, and is particularily * only of benefit to systems that require use of MVEL's strict typing facilities. In most cases, this implementation * can simply return: Object.class * * @return A Class instance representing the type of the target variable. */ public Class getType(); /* * If this is a declared variable of a static type, MVEL will make it known by passing the type here. */ public void setStaticType(Class type); /** * Returns the bitset of special variable flags. Internal use only. This should just return 0 in custom * implentations. * * @return Bitset of special flags. */ public int getFlags(); /** * Returns the physical target value of the variable. * * @return The actual variable value. */ public Object getValue(); /** * Sets the value of the physical target value. * * @param value The new value. * @return value after any conversion */ public void setValue(Object value); } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/Interceptor.java0000644000175000017500000000371111100166032025324 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration; import org.mvel2.ast.ASTNode; /** * An interceptor can be used to decorate functionality into an expression or to hook into external functionality, such * as to log an event or fire some other event. * * @author Christopher Brock */ public interface Interceptor { public static final int NORMAL_FLOW = 0; public static final int SKIP = 1; public static final int END = 2; /** * This method is executed before the wrapped statement. * * @param node The ASTNode wrapped by the interceptor * @param factory The variable factory * @return The response code. Should return 0. */ public int doBefore(ASTNode node, VariableResolverFactory factory); /** * This method is called after the wrapped statement has completed. A copy of the top-value of the execution * stack is also availablehere. * * @param exitStackValue The value on the top of the stack after executing the statement. * @param node The ASTNode wrapped by the interceptor * @param factory The variable factory * @return The response code. Should return 0. */ public int doAfter(Object exitStackValue, ASTNode node, VariableResolverFactory factory); } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/PropertyHandler.java0000644000175000017500000000360311077457613026175 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration; /** * This interface allows an external property handler to resolve a property against the provided context. * * @see org.mvel2.optimizers.impl.asm.ProducesBytecode */ public interface PropertyHandler { /** * Retrieves the value of the property. * * @param name - the name of the property to be resolved. * @param contextObj - the current context object. * @param variableFactory - the root variable factory provided by the runtime. * @return - the value of the property. */ public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory); /** * Sets the value of the property. * * @param name - the name of the property to be resolved. * @param contextObj - the current context object. * @param variableFactory - the root variable factory provided by the runtime. * @param value - the value to be set to the resolved property * @return - the resultant value of the property (should normally be the same as the value passed) */ public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value); } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/GlobalListenerFactory.java0000644000175000017500000000324111122037043027265 0ustar drazzibdrazzibpackage org.mvel2.integration; import java.util.List; import java.util.LinkedList; public class GlobalListenerFactory { private static List propertyGetListeners; private static List propertySetListeners; public static boolean hasGetListeners() { return propertyGetListeners != null && !propertyGetListeners.isEmpty(); } public static boolean hasSetListeners() { return propertySetListeners != null && !propertySetListeners.isEmpty(); } public static boolean registerGetListener(Listener getListener) { if (propertyGetListeners == null) propertyGetListeners = new LinkedList(); return propertyGetListeners.add(getListener); } public static boolean registerSetListener(Listener getListener) { if (propertySetListeners == null) propertySetListeners = new LinkedList(); return propertySetListeners.add(getListener); } public static void notifyGetListeners(Object target, String name, VariableResolverFactory variableFactory) { if (propertyGetListeners != null) { for (Listener l : propertyGetListeners) { l.onEvent(target, name, variableFactory, null); } } } public static void notifySetListeners(Object target, String name, VariableResolverFactory variableFactory, Object value) { if (propertySetListeners != null) { for (Listener l : propertySetListeners) { l.onEvent(target, name, variableFactory, value); } } } public static void disposeAll() { propertyGetListeners = null; propertySetListeners = null; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/Listener.java0000644000175000017500000000026211121621456024622 0ustar drazzibdrazzibpackage org.mvel2.integration; public interface Listener { public void onEvent(Object context, String contextName, VariableResolverFactory variableFactory, Object value); } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/ResolverTools.java0000644000175000017500000000437611077457613025705 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration; /** * A set of tools for dealing with factorys, specifically to make chaining issues easy to deal with. * * @author Christopher Brock */ public class ResolverTools { /** * Based on a root factory, append the new factory to the end of the chain. * * @param root The root factory * @param newFactory The new factory * @return An instance of the new factory */ public static T appendFactory(VariableResolverFactory root, T newFactory) { if (root.getNextFactory() == null) { root.setNextFactory(newFactory); } else { VariableResolverFactory vrf = root; while (vrf.getNextFactory() != null) { vrf = vrf.getNextFactory(); } vrf.setNextFactory(newFactory); } return newFactory; } /** * Based on the root factory, insert the new factory right after the root, and before any other in the chain. * * @param root The root factory * @param newFactory The new factory * @return An instance of the new factory. */ public static T insertFactory(VariableResolverFactory root, T newFactory) { if (root.getNextFactory() == null) { root.setNextFactory(newFactory); } else { newFactory.setNextFactory(root.getNextFactory()); root.setNextFactory(newFactory); } return newFactory; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/PropertyHandlerFactory.java0000644000175000017500000000650311236144601027512 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration; import java.util.HashMap; import java.util.Map; public class PropertyHandlerFactory { protected static Map propertyHandlerClass = new HashMap(); protected static PropertyHandler nullPropertyHandler; protected static PropertyHandler nullMethodHandler; public static PropertyHandler getPropertyHandler(Class clazz) { return propertyHandlerClass.get(clazz); } public static boolean hasPropertyHandler(Class clazz) { if (clazz == null) return false; if (!propertyHandlerClass.containsKey(clazz)) { Class clazzWalk = clazz; do { if (clazz != clazzWalk && propertyHandlerClass.containsKey(clazzWalk)) { propertyHandlerClass.put(clazz, propertyHandlerClass.get(clazzWalk)); return true; } for (Class c : clazzWalk.getInterfaces()) { if (propertyHandlerClass.containsKey(c)) { propertyHandlerClass.put(clazz, propertyHandlerClass.get(c)); return true; } } } while ((clazzWalk = clazzWalk.getSuperclass()) != null && clazzWalk != Object.class); return false; } else { return true; } } public static void registerPropertyHandler(Class clazz, PropertyHandler propertyHandler) { do { propertyHandlerClass.put(clazz, propertyHandler); for (Class c : clazz.getInterfaces()) { propertyHandlerClass.put(c, propertyHandler); } } while ((clazz = clazz.getSuperclass()) != null && clazz != Object.class); } public static void setNullPropertyHandler(PropertyHandler handler) { nullPropertyHandler = handler; } public static boolean hasNullPropertyHandler() { return nullPropertyHandler != null; } public static PropertyHandler getNullPropertyHandler() { return nullPropertyHandler; } public static void setNullMethodHandler(PropertyHandler handler) { nullMethodHandler = handler; } public static boolean hasNullMethodHandler() { return nullMethodHandler != null; } public static PropertyHandler getNullMethodHandler() { return nullMethodHandler; } public static void unregisterPropertyHandler(Class clazz) { propertyHandlerClass.remove(clazz); } public static void disposeAll() { nullMethodHandler = null; nullPropertyHandler = null; propertyHandlerClass.clear(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/VariableResolverFactory.java0000644000175000017500000001066711077457613027662 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration; import java.io.Serializable; import java.util.Set; /** * A VariableResolverFactory is the primary integration point for tying in external variables. The factory is * responsible for returing {@link org.mvel2.integration.VariableResolver}'s to the MVEL runtime. Factories are * also structured in a chain to maintain locality-of-reference. */ public interface VariableResolverFactory extends Serializable { /** * Creates a new variable. This probably doesn't need to be implemented in most scenarios. This is * used for variable assignment. * * @param name - name of the variable being created * @param value - value of the variable * @return instance of the variable resolver associated with the variable */ public VariableResolver createVariable(String name, Object value); public VariableResolver createIndexedVariable(int index, String name, Object value); /** * Creates a new variable, and assigns a static type. It is expected the underlying factory and resolver * will enforce this. * * @param name - name of the variable being created * @param value - value of the variable * @param type - the static type * @return instance of the variable resolver associated with the variable */ public VariableResolver createVariable(String name, Object value, Class type); public VariableResolver createIndexedVariable(int index, String name, Object value, Class typee); public VariableResolver setIndexedVariableResolver(int index, VariableResolver variableResolver); /** * Returns the next factory in the factory chain. MVEL uses a hierarchical variable resolution strategy, * much in the same way as Classloaders in Java. For performance reasons, it is the responsibility of * the individual VariableResolverFactory to pass off to the next one. * * @return instance of the next factory - null if none. */ public VariableResolverFactory getNextFactory(); /** * Sets the next factory in the chain. Proper implementation: * *

* return this.nextFactory = resolverFactory; * * * @param resolverFactory - instance of next resolver factory * @return - instance of next resolver factory */ public VariableResolverFactory setNextFactory(VariableResolverFactory resolverFactory); /** * Return a variable resolver for the specified variable name. This method is expected to traverse the * heirarchy of ResolverFactories. * * @param name - variable name * @return - instance of the VariableResolver for the specified variable */ public VariableResolver getVariableResolver(String name); public VariableResolver getIndexedVariableResolver(int index); /** * Deterimines whether or not the current VariableResolverFactory is the physical target for the actual * variable. * * @param name - variable name * @return - boolean indicating whether or not factory is the physical target */ public boolean isTarget(String name); /** * Determines whether or not the variable is resolver in the chain of factories. * * @param name - variable name * @return - boolean */ public boolean isResolveable(String name); /** * Return a list of known variables inside the factory. This method should not recurse into other factories. * But rather return only the variables living inside this factory. * * @return */ public Set getKnownVariables(); public int variableIndexOf(String name); public boolean isIndexedFactory(); } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/0000755000175000017500000000000011412747047023143 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/LocalVariableResolverFactory.java0000644000175000017500000000141611077457613031566 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; public interface LocalVariableResolverFactory { } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/ItemResolverFactory.java0000644000175000017500000000556611077457613027776 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; public class ItemResolverFactory extends BaseVariableResolverFactory { private final ItemResolver resolver; public ItemResolverFactory(ItemResolver resolver, VariableResolverFactory nextFactory) { this.resolver = resolver; this.nextFactory = nextFactory; } public VariableResolver createVariable(String name, Object value) { if (isTarget(name)) { resolver.setValue(value); return resolver; } else { return nextFactory.createVariable(name, value); } } public VariableResolver createVariable(String name, Object value, Class type) { if (isTarget(name)) { throw new RuntimeException("variable already defined in scope: " + name); } else { return nextFactory.createVariable(name, value); } } public VariableResolver getVariableResolver(String name) { return isTarget(name) ? resolver : nextFactory.getVariableResolver(name); } public boolean isTarget(String name) { return resolver.getName().equals(name); } public boolean isResolveable(String name) { return resolver.getName().equals(name) || (nextFactory != null && nextFactory.isResolveable(name)); } public static class ItemResolver implements VariableResolver { private final String name; private Class type = Object.class; public Object value; public ItemResolver(String name, Class type) { this.name = name; this.type = type; } public ItemResolver(String name) { this.name = name; } public String getName() { return name; } public Class getType() { return type; } public void setStaticType(Class type) { this.type = type; } public int getFlags() { return 0; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/MapVariableResolver.java0000644000175000017500000000537311257005261027713 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.CompileException; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import org.mvel2.integration.VariableResolver; import java.util.Map; import java.util.HashMap; public class MapVariableResolver implements VariableResolver { private String name; private Class knownType; private Map variableMap; public MapVariableResolver(Map variableMap, String name) { this.variableMap = variableMap; this.name = name; } public MapVariableResolver(Map variableMap, String name, Class knownType) { this.name = name; this.knownType = knownType; this.variableMap = variableMap; } public void setName(String name) { this.name = name; } public void setStaticType(Class knownType) { this.knownType = knownType; } public void setVariableMap(Map variableMap) { this.variableMap = variableMap; } public String getName() { return name; } public Class getType() { return knownType; } public void setValue(Object value) { if (knownType != null && value != null && value.getClass() != knownType) { if (!canConvert(knownType, value.getClass())) { throw new CompileException("cannot assign " + value.getClass().getName() + " to type: " + knownType.getName()); } try { value = convert(value, knownType); } catch (Exception e) { throw new CompileException("cannot convert value of " + value.getClass().getName() + " to: " + knownType.getName()); } } //noinspection unchecked variableMap.put(name, value); } public Object getValue() { return variableMap.get(name); } public int getFlags() { return 0; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/ClassImportResolver.java0000644000175000017500000000347111147075773030002 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.CompileException; import org.mvel2.integration.VariableResolver; public class ClassImportResolver implements VariableResolver { private String name; private Class type; public ClassImportResolver(String fqcn, String name) { this.name = name; try { this.type = Class.forName(fqcn, true, Thread.currentThread().getContextClassLoader()); } catch (Exception e) { throw new CompileException("failed import", e); } } public ClassImportResolver(String name, Class type) { this.name = name; this.type = type; } public void setName(String name) { this.name = name; } public void setStaticType(Class knownType) { this.type = knownType; } public String getName() { return name; } public Class getType() { return Class.class; } public Object getValue() { return type; } public int getFlags() { return 0; } public void setValue(Object value) { } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/FunctionVariableResolverFactory.java0000644000175000017500000001476511257005261032320 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.CompileException; import org.mvel2.ast.Function; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import java.util.HashMap; public class FunctionVariableResolverFactory extends BaseVariableResolverFactory implements LocalVariableResolverFactory { private Function function; public FunctionVariableResolverFactory(Function function, VariableResolverFactory nextFactory, String[] indexedVariables, Object[] parameters) { this.function = function; this.variableResolvers = new HashMap(); this.nextFactory = nextFactory; this.indexedVariableResolvers = new VariableResolver[(this.indexedVariableNames = indexedVariables).length]; for (int i = 0; i < parameters.length; i++) { variableResolvers.put(indexedVariableNames[i], null); this.indexedVariableResolvers[i] = new SimpleValueResolver(parameters[i]); // variableResolvers.put(indexedVariableNames[i], this.indexedVariableResolvers[i] = new SimpleValueResolver(parameters[i])); } } public boolean isResolveable(String name) { return variableResolvers.containsKey(name) || (nextFactory != null && nextFactory.isResolveable(name)); } public VariableResolver createVariable(String name, Object value) { VariableResolver resolver = getVariableResolver(name); if (resolver == null) { int idx = increaseRegisterTableSize(); this.indexedVariableNames[idx] = name; this.indexedVariableResolvers[idx] = new SimpleValueResolver(value); variableResolvers.put(name, null); // variableResolvers.put(name, this.indexedVariableResolvers[idx] = new SimpleValueResolver(value)); return this.indexedVariableResolvers[idx]; } else { resolver.setValue(value); return resolver; } } public VariableResolver createVariable(String name, Object value, Class type) { VariableResolver vr = this.variableResolvers != null ? this.variableResolvers.get(name) : null; if (vr != null && vr.getType() != null) { throw new CompileException("variable already defined within scope: " + vr.getType() + " " + name); } else { return createIndexedVariable(variableIndexOf(name), name, value); } } public VariableResolver createIndexedVariable(int index, String name, Object value) { index = index - indexOffset; if (indexedVariableResolvers[index] != null) { indexedVariableResolvers[index].setValue(value); } else { indexedVariableResolvers[index] = new SimpleValueResolver(value); } variableResolvers.put(name, null); return indexedVariableResolvers[index]; } public VariableResolver createIndexedVariable(int index, String name, Object value, Class type) { index = index - indexOffset; if (indexedVariableResolvers[index] != null) { indexedVariableResolvers[index].setValue(value); } else { indexedVariableResolvers[index] = new SimpleValueResolver(value); } return indexedVariableResolvers[index]; } public VariableResolver getIndexedVariableResolver(int index) { if (indexedVariableResolvers[index] == null) { /** * If the register is null, this means we need to forward-allocate the variable onto the * register table. */ return indexedVariableResolvers[index] = super.getVariableResolver(indexedVariableNames[index]); } return indexedVariableResolvers[index]; } public VariableResolver getVariableResolver(String name) { int idx; // if (variableResolvers.containsKey(name)) return variableResolvers.get(name); if ((idx = variableIndexOf(name)) != -1) { if (indexedVariableResolvers[idx] == null) { indexedVariableResolvers[idx] = new SimpleValueResolver(null); } variableResolvers.put(indexedVariableNames[idx], null); return indexedVariableResolvers[idx]; } return super.getVariableResolver(name); } public boolean isIndexedFactory() { return true; } public boolean isTarget(String name) { return variableResolvers.containsKey(name) || variableIndexOf(name) != -1; } private int increaseRegisterTableSize() { String[] oldNames = indexedVariableNames; VariableResolver[] oldResolvers = indexedVariableResolvers; int newLength = oldNames.length + 1; indexedVariableNames = new String[newLength]; indexedVariableResolvers = new VariableResolver[newLength]; for (int i = 0; i < oldNames.length; i++) { indexedVariableNames[i] = oldNames[i]; indexedVariableResolvers[i] = oldResolvers[i]; } return newLength - 1; } public void updateParameters(Object[] parameters) { // this.indexedVariableResolvers = new VariableResolver[parameters.length]; for (int i = 0; i < parameters.length; i++) { this.indexedVariableResolvers[i] = new SimpleValueResolver(parameters[i]); } // for (int i = parameters.length; i < indexedVariableResolvers.length; i++) { // this.indexedVariableResolvers[i] = null; // } } public VariableResolver[] getIndexedVariableResolvers() { return this.indexedVariableResolvers; } public void setIndexedVariableResolvers(VariableResolver[] vr) { this.indexedVariableResolvers = vr; } public Function getFunction() { return function; } public void setIndexOffset(int offset) { this.indexOffset = offset; } }mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/MapVariableResolverFactory.java0000644000175000017500000001036711253272603031244 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.CompileException; import org.mvel2.UnresolveablePropertyException; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; @SuppressWarnings({"unchecked"}) public class MapVariableResolverFactory extends BaseVariableResolverFactory { /** * Holds the instance of the variables. */ protected Map variables; public MapVariableResolverFactory() { } public MapVariableResolverFactory(Map variables) { this.variables = variables; } public MapVariableResolverFactory(Map variables, VariableResolverFactory nextFactory) { this.variables = variables; this.nextFactory = nextFactory; } public MapVariableResolverFactory(Map variables, boolean cachingSafe) { this.variables = variables; } public VariableResolver createVariable(String name, Object value) { VariableResolver vr; try { (vr = getVariableResolver(name)).setValue(value); return vr; } catch (UnresolveablePropertyException e) { addResolver(name, vr = new MapVariableResolver(variables, name)).setValue(value); return vr; } } public VariableResolver createVariable(String name, Object value, Class type) { VariableResolver vr; try { vr = getVariableResolver(name); } catch (UnresolveablePropertyException e) { vr = null; } if (vr != null && vr.getType() != null) { throw new CompileException("variable already defined within scope: " + vr.getType() + " " + name); } else { addResolver(name, vr = new MapVariableResolver(variables, name, type)).setValue(value); return vr; } } public VariableResolver getVariableResolver(String name) { VariableResolver vr = variableResolvers.get(name); if (vr != null) { return vr; } else if (variables.containsKey(name)) { variableResolvers.put(name, vr = new MapVariableResolver(variables, name)); return vr; } else if (nextFactory != null) { return nextFactory.getVariableResolver(name); } throw new UnresolveablePropertyException("unable to resolve variable '" + name + "'"); } public boolean isResolveable(String name) { return (variableResolvers.containsKey(name)) || (variables != null && variables.containsKey(name)) || (nextFactory != null && nextFactory.isResolveable(name)); } protected VariableResolver addResolver(String name, VariableResolver vr) { variableResolvers.put(name, vr); return vr; } public boolean isTarget(String name) { return variableResolvers.containsKey(name); } public Set getKnownVariables() { if (nextFactory == null) { if (variables != null) return new HashSet(variables.keySet()); return new HashSet(0); } else { if (variables != null) return new HashSet(variables.keySet()); return new HashSet(0); } } public void clear() { variableResolvers.clear(); variables.clear(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/IndexedVariableResolverFactory.java0000644000175000017500000001027411244550175032107 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.UnresolveablePropertyException; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import java.util.HashSet; import java.util.Set; @SuppressWarnings({"unchecked"}) public class IndexedVariableResolverFactory extends BaseVariableResolverFactory { /** * Holds the instance of the variables. */ private Object[] values; public IndexedVariableResolverFactory(String[] varNames, Object[] values) { this.indexedVariableNames = varNames; this.values = values; // this.nextFactory = new MapVariableResolverFactory(); this.indexedVariableResolvers = createResolvers(values); } public IndexedVariableResolverFactory(String[] varNames, Object[] values, VariableResolverFactory nextFactory) { this.indexedVariableNames = varNames; this.values = values; this.nextFactory = new MapVariableResolverFactory(); this.nextFactory.setNextFactory(nextFactory); this.indexedVariableResolvers = createResolvers(values); } private static VariableResolver[] createResolvers(Object[] values) { VariableResolver[] vr = new VariableResolver[values.length]; for (int i = 0; i < values.length; i++) { vr[i] = new IndexVariableResolver(i, values); } return vr; } public VariableResolver createIndexedVariable(int index, String name, Object value) { throw new RuntimeException("Error: cannot write to factory"); } public VariableResolver getIndexedVariableResolver(int index) { return indexedVariableResolvers[index]; } public VariableResolver createVariable(String name, Object value) { return nextFactory.createVariable(name, value); } public VariableResolver createVariable(String name, Object value, Class type) { if (nextFactory == null) nextFactory = new MapVariableResolverFactory(); return nextFactory.createVariable(name, value, type); } public VariableResolver getVariableResolver(String name) { VariableResolver vr = getResolver(name); if (vr != null) return vr; else if (nextFactory != null) { return nextFactory.getVariableResolver(name); } throw new UnresolveablePropertyException("unable to resolve variable '" + name + "'"); } public boolean isResolveable(String name) { return isTarget(name) || (nextFactory != null && nextFactory.isResolveable(name)); } protected VariableResolver addResolver(String name, VariableResolver vr) { variableResolvers.put(name, vr); return vr; } private VariableResolver getResolver(String name) { for (int i = 0; i < indexedVariableNames.length; i++) { if (indexedVariableNames[i].equals(name)) { return indexedVariableResolvers[i]; } } return null; } public boolean isTarget(String name) { for (int i = 0; i < indexedVariableNames.length; i++) { if (indexedVariableNames[i].equals(name)) { return true; } } return false; } public Set getKnownVariables() { return new HashSet(0); } public void clear() { // variableResolvers.clear(); } @Override public boolean isIndexedFactory() { return true; } }mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/BaseVariableResolverFactory.java0000644000175000017500000001357611257005261031404 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.UnresolveablePropertyException; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Use this class to extend you own VariableResolverFactories. It contains most of the baseline implementation needed * for the vast majority of integration needs. */ public abstract class BaseVariableResolverFactory implements VariableResolverFactory { protected Map variableResolvers = new HashMap(); protected VariableResolverFactory nextFactory; protected int indexOffset = 0; protected String[] indexedVariableNames; protected VariableResolver[] indexedVariableResolvers; public VariableResolverFactory getNextFactory() { return nextFactory; } public VariableResolverFactory setNextFactory(VariableResolverFactory resolverFactory) { return nextFactory = resolverFactory; } public VariableResolver getVariableResolver(String name) { if (isResolveable(name)) { if (variableResolvers.containsKey(name)) { return variableResolvers.get(name); } else if (nextFactory != null) { return nextFactory.getVariableResolver(name); } } throw new UnresolveablePropertyException("unable to resolve variable '" + name + "'"); } public boolean isNextResolveable(String name) { return nextFactory != null && nextFactory.isResolveable(name); } public void appendFactory(VariableResolverFactory resolverFactory) { if (nextFactory == null) { nextFactory = resolverFactory; } else { VariableResolverFactory vrf = nextFactory; while (vrf.getNextFactory() != null) { vrf = vrf.getNextFactory(); } vrf.setNextFactory(nextFactory); } } public void insertFactory(VariableResolverFactory resolverFactory) { if (nextFactory == null) { nextFactory = resolverFactory; } else { resolverFactory.setNextFactory(nextFactory = resolverFactory); } } public Set getKnownVariables() { if (nextFactory == null) { return new HashSet(variableResolvers.keySet()); // return new HashSet(0); } else { HashSet vars = new HashSet(variableResolvers.keySet()); vars.addAll(nextFactory.getKnownVariables()); return vars; } } public VariableResolver createIndexedVariable(int index, String name, Object value) { if (nextFactory != null) { return nextFactory.createIndexedVariable(index - indexOffset, name, value); } else { throw new RuntimeException("cannot create indexed variable: " + name + "(" + index + "). operation not supported by resolver: " + this.getClass().getName()); } } public VariableResolver getIndexedVariableResolver(int index) { if (nextFactory != null) { return nextFactory.getIndexedVariableResolver(index - indexOffset); } else { throw new RuntimeException("cannot access indexed variable: " + index + ". operation not supported by resolver: " + this.getClass().getName()); } } public VariableResolver createIndexedVariable(int index, String name, Object value, Class type) { if (nextFactory != null) { return nextFactory.createIndexedVariable(index - indexOffset, name, value, type); } else { throw new RuntimeException("cannot access indexed variable: " + name + "(" + index + "). operation not supported by resolver.: " + this.getClass().getName()); } } public Map getVariableResolvers() { return variableResolvers; } public void setVariableResolvers(Map variableResolvers) { this.variableResolvers = variableResolvers; } public String[] getIndexedVariableNames() { return indexedVariableNames; } public void setIndexedVariableNames(String[] indexedVariableNames) { this.indexedVariableNames = indexedVariableNames; } public int variableIndexOf(String name) { for (int i = 0; i < indexedVariableNames.length; i++) { if (name.equals(indexedVariableNames[i])) { return i; } } return -1; } public VariableResolver setIndexedVariableResolver(int index, VariableResolver resolver) { if (indexedVariableResolvers == null) { return (indexedVariableResolvers = new VariableResolver[indexedVariableNames.length])[index-indexOffset] = resolver; } else { return indexedVariableResolvers[index-indexOffset] = resolver; } } public boolean isIndexedFactory() { return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/SimpleVariableResolverFactory.java0000644000175000017500000000454611244064005031755 0ustar drazzibdrazzibpackage org.mvel2.integration.impl; import org.mvel2.integration.VariableResolver; import java.util.HashMap; import java.util.Map; import java.util.Set; public class SimpleVariableResolverFactory extends BaseVariableResolverFactory { public SimpleVariableResolverFactory(Map variables) { for (Map.Entry entry : variables.entrySet()) { createVariable(entry.getKey(), entry.getValue()); } } public VariableResolver createVariable(String name, Object value) { if (variableResolvers == null) variableResolvers = new HashMap(5, 0.6f); SimpleValueResolver svr = new SimpleValueResolver(value); variableResolvers.put(name, svr); return svr; } public VariableResolver createIndexedVariable(int index, String name, Object value) { return null; } public VariableResolver createVariable(String name, Object value, Class type) { if (variableResolvers == null) variableResolvers = new HashMap(5, 0.6f); SimpleSTValueResolver svr = new SimpleSTValueResolver(value, type); variableResolvers.put(name, svr); return svr; } public VariableResolver createIndexedVariable(int index, String name, Object value, Class typee) { return null; } public VariableResolver setIndexedVariableResolver(int index, VariableResolver variableResolver) { return null; } public boolean isTarget(String name) { return variableResolvers.containsKey(name); } public boolean isResolveable(String name) { return variableResolvers.containsKey(name) || (nextFactory != null && nextFactory.isResolveable(name)); } @Override public VariableResolver getVariableResolver(String name) { VariableResolver vr = variableResolvers.get(name); return vr != null ? vr : (nextFactory == null ? null : nextFactory.getVariableResolver(name)); } public Set getKnownVariables() { return variableResolvers.keySet(); } public int variableIndexOf(String name) { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean isIndexedFactory() { return false; //To change body of implemented methods use File | Settings | File Templates. } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/DefaultLocalVariableResolverFactory.java0000644000175000017500000000310711114565124033057 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.integration.VariableResolverFactory; import java.util.HashMap; import java.util.Map; public class DefaultLocalVariableResolverFactory extends MapVariableResolverFactory implements LocalVariableResolverFactory { public DefaultLocalVariableResolverFactory() { super(new HashMap()); } public DefaultLocalVariableResolverFactory(Map variables) { super(variables); } public DefaultLocalVariableResolverFactory(Map variables, VariableResolverFactory nextFactory) { super(variables, nextFactory); } public DefaultLocalVariableResolverFactory(Map variables, boolean cachingSafe) { super(variables); } public DefaultLocalVariableResolverFactory(VariableResolverFactory nextFactory) { super(new HashMap(), nextFactory); } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/ImmutableDefaultFactory.java0000644000175000017500000000521611077457613030572 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.CompileException; import org.mvel2.UnresolveablePropertyException; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import java.util.Set; public class ImmutableDefaultFactory implements VariableResolverFactory { private void throwError() { throw new CompileException("cannot assign variables; no variable resolver factory available."); } public VariableResolver createVariable(String name, Object value) { throwError(); return null; } public VariableResolver createIndexedVariable(int index, String name, Object value) { throwError(); return null; } public VariableResolver createVariable(String name, Object value, Class type) { throwError(); return null; } public VariableResolver createIndexedVariable(int index, String name, Object value, Class typee) { throwError(); return null; } public VariableResolver setIndexedVariableResolver(int index, VariableResolver variableResolver) { throwError(); return null; } public VariableResolverFactory getNextFactory() { return null; } public VariableResolverFactory setNextFactory(VariableResolverFactory resolverFactory) { throw new CompileException("cannot chain to this factory"); } public VariableResolver getVariableResolver(String name) { throw new UnresolveablePropertyException(name); } public VariableResolver getIndexedVariableResolver(int index) { throwError(); return null; } public boolean isTarget(String name) { return false; } public boolean isResolveable(String name) { return false; } public Set getKnownVariables() { return null; } public int variableIndexOf(String name) { return -1; } public boolean isIndexedFactory() { return false; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/TypeInjectionResolverFactory.java0000644000175000017500000000143611077457613031654 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; /** * This is a marker interface */ public interface TypeInjectionResolverFactory { } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/StaticMethodImportResolverFactory.java0000644000175000017500000000505411077457613032653 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.ParserContext; import org.mvel2.integration.VariableResolver; import org.mvel2.util.MethodStub; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * @author Christopher Brock */ public class StaticMethodImportResolverFactory extends BaseVariableResolverFactory { public StaticMethodImportResolverFactory(ParserContext ctx) { this.variableResolvers = new HashMap(); for (Map.Entry entry : ctx.getImports().entrySet()) { if (entry.getValue() instanceof Method) { createVariable(entry.getKey(), entry.getValue()); } } } public StaticMethodImportResolverFactory() { this.variableResolvers = new HashMap(); } public VariableResolver createVariable(String name, Object value) { if (value instanceof Method) value = new MethodStub((Method) value); StaticMethodImportResolver methodResolver = new StaticMethodImportResolver(name, (MethodStub) value); this.variableResolvers.put(name, methodResolver); return methodResolver; } public VariableResolver createVariable(String name, Object value, Class type) { return null; } public boolean isTarget(String name) { return this.variableResolvers.containsKey(name); } public boolean isResolveable(String name) { return isTarget(name) || isNextResolveable(name); } public Map getImportedMethods() { Map im = new HashMap(); for (Map.Entry e : this.variableResolvers.entrySet()) { im.put(e.getKey(), (Method) e.getValue().getValue()); } return im; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/ClassImportResolverFactory.java0000644000175000017500000001041711176724505031324 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.ParserConfiguration; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ClassImportResolverFactory extends BaseVariableResolverFactory { private Set packageImports; private ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); public ClassImportResolverFactory() { super(); variableResolvers = new HashMap(); } public ClassImportResolverFactory(ParserConfiguration ctx, VariableResolverFactory nextFactory) { packageImports = ctx.getPackageImports(); Map classes = ctx.getImports(); classLoader = ctx.getClassLoader(); this.nextFactory = nextFactory; this.variableResolvers = new HashMap(); for (Map.Entry e : classes.entrySet()) { variableResolvers.put(e.getKey(), new SimpleValueResolver(e.getValue())); } } public VariableResolver createVariable(String name, Object value) { if (nextFactory == null) { nextFactory = new MapVariableResolverFactory(new HashMap()); } return nextFactory.createVariable(name, value); } public VariableResolver createVariable(String name, Object value, Class type) { if (nextFactory == null) { nextFactory = new MapVariableResolverFactory(new HashMap()); } return nextFactory.createVariable(name, value); } public Class addClass(Class clazz) { variableResolvers.put(clazz.getSimpleName(), new SimpleValueResolver(clazz)); return clazz; } public boolean isTarget(String name) { return variableResolvers.containsKey(name); } public boolean isResolveable(String name) { if (variableResolvers.containsKey(name) || isNextResolveable(name)) { return true; } else if (packageImports != null) { for (String s : packageImports) { try { addClass(classLoader.loadClass(s + "." + name)); return true; } catch (ClassNotFoundException e) { // do nothing; } catch (NoClassDefFoundError e) { // do nothing; } } } return false; } public void clear() { variableResolvers.clear(); } public void setImportedClasses(Map imports) { if (imports == null) return; for (Map.Entry e : imports.entrySet()) { variableResolvers.put(e.getKey(), new SimpleValueResolver(e.getValue())); } } public Map getImportedClasses() { Map imports = new HashMap(); for (Map.Entry e : variableResolvers.entrySet()) { imports.put(e.getKey(), e.getValue().getValue()); } return imports; } public void addPackageImport(String packageName) { if (packageImports == null) packageImports = new HashSet(); packageImports.add(packageName); } @Override public Set getKnownVariables() { return nextFactory == null ? new HashSet(0) : nextFactory.getKnownVariables(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/SimpleValueResolver.java0000644000175000017500000000241611077457613027765 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.integration.VariableResolver; public class SimpleValueResolver implements VariableResolver { private Object value; public SimpleValueResolver(Object value) { this.value = value; } public String getName() { return null; } public Class getType() { return Object.class; } public void setStaticType(Class type) { } public int getFlags() { return 0; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/CachedMapVariableResolver.java0000644000175000017500000000351311115335157031000 0ustar drazzibdrazzibpackage org.mvel2.integration.impl; import org.mvel2.integration.VariableResolver; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import org.mvel2.CompileException; import java.util.Map; public class CachedMapVariableResolver implements VariableResolver { private String name; private Class knownType; private Map.Entry entry; public CachedMapVariableResolver(Map.Entry entry, String name) { this.entry = entry; this.name = name; } public CachedMapVariableResolver(Map.Entry entry, String name, Class knownType) { this.name = name; this.knownType = knownType; this.entry = entry; } public void setName(String name) { this.name = name; } public void setStaticType(Class knownType) { this.knownType = knownType; } public String getName() { return name; } public Class getType() { return knownType; } public void setValue(Object value) { if (knownType != null && value != null && value.getClass() != knownType) { Class t = value.getClass(); if (!canConvert(knownType, t)) { throw new CompileException("cannot assign " + value.getClass().getName() + " to type: " + knownType.getName()); } try { value = convert(value, knownType); } catch (Exception e) { throw new CompileException("cannot convert value of " + value.getClass().getName() + " to: " + knownType.getName()); } } //noinspection unchecked entry.setValue(value); } public Object getValue() { return entry.getValue(); } public int getFlags() { return 0; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/IndexVariableResolver.java0000644000175000017500000000213511244544040030235 0ustar drazzibdrazzibpackage org.mvel2.integration.impl; import org.mvel2.integration.VariableResolver; /** * Created by IntelliJ IDEA. * User: christopherbrock * Date: 24-Aug-2009 * Time: 12:48:31 PM * To change this template use File | Settings | File Templates. */ public class IndexVariableResolver implements VariableResolver { private int indexPos; private Object[] vars; public IndexVariableResolver(int indexPos, Object[] vars) { this.indexPos = indexPos; this.vars = vars; } public String getName() { return null; } public Class getType() { return null; //To change body of implemented methods use File | Settings | File Templates. } public void setStaticType(Class type) { //To change body of implemented methods use File | Settings | File Templates. } public int getFlags() { return 0; //To change body of implemented methods use File | Settings | File Templates. } public Object getValue() { return vars[indexPos]; } public void setValue(Object value) { vars[indexPos] = value; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/CachedMapVariableResolverFactory.java0000644000175000017500000000767511115335157032345 0ustar drazzibdrazzibpackage org.mvel2.integration.impl; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.VariableResolver; import org.mvel2.UnresolveablePropertyException; import org.mvel2.CompileException; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; public class CachedMapVariableResolverFactory extends BaseVariableResolverFactory { /** * Holds the instance of the variables. */ protected Map variables; public CachedMapVariableResolverFactory() { } public CachedMapVariableResolverFactory(Map variables) { this.variables = variables; variableResolvers = new HashMap(variables.size() * 2); for (Map.Entry entry : variables.entrySet()) { variableResolvers.put(entry.getKey(), new CachedMapVariableResolver(entry, entry.getKey())); } } public CachedMapVariableResolverFactory(Map variables, VariableResolverFactory nextFactory) { this.variables = variables; variableResolvers = new HashMap(variables.size() * 2); for (Map.Entry entry : variables.entrySet()) { variableResolvers.put(entry.getKey(), new CachedMapVariableResolver(entry, entry.getKey())); } this.nextFactory = nextFactory; } public VariableResolver createVariable(String name, Object value) { VariableResolver vr; try { (vr = getVariableResolver(name)).setValue(value); return vr; } catch (UnresolveablePropertyException e) { addResolver(name, vr = new MapVariableResolver(variables, name)).setValue(value); return vr; } } public VariableResolver createVariable(String name, Object value, Class type) { VariableResolver vr; try { vr = getVariableResolver(name); } catch (UnresolveablePropertyException e) { vr = null; } if (vr != null && vr.getType() != null) { throw new CompileException("variable already defined within scope: " + vr.getType() + " " + name); } else { addResolver(name, vr = new MapVariableResolver(variables, name, type)).setValue(value); return vr; } } public VariableResolver getVariableResolver(String name) { VariableResolver vr = variableResolvers.get(name); if (vr != null) { return vr; } else if (variables.containsKey(name)) { variableResolvers.put(name, vr = new MapVariableResolver(variables, name)); return vr; } else if (nextFactory != null) { return nextFactory.getVariableResolver(name); } throw new UnresolveablePropertyException("unable to resolve variable '" + name + "'"); } public boolean isResolveable(String name) { return (variableResolvers != null && variableResolvers.containsKey(name)) || (variables != null && variables.containsKey(name)) || (nextFactory != null && nextFactory.isResolveable(name)); } protected VariableResolver addResolver(String name, VariableResolver vr) { if (variableResolvers == null) variableResolvers = new HashMap(); variableResolvers.put(name, vr); return vr; } public boolean isTarget(String name) { return variableResolvers != null && variableResolvers.containsKey(name); } public Set getKnownVariables() { if (nextFactory == null) { if (variables != null) return new HashSet(variables.keySet()); return new HashSet(0); } else { if (variables != null) return new HashSet(variables.keySet()); return new HashSet(0); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/StaticMethodImportResolver.java0000644000175000017500000000276411077457613031330 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.integration.VariableResolver; import org.mvel2.util.MethodStub; /** * @author Christopher Brock */ public class StaticMethodImportResolver implements VariableResolver { private String name; private MethodStub method; public StaticMethodImportResolver(String name, MethodStub method) { this.name = name; this.method = method; } public String getName() { return name; } public Class getType() { return null; } public void setStaticType(Class type) { } public int getFlags() { return 0; } public MethodStub getValue() { return method; } public void setValue(Object value) { this.method = (MethodStub) value; } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/TypeInjectionResolverFactoryImpl.java0000644000175000017500000000532511114565124032464 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.ParserContext; import org.mvel2.integration.VariableResolver; import org.mvel2.integration.VariableResolverFactory; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class TypeInjectionResolverFactoryImpl extends MapVariableResolverFactory implements TypeInjectionResolverFactory { public TypeInjectionResolverFactoryImpl() { this.variables = new HashMap(); } public TypeInjectionResolverFactoryImpl(Map variables) { this.variables = variables; } public TypeInjectionResolverFactoryImpl(ParserContext ctx, VariableResolverFactory nextVariableResolverFactory) { super(ctx.getImports(), ctx.hasFunction() ? new TypeInjectionResolverFactoryImpl(ctx.getFunctions(), nextVariableResolverFactory) : nextVariableResolverFactory); } public TypeInjectionResolverFactoryImpl(Map variables, VariableResolverFactory nextFactory) { super(variables, nextFactory); } public TypeInjectionResolverFactoryImpl(Map variables, boolean cachingSafe) { super(variables); } public VariableResolver createVariable(String name, Object value) { if (nextFactory == null) { nextFactory = new MapVariableResolverFactory(new HashMap()); } /** * Delegate to the next factory. */ return nextFactory.createVariable(name, value); } public VariableResolver createVariable(String name, Object value, Class type) { if (nextFactory == null) { nextFactory = new MapVariableResolverFactory(new HashMap()); } /** * Delegate to the next factory. */ return nextFactory.createVariable(name, value, type); } public Set getKnownVariables() { if (nextFactory == null) { return new HashSet(0); } else { return nextFactory.getKnownVariables(); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/integration/impl/SimpleSTValueResolver.java0000644000175000017500000000405111163775741030232 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.integration.impl; import org.mvel2.integration.VariableResolver; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataConversion.convert; import org.mvel2.CompileException; public class SimpleSTValueResolver implements VariableResolver { private Object value; private Class type; public SimpleSTValueResolver(Object value, Class type) { this.value = value; this.type = type; } public String getName() { return null; } public Class getType() { return type; } public void setStaticType(Class type) { this.type = type; } public int getFlags() { return 0; } public Object getValue() { return value; } public void setValue(Object value) { if (type != null && value != null && value.getClass() != type) { if (!canConvert(type, value.getClass())) { throw new CompileException("cannot assign " + value.getClass().getName() + " to type: " + type.getName()); } try { value = convert(value, type); } catch (Exception e) { throw new CompileException("cannot convert value of " + value.getClass().getName() + " to: " + type.getName()); } } this.value = value; } }mvel-2.0.18.orig/src/main/java/org/mvel2/util/0000755000175000017500000000000011412747055020633 5ustar drazzibdrazzibmvel-2.0.18.orig/src/main/java/org/mvel2/util/StackElement.java0000644000175000017500000000171711077460760024065 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import java.io.Serializable; public class StackElement implements Serializable { public StackElement(StackElement next, Object value) { this.next = next; this.value = value; } public volatile StackElement next; public volatile Object value; } mvel-2.0.18.orig/src/main/java/org/mvel2/util/MVELClassLoader.java0000644000175000017500000000145711077460760024367 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; public interface MVELClassLoader { public Class defineClassX(String className, byte[] b, int start, int end); } mvel-2.0.18.orig/src/main/java/org/mvel2/util/ParseTools.java0000644000175000017500000020630311363352207023571 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.*; import static org.mvel2.DataConversion.canConvert; import static org.mvel2.DataTypes.*; import static org.mvel2.MVEL.getDebuggingOutputFileName; import org.mvel2.ast.ASTNode; import org.mvel2.compiler.*; import static org.mvel2.compiler.AbstractParser.LITERALS; import static org.mvel2.integration.ResolverTools.insertFactory; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.ClassImportResolverFactory; import org.mvel2.math.MathProcessor; import java.io.*; import static java.lang.Class.forName; import static java.lang.Double.parseDouble; import static java.lang.String.valueOf; import static java.lang.System.arraycopy; import static java.lang.Thread.currentThread; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.nio.ByteBuffer; import static java.nio.ByteBuffer.allocateDirect; import java.nio.channels.ReadableByteChannel; import java.util.*; @SuppressWarnings({"ManualArrayCopy"}) public class ParseTools { public static final String[] EMPTY_STR_ARR = new String[0]; public static final Object[] EMPTY_OBJ_ARR = new Object[0]; public static final Class[] EMPTY_CLS_ARR = new Class[0]; static { try { double version = parseDouble(System.getProperty("java.version").substring(0, 3)); if (version < 1.5) { throw new RuntimeException("unsupported java version: " + version); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("unable to initialize math processor", e); } } public static String[] parseMethodOrConstructor(char[] parm) { int start = -1; for (int i = 0; i < parm.length; i++) { if (parm[i] == '(') { start = ++i; break; } } if (start != -1) { return parseParameterList(parm, --start + 1, balancedCapture(parm, start, '(') - start - 1); } return EMPTY_STR_ARR; } public static String[] parseParameterDefList(char[] parm, int offset, int length) { List list = new LinkedList(); if (length == -1) length = parm.length; int start = offset; int i = offset; int end = i + length; String s; for (; i < end; i++) { switch (parm[i]) { case '(': case '[': case '{': i = balancedCapture(parm, i, parm[i]); continue; case '\'': i = captureStringLiteral('\'', parm, i, parm.length); continue; case '"': i = captureStringLiteral('"', parm, i, parm.length); continue; case ',': if (i > start) { while (isWhitespace(parm[start])) start++; checkNameSafety(s = new String(parm, start, i - start)); list.add(s); } while (isWhitespace(parm[i])) i++; start = i + 1; continue; default: if (!isWhitespace(parm[i]) && !isIdentifierPart(parm[i])) { throw new CompileException("expected parameter"); } } } if (start < (length + offset) && i > start) { if ((s = createStringTrimmed(parm, start, i - start)).length() > 0) { checkNameSafety(s); list.add(s); } } else if (list.size() == 0) { if ((s = createStringTrimmed(parm, start, length)).length() > 0) { checkNameSafety(s); list.add(s); } } return list.toArray(new String[list.size()]); } public static String[] parseParameterList(char[] parm, int offset, int length) { List list = new LinkedList(); if (length == -1) length = parm.length; int start = offset; int i = offset; int end = i + length; for (; i < end; i++) { switch (parm[i]) { case '(': case '[': case '{': i = balancedCapture(parm, i, parm[i]); continue; case '\'': i = captureStringLiteral('\'', parm, i, parm.length); continue; case '"': i = captureStringLiteral('"', parm, i, parm.length); continue; case ',': if (i > start) { while (isWhitespace(parm[start])) start++; list.add(new String(parm, start, i - start)); } while (isWhitespace(parm[i])) i++; start = i + 1; } } if (start < (length + offset) && i > start) { String s = createStringTrimmed(parm, start, i - start); if (s.length() > 0) list.add(s); } else if (list.size() == 0) { String s = createStringTrimmed(parm, start, length); if (s.length() > 0) list.add(s); } return list.toArray(new String[list.size()]); } private static Map>> RESOLVED_METH_CACHE = new WeakHashMap>>(10); public static Method getBestCandidate(Object[] arguments, String method, Class decl, Method[] methods, boolean requireExact) { Class[] targetParms = new Class[arguments.length]; for (int i = 0; i != arguments.length; i++) { targetParms[i] = arguments[i] != null ? arguments[i].getClass() : null; } return getBestCandidate(targetParms, method, decl, methods, requireExact); } public static Method getBestCandidate(Class[] arguments, String method, Class decl, Method[] methods, boolean requireExact) { if (methods.length == 0) { return null; } Class[] parmTypes; Method bestCandidate = null; int bestScore = 0; int score = 0; Integer hash = createClassSignatureHash(decl, arguments); Map> methCache = RESOLVED_METH_CACHE.get(method); WeakReference ref; if (methCache != null && (ref = methCache.get(hash)) != null && (bestCandidate = ref.get()) != null) { return bestCandidate; } for (Method meth : methods) { if (method.equals(meth.getName())) { if ((parmTypes = meth.getParameterTypes()).length != arguments.length) { continue; } else if (arguments.length == 0 && parmTypes.length == 0) { bestCandidate = meth; break; } for (int i = 0; i != arguments.length; i++) { if (arguments[i] == null) { if (!parmTypes[i].isPrimitive()) { score += 5; } else { score = 0; break; } } else if (parmTypes[i] == arguments[i]) { score += 6; } else if (parmTypes[i].isPrimitive() && boxPrimitive(parmTypes[i]) == arguments[i]) { score += 5; } else if (arguments[i].isPrimitive() && unboxPrimitive(arguments[i]) == parmTypes[i]) { score += 5; } else if (isNumericallyCoercible(arguments[i], parmTypes[i])) { score += 4; } else if (boxPrimitive(parmTypes[i]).isAssignableFrom(boxPrimitive(arguments[i])) && Object.class != arguments[i]) { score += 3 + scoreInterface(parmTypes[i], arguments[i]); } else if (!requireExact && canConvert(parmTypes[i], arguments[i])) { if (parmTypes[i].isArray() && arguments[i].isArray()) score += 1; else if (parmTypes[i] == char.class && arguments[i] == String.class) score += 1; score += 1; } else if (arguments[i] == Object.class) { score += 1; } else { score = 0; break; } } if (score != 0 && score > bestScore) { bestCandidate = meth; bestScore = score; } score = 0; } } if (bestCandidate != null) { if (methCache == null) { RESOLVED_METH_CACHE.put(method, methCache = new WeakHashMap>()); } methCache.put(hash, new WeakReference(bestCandidate)); } return bestCandidate; } public static int scoreInterface(Class parm, Class arg) { if (parm.isInterface()) { Class[] iface = arg.getInterfaces(); if (iface != null) { for (Class c : iface) { if (c == parm) return 1; else if (parm.isAssignableFrom(c)) return scoreInterface(parm, arg.getSuperclass()); } } } return 0; } public static Method getExactMatch(String name, Class[] args, Class returnType, Class cls) { for (Method meth : cls.getMethods()) { if (name.equals(meth.getName()) && returnType == meth.getReturnType()) { Class[] parameterTypes = meth.getParameterTypes(); if (parameterTypes.length != args.length) continue; for (int i = 0; i < parameterTypes.length; i++) { if (parameterTypes[i] != args[i]) return null; } return meth; } } return null; } public static Method getWidenedTarget(Method method) { Class cls = method.getDeclaringClass(); Method m = method, best = method; Class[] args = method.getParameterTypes(); String name = method.getName(); Class rt = m.getReturnType(); do { if (cls.getInterfaces().length != 0) { for (Class iface : cls.getInterfaces()) { if ((m = getExactMatch(name, args, rt, iface)) != null) { if ((best = m).getDeclaringClass().getSuperclass() != null) { cls = m.getDeclaringClass(); } } } } if (cls != method.getDeclaringClass()) { if ((m = getExactMatch(name, args, rt, cls)) != null) { if ((best = m).getDeclaringClass().getSuperclass() != null) { cls = m.getDeclaringClass(); } } } } while ((cls = cls.getSuperclass()) != null); return best; } private static Map>> RESOLVED_CONST_CACHE = new WeakHashMap>>(10); private static Map> CONSTRUCTOR_PARMS_CACHE = new WeakHashMap>(10); private static Class[] getConstructors(Constructor cns) { WeakReference ref = CONSTRUCTOR_PARMS_CACHE.get(cns); Class[] parms; if (ref != null && (parms = ref.get()) != null) { return parms; } else { CONSTRUCTOR_PARMS_CACHE.put(cns, new WeakReference(parms = cns.getParameterTypes())); return parms; } } public static Constructor getBestConstructorCandidate(Object[] args, Class cls, boolean requireExact) { Class[] arguments = new Class[args.length]; for (int i = 0; i != args.length; i++) { if (args[i] != null) { arguments[i] = args[i].getClass(); } } return getBestConstructorCandidate(arguments, cls, requireExact); } public static Constructor getBestConstructorCandidate(Class[] arguments, Class cls, boolean requireExact) { Class[] parmTypes; Constructor bestCandidate = null; int bestScore = 0; int score = 0; Integer hash = createClassSignatureHash(cls, arguments); Map> cache = RESOLVED_CONST_CACHE.get(cls); WeakReference ref; if (cache != null && (ref = cache.get(hash)) != null && (bestCandidate = ref.get()) != null) { return bestCandidate; } for (Constructor construct : getConstructors(cls)) { if ((parmTypes = getConstructors(construct)).length != arguments.length) { continue; } else if (arguments.length == 0 && parmTypes.length == 0) { return construct; } for (int i = 0; i != arguments.length; i++) { if (arguments[i] == null) { if (!parmTypes[i].isPrimitive()) { score += 5; } else { score = 0; break; } } else if (parmTypes[i] == arguments[i]) { score += 6; } else if (parmTypes[i].isPrimitive() && boxPrimitive(parmTypes[i]) == arguments[i]) { score += 5; } else if (arguments[i].isPrimitive() && unboxPrimitive(arguments[i]) == parmTypes[i]) { score += 5; } else if (isNumericallyCoercible(arguments[i], parmTypes[i])) { score += 4; } else if (boxPrimitive(parmTypes[i]).isAssignableFrom(boxPrimitive(arguments[i])) && parmTypes[i] != Object.class) { score += 3 + scoreInterface(parmTypes[i], arguments[i]); } else if (!requireExact && canConvert(parmTypes[i], arguments[i])) { if (parmTypes[i].isArray() && arguments[i].isArray()) score += 1; else if (parmTypes[i] == char.class && arguments[i] == String.class) score += 1; score += 1; } else if (arguments[i] == Object.class) { score += 1; } else { score = 0; break; } } if (score != 0 && score > bestScore) { bestCandidate = construct; bestScore = score; } score = 0; } if (bestCandidate != null) { if (cache == null) { RESOLVED_CONST_CACHE.put(cls, cache = new WeakHashMap>()); } cache.put(hash, new WeakReference(bestCandidate)); } return bestCandidate; } private static Map>> CLASS_RESOLVER_CACHE = new WeakHashMap>>(1, 1.0f); private static Map> CLASS_CONSTRUCTOR_CACHE = new WeakHashMap>(10); public static Class createClass(String className, ParserContext pCtx) throws ClassNotFoundException { ClassLoader classLoader = currentThread().getContextClassLoader(); Map> cache = CLASS_RESOLVER_CACHE.get(classLoader); if (cache == null) { CLASS_RESOLVER_CACHE.put(classLoader, cache = new WeakHashMap>(10)); } WeakReference ref; Class cls; if ((ref = cache.get(className)) != null && (cls = ref.get()) != null) { return cls; } else { try { cls = pCtx == null ? Class.forName(className, true, Thread.currentThread().getContextClassLoader()) : Class.forName(className, true, pCtx.getParserConfiguration().getClassLoader()); } catch (ClassNotFoundException e) { /** * Now try the system classloader. */ cls = forName(className, true, Thread.currentThread().getContextClassLoader()); } cache.put(className, new WeakReference(cls)); return cls; } } public static Constructor[] getConstructors(Class cls) { WeakReference ref = CLASS_CONSTRUCTOR_CACHE.get(cls); Constructor[] cns; if (ref != null && (cns = ref.get()) != null) { return cns; } else { CLASS_CONSTRUCTOR_CACHE.put(cls, new WeakReference(cns = cls.getConstructors())); return cns; } } public static String[] captureContructorAndResidual(char[] cs) { int depth = 0; for (int i = 0; i < cs.length; i++) { switch (cs[i]) { case '(': depth++; continue; case ')': if (1 == depth--) { return new String[]{new String(cs, 0, ++i), createStringTrimmed(cs, i, cs.length - i)}; } } } return new String[]{new String(cs)}; } public static Class boxPrimitive(Class cls) { if (cls == int.class || cls == Integer.class) { return Integer.class; } else if (cls == int[].class || cls == Integer[].class) { return Integer[].class; } else if (cls == char.class || cls == Character.class) { return Character.class; } else if (cls == char[].class || cls == Character[].class) { return Character[].class; } else if (cls == long.class || cls == Long.class) { return Long.class; } else if (cls == long[].class || cls == Long[].class) { return Long[].class; } else if (cls == short.class || cls == Short.class) { return Short.class; } else if (cls == short[].class || cls == Short[].class) { return Short[].class; } else if (cls == double.class || cls == Double.class) { return Double.class; } else if (cls == double[].class || cls == Double[].class) { return Double[].class; } else if (cls == float.class || cls == Float.class) { return Float.class; } else if (cls == float[].class || cls == Float[].class) { return Float[].class; } else if (cls == boolean.class || cls == Boolean.class) { return Boolean.class; } else if (cls == boolean[].class || cls == Boolean[].class) { return Boolean[].class; } else if (cls == byte.class || cls == Byte.class) { return Byte.class; } else if (cls == byte[].class || cls == Byte[].class) { return Byte[].class; } return cls; } public static Class unboxPrimitive(Class cls) { if (cls == Integer.class || cls == int.class) { return int.class; } else if (cls == Integer[].class || cls == int[].class) { return int[].class; } else if (cls == Long.class || cls == long.class) { return long.class; } else if (cls == Long[].class || cls == long[].class) { return long[].class; } else if (cls == Character.class || cls == char.class) { return char.class; } else if (cls == Character[].class || cls == char[].class) { return char[].class; } else if (cls == Short.class || cls == short.class) { return short.class; } else if (cls == Short[].class || cls == short[].class) { return short[].class; } else if (cls == Double.class || cls == double.class) { return double.class; } else if (cls == Double[].class || cls == double[].class) { return double[].class; } else if (cls == Float.class || cls == float.class) { return float.class; } else if (cls == Float[].class || cls == float[].class) { return float[].class; } else if (cls == Boolean.class || cls == boolean.class) { return boolean.class; } else if (cls == Boolean[].class || cls == boolean[].class) { return boolean[].class; } else if (cls == Byte.class || cls == byte.class) { return byte.class; } else if (cls == Byte[].class || cls == byte[].class) { return byte[].class; } return cls; } public static boolean containsCheck(Object compareTo, Object compareTest) { if (compareTo == null) return false; else if (compareTo instanceof String) return ((String) compareTo).contains(valueOf(compareTest)); else if (compareTo instanceof Collection) return ((Collection) compareTo).contains(compareTest); else if (compareTo instanceof Map) return ((Map) compareTo).containsKey(compareTest); else if (compareTo.getClass().isArray()) { for (Object o : ((Object[]) compareTo)) { if (compareTest == null && o == null) return true; else if ((Boolean) MathProcessor.doOperations(o, Operator.EQUAL, compareTest)) return true; } } return false; } public static int createClassSignatureHash(Class declaring, Class[] sig) { int hash = 0; for (Class cls : sig) { if (cls != null) hash += cls.hashCode(); } return hash + sig.length + declaring.hashCode(); } /** * Replace escape sequences and return trim required. * * @param escapeStr - * @param pos - * @return - */ public static int handleEscapeSequence(char[] escapeStr, int pos) { escapeStr[pos - 1] = 0; switch (escapeStr[pos]) { case '\\': escapeStr[pos] = '\\'; return 1; case 'b': escapeStr[pos] = '\b'; return 1; case 'f': escapeStr[pos] = '\f'; return 1; case 't': escapeStr[pos] = '\t'; return 1; case 'r': escapeStr[pos] = '\r'; return 1; case 'n': escapeStr[pos] = '\n'; return 1; case '\'': escapeStr[pos] = '\''; return 1; case '"': escapeStr[pos] = '\"'; return 1; case 'u': //unicode int s = pos; if (s + 4 > escapeStr.length) throw new CompileException("illegal unicode escape sequence"); else { while (++pos - s != 5) { if ((escapeStr[pos] > ('0' - 1) && escapeStr[pos] < ('9' + 1)) || (escapeStr[pos] > ('A' - 1) && escapeStr[pos] < ('F' + 1))) { } else { throw new CompileException("illegal unicode escape sequence"); } } escapeStr[s - 1] = (char) Integer.decode("0x" + new String(escapeStr, s + 1, 4)).intValue(); escapeStr[s] = 0; escapeStr[s + 1] = 0; escapeStr[s + 2] = 0; escapeStr[s + 3] = 0; escapeStr[s + 4] = 0; return 5; } default: //octal s = pos; while (escapeStr[pos] >= '0' && escapeStr[pos] < '8') { if (pos != s && escapeStr[s] > '3') { escapeStr[s - 1] = (char) Integer.decode("0" + new String(escapeStr, s, pos - s + 1)).intValue(); escapeStr[s] = 0; escapeStr[s + 1] = 0; return 2; } else if ((pos - s) == 2) { escapeStr[s - 1] = (char) Integer.decode("0" + new String(escapeStr, s, pos - s + 1)).intValue(); escapeStr[s] = 0; escapeStr[s + 1] = 0; escapeStr[s + 2] = 0; return 3; } if (pos + 1 == escapeStr.length || (escapeStr[pos] < '0' || escapeStr[pos] > '7')) { escapeStr[s - 1] = (char) Integer.decode("0" + new String(escapeStr, s, pos - s + 1)).intValue(); escapeStr[s] = 0; return 1; } pos++; } throw new CompileException("illegal escape sequence: " + escapeStr[pos]); } } public static char[] createShortFormOperativeAssignment(String name, char[] statement, int operation) { if (operation == -1) { return statement; } char[] stmt; char op = 0; switch (operation) { case Operator.ADD: op = '+'; break; case Operator.STR_APPEND: op = '#'; break; case Operator.SUB: op = '-'; break; case Operator.MULT: op = '*'; break; case Operator.MOD: op = '%'; break; case Operator.DIV: op = '/'; break; case Operator.BW_AND: op = '&'; break; case Operator.BW_OR: op = '|'; break; case Operator.BW_SHIFT_LEFT: op = '\u00AB'; break; case Operator.BW_SHIFT_RIGHT: op = '\u00BB'; break; case Operator.BW_USHIFT_RIGHT: op = '\u00AC'; break; } arraycopy(name.toCharArray(), 0, (stmt = new char[name.length() + statement.length + 1]), 0, name.length()); stmt[name.length()] = op; arraycopy(statement, 0, stmt, name.length() + 1, statement.length); return stmt; } public static ClassImportResolverFactory findClassImportResolverFactory(VariableResolverFactory factory) { VariableResolverFactory v = factory; while (v != null) { if (v instanceof ClassImportResolverFactory) { return (ClassImportResolverFactory) v; } v = v.getNextFactory(); } if (factory == null) { throw new OptimizationFailure("unable to import classes. no variable resolver factory available."); } else { return insertFactory(factory, new ClassImportResolverFactory()); } } public static Class findClass(VariableResolverFactory factory, String name, ParserContext ctx) throws ClassNotFoundException { try { if (LITERALS.containsKey(name)) { return (Class) LITERALS.get(name); } else if (factory != null && factory.isResolveable(name)) { return (Class) factory.getVariableResolver(name).getValue(); } else if (ctx != null && ctx.hasImport(name)) { return ctx.getImport(name); } else { return createClass(name, ctx); } } catch (ClassNotFoundException e) { throw e; } catch (Exception e) { throw new CompileException("class not found: " + name, e); } } public static char[] subset(char[] array, int start, int length) { if (length < 0) return new char[0]; char[] newArray = new char[length]; for (int i = 0; i < newArray.length; i++) { newArray[i] = array[i + start]; } return newArray; } public static char[] subset(char[] array, int start) { char[] newArray = new char[array.length - start]; for (int i = 0; i < newArray.length; i++) { newArray[i] = array[i + start]; } return newArray; } private static final HashMap typeResolveMap = new HashMap(); static { Map t = typeResolveMap; t.put(BigDecimal.class, DataTypes.BIG_DECIMAL); t.put(BigInteger.class, DataTypes.BIG_INTEGER); t.put(String.class, DataTypes.STRING); t.put(int.class, INTEGER); t.put(Integer.class, DataTypes.W_INTEGER); t.put(short.class, DataTypes.SHORT); t.put(Short.class, DataTypes.W_SHORT); t.put(float.class, DataTypes.FLOAT); t.put(Float.class, DataTypes.W_FLOAT); t.put(double.class, DOUBLE); t.put(Double.class, DataTypes.W_DOUBLE); t.put(long.class, LONG); t.put(Long.class, DataTypes.W_LONG); t.put(boolean.class, DataTypes.BOOLEAN); t.put(Boolean.class, DataTypes.W_BOOLEAN); t.put(byte.class, DataTypes.BYTE); t.put(Byte.class, DataTypes.W_BYTE); t.put(char.class, DataTypes.CHAR); t.put(Character.class, DataTypes.W_CHAR); t.put(BlankLiteral.class, DataTypes.EMPTY); } public static int resolveType(Object o) { if (o == null) return DataTypes.OBJECT; else return __resolveType(o.getClass()); } public static int resolveType(Class cls) { Integer i = typeResolveMap.get(cls); if (i == null) return DataTypes.OBJECT; else { return i; } } public static int __resolveType(Class cls) { if (Integer.class == cls) return DataTypes.W_INTEGER; if (Double.class == cls) return DataTypes.W_DOUBLE; if (Boolean.class == cls) return DataTypes.W_BOOLEAN; if (String.class == cls) return DataTypes.STRING; if (Long.class == cls) return DataTypes.W_LONG; if (Short.class == cls) return DataTypes.W_SHORT; if (Float.class == cls) return DataTypes.W_FLOAT; if (Byte.class == cls) return DataTypes.W_BYTE; if (Character.class == cls) return DataTypes.W_CHAR; if (BigDecimal.class == cls) return DataTypes.BIG_DECIMAL; if (BigInteger.class == cls) return DataTypes.BIG_INTEGER; if (int.class == cls) return INTEGER; if (short.class == cls) return DataTypes.SHORT; if (float.class == cls) return DataTypes.FLOAT; if (double.class == cls) return DOUBLE; if (long.class == cls) return LONG; if (boolean.class == cls) return DataTypes.BOOLEAN; if (byte.class == cls) return DataTypes.BYTE; if (char.class == cls) return DataTypes.CHAR; if (BlankLiteral.class == cls) return DataTypes.EMPTY; return DataTypes.OBJECT; } public static boolean isNumericallyCoercible(Class target, Class parm) { Class boxedTarget = target.isPrimitive() ? boxPrimitive(target) : target; if (boxedTarget != null && Number.class.isAssignableFrom(target)) { if ((boxedTarget = parm.isPrimitive() ? boxPrimitive(parm) : parm) != null) { return Number.class.isAssignableFrom(boxedTarget); } } return false; } public static Object narrowType(final BigDecimal result, int returnTarget) { if (returnTarget == DataTypes.W_DOUBLE || result.scale() > 0) { return result.doubleValue(); } else if (returnTarget == DataTypes.W_LONG || result.longValue() > Integer.MAX_VALUE) { return result.longValue(); } else { return result.intValue(); } } public static Method determineActualTargetMethod(Method method) { String name = method.getName(); /** * Follow our way up the class heirarchy until we find the physical target method. */ for (Class cls : method.getDeclaringClass().getInterfaces()) { for (Method meth : cls.getMethods()) { if (meth.getParameterTypes().length == 0 && name.equals(meth.getName())) { return meth; } } } return null; } public static int captureToNextTokenJunction(char[] expr, int cursor, ParserContext pCtx) { while (cursor != expr.length) { switch (expr[cursor]) { case '{': case '(': return cursor; case '[': cursor = balancedCaptureWithLineAccounting(expr, cursor, '[', pCtx) + 1; continue; default: if (isWhitespace(expr[cursor])) { return cursor; } cursor++; } } return cursor; } public static int nextNonBlank(char[] expr, int cursor) { if ((cursor + 1) >= expr.length) { throw new CompileException("unexpected end of statement", expr, cursor); } int i = cursor; while (i != expr.length && isWhitespace(expr[i])) i++; return i; } public static int skipWhitespace(char[] expr, int cursor, ParserContext pCtx) { int line = pCtx.getLineCount(); int lastLineStart = pCtx.getLineOffset(); Skip: while (cursor != expr.length) { switch (expr[cursor]) { case '\n': line++; lastLineStart = cursor; case '\r': cursor++; continue; case '/': if (cursor + 1 != expr.length) { switch (expr[cursor + 1]) { case '/': expr[cursor++] = ' '; while (cursor != expr.length && expr[cursor] != '\n') expr[cursor++] = ' '; if (cursor != expr.length) expr[cursor++] = ' '; line++; lastLineStart = cursor; continue; case '*': int len = expr.length - 1; expr[cursor++] = ' '; while (cursor != len && !(expr[cursor] == '*' && expr[cursor + 1] == '/')) { if (expr[cursor] == '\n') { line++; lastLineStart = cursor; } expr[cursor++] = ' '; } if (cursor != len) expr[cursor++] = expr[cursor++] = ' '; continue; default: break Skip; } } default: if (!isWhitespace(expr[cursor])) break Skip; } cursor++; } return cursor; } public static boolean isStatementNotManuallyTerminated(char[] expr, int cursor) { if (cursor >= expr.length) return false; int c = cursor; while (c != expr.length && isWhitespace(expr[c])) c++; return !(c != expr.length && expr[c] == ';'); } public static int captureToEOS(char[] expr, int cursor, ParserContext pCtx) { while (cursor != expr.length) { switch (expr[cursor]) { case '(': case '[': case '{': if ((cursor = balancedCaptureWithLineAccounting(expr, cursor, expr[cursor], pCtx)) >= expr.length) return cursor; break; case '"': case '\'': cursor = captureStringLiteral(expr[cursor], expr, cursor, expr.length); break; case ',': case ';': case '}': return cursor; } cursor++; } return cursor; } /** * From the specified cursor position, trim out any whitespace between the current position and the end of the * last non-whitespace character. * * @param pos - current position * @return new position. */ public static int trimLeft(char[] expr, int start, int pos) { if (pos > expr.length) pos = expr.length; while (pos != 0 && pos >= start && isWhitespace(expr[pos - 1])) pos--; return pos; } /** * From the specified cursor position, trim out any whitespace between the current position and beginning of the * first non-whitespace character. * * @param pos - * @return - */ public static int trimRight(char[] expr, int start, int pos) { while (pos != expr.length && isWhitespace(expr[pos])) pos++; return pos; } public static char[] subArray(char[] expr, final int start, final int end) { if (start >= end) return new char[0]; char[] newA = new char[end - start]; for (int i = 0; i != newA.length; i++) { newA[i] = expr[i + start]; } return newA; } /** * This is an important aspect of the core parser tools. This method is used throughout the core parser * and sub-lexical parsers to capture a balanced capture between opening and terminating tokens such as: * ( [ { ' " *
*
* For example: ((foo + bar + (bar - foo)) * 20;
*
*

* If a balanced capture is performed from position 2, we get "(foo + bar + (bar - foo))" back.
* If a balanced capture is performed from position 15, we get "(bar - foo)" back.
* Etc. * * @param chars - * @param start - * @param type - * @return - */ public static int balancedCapture(char[] chars, int start, char type) { int depth = 1; char term = type; switch (type) { case '[': term = ']'; break; case '{': term = '}'; break; case '(': term = ')'; break; } if (type == term) { for (start++; start < chars.length; start++) { if (chars[start] == type) { return start; } } } else { for (start++; start < chars.length; start++) { if (start < chars.length && chars[start] == '/') { if (start + 1 == chars.length) return start; if (chars[start + 1] == '/') { start++; while (start < chars.length && chars[start] != '\n') start++; } else if (chars[start + 1] == '*') { start += 2; while (start < chars.length) { switch (chars[start]) { case '*': if (start + 1 < chars.length && chars[start + 1] == '/') { break; } case '\r': case '\n': break; } start++; } } } if (start == chars.length) return start; if (chars[start] == '\'' || chars[start] == '"') { start = captureStringLiteral(chars[start], chars, start, chars.length); } else if (chars[start] == type) { depth++; } else if (chars[start] == term && --depth == 0) { return start; } } } switch (type) { case '[': throw new CompileException("unbalanced braces [ ... ]", chars, start); case '{': throw new CompileException("unbalanced braces { ... }", chars, start); case '(': throw new CompileException("unbalanced braces ( ... )", chars, start); default: throw new CompileException("unterminated string literal", chars, start); } } public static int balancedCaptureWithLineAccounting(char[] chars, int start, char type, ParserContext pCtx) { int depth = 1; char term = type; switch (type) { case '[': term = ']'; break; case '{': term = '}'; break; case '(': term = ')'; break; } if (type == term) { for (start++; start != chars.length; start++) { if (chars[start] == type) { return start; } } } else { int lines = 0; for (start++; start < chars.length; start++) { if (isWhitespace(chars[start])) { switch (chars[start]) { case '\r': continue; case '\n': if (pCtx != null) pCtx.setLineOffset((short) start); lines++; } } else if (start < chars.length && chars[start] == '/') { if (start + 1 == chars.length) return start; if (chars[start + 1] == '/') { start++; while (start < chars.length && chars[start] != '\n') start++; } else if (chars[start + 1] == '*') { start += 2; Skiploop: while (start != chars.length) { switch (chars[start]) { case '*': if (start + 1 < chars.length && chars[start + 1] == '/') { break Skiploop; } case '\r': case '\n': if (pCtx != null) pCtx.setLineOffset((short) start); lines++; break; } start++; } } } if (start == chars.length) return start; if (chars[start] == '\'' || chars[start] == '"') { start = captureStringLiteral(chars[start], chars, start, chars.length); } else if (chars[start] == type) { depth++; } else if (chars[start] == term && --depth == 0) { if (pCtx != null) pCtx.incrementLineCount(lines); return start; } } } switch (type) { case '[': throw new CompileException("unbalanced braces [ ... ]", chars, start); case '{': throw new CompileException("unbalanced braces { ... }", chars, start); case '(': throw new CompileException("unbalanced braces ( ... )", chars, start); default: throw new CompileException("unterminated string literal", chars, start); } } public static String handleStringEscapes(char[] input) { int escapes = 0; for (int i = 0; i < input.length; i++) { if (input[i] == '\\') { escapes += handleEscapeSequence(input, ++i); } } if (escapes == 0) return new String(input); char[] processedEscapeString = new char[input.length - escapes]; int cursor = 0; for (char aName : input) { if (aName != 0) { processedEscapeString[cursor++] = aName; } } return new String(processedEscapeString); } public static int captureStringLiteral(final char type, final char[] expr, int cursor, int length) { while (++cursor < length && expr[cursor] != type) { if (expr[cursor] == '\\') cursor++; } if (cursor >= length || expr[cursor] != type) { throw new CompileException("unterminated literal", expr, cursor); } return cursor; } public static void parseWithExpressions(String nestParm, char[] block, int begin, int ending, Object ctx, VariableResolverFactory factory) { /** * * MAINTENANCE NOTE: A COMPILING VERSION OF THIS CODE IS DUPLICATED IN: WithNode * */ int start = begin; String parm = ""; int end = -1; int oper = -1; for (int i = begin; i < ending; i++) { switch (block[i]) { case '{': case '[': case '(': i = balancedCapture(block, i, block[i]); continue; case '/': if (i < ending && block[i + 1] == '/') { while (i < ending && block[i] != '\n') block[i++] = ' '; if (parm == null) start = i; } else if (i < ending && block[i + 1] == '*') { int len = ending - 1; while (i < len && !(block[i] == '*' && block[i + 1] == '/')) { block[i++] = ' '; } block[i++] = ' '; block[i++] = ' '; if (parm == null) start = i; } else if (i < ending && block[i + 1] == '=') { oper = Operator.DIV; } continue; case '%': case '*': case '-': case '+': if (i + 1 < ending && block[i + 1] == '=') { oper = opLookup(block[i]); } continue; case '=': parm = new String(block, start, i - start - (oper != -1 ? 1 : 0)).trim(); start = i + 1; continue; case ',': if (end == -1) end = i; if (parm == null) { MVEL.eval(new StringAppender(nestParm).append('.') .append(block, start, end - start).toString(), ctx, factory); oper = -1; start = ++i; } else { MVEL.setProperty(ctx, parm, MVEL.eval(new String(createShortFormOperativeAssignment(new StringAppender(nestParm).append(".").append(parm).toString(), subset(block, start, end - start), oper)), ctx, factory)); parm = null; oper = -1; start = ++i; } end = -1; break; } } if (start != (end = ending)) { if (parm == null || "".equals(parm)) { MVEL.eval(new StringAppender(nestParm).append('.') .append(block, start, end - start).toString(), ctx, factory); } else { MVEL.setProperty(ctx, parm, MVEL.eval( new String(createShortFormOperativeAssignment(new StringAppender(nestParm).append(".").append(parm).toString(), subset(block, start, end - start), oper)), ctx, factory)); } } } public static Object handleNumericConversion(final char[] val) { if (val.length != 1 && val[0] == '0' && val[1] != '.') { if (!isDigit(val[val.length - 1])) { switch (val[val.length - 1]) { case 'L': case 'l': return Long.decode(new String(val, 0, val.length - 1)); case 'I': return BigInteger.valueOf(Long.decode(new String(val, 0, val.length - 1))); case 'D': return BigDecimal.valueOf(Long.decode(new String(val, 0, val.length - 1))); } } return Integer.decode(new String(val)); } else if (!isDigit(val[val.length - 1])) { switch (val[val.length - 1]) { case 'l': case 'L': return java.lang.Long.parseLong(new String(val, 0, val.length - 1)); case '.': case 'd': case 'D': return parseDouble(new String(val, 0, val.length - 1)); case 'f': case 'F': return java.lang.Float.parseFloat(new String(val, 0, val.length - 1)); case 'I': return new BigInteger(new String(val, 0, val.length - 1)); case 'B': return new BigDecimal(new String(val, 0, val.length - 1)); } throw new CompileException("unrecognized numeric literal"); } else { switch (numericTest(val)) { case DataTypes.FLOAT: return java.lang.Float.parseFloat(new String(val)); case INTEGER: return java.lang.Integer.parseInt(new String(val)); case LONG: return java.lang.Long.parseLong(new String(val)); case DOUBLE: return parseDouble(new String(val)); case DataTypes.BIG_DECIMAL: return new BigDecimal(val, MathContext.DECIMAL128); default: return new String(val); } } } public static boolean isNumeric(Object val) { if (val == null) return false; Class clz; if (val instanceof Class) { clz = (Class) val; } else { clz = val.getClass(); } return clz == int.class || clz == long.class || clz == short.class || clz == double.class || clz == float.class || Number.class.isAssignableFrom(clz); } public static int numericTest(final char[] val) { boolean fp = false; int len = val.length; char c; int i = 0; if (len > 1) { if (val[0] == '-') i++; else if (val[0] == '~') { i++; if (val[1] == '-') i++; } } for (; i < len; i++) { if (!isDigit(c = val[i])) { switch (c) { case '.': fp = true; break; case 'e': case 'E': fp = true; if (i++ < len && val[i] == '-') i++; break; default: return -1; } } } if (len != 0) { if (fp) { return DOUBLE; } else if (len > 9) { return LONG; } else { return INTEGER; } } return -1; } public static boolean isNumber(Object val) { if (val == null) return false; if (val instanceof String) return isNumber((String) val); if (val instanceof char[]) return isNumber((char[]) val); return val instanceof Integer || val instanceof BigDecimal || val instanceof BigInteger || val instanceof Float || val instanceof Double || val instanceof Long || val instanceof Short || val instanceof Character; } public static boolean isNumber(final String val) { int len = val.length(); char c; boolean f = true; int i = 0; if (len > 1) { if (val.charAt(0) == '-') i++; else if (val.charAt(0) == '~') { i++; if (val.charAt(1) == '-') i++; } } for (; i < len; i++) { if (!isDigit(c = val.charAt(i))) { if (c == '.' && f) { f = false; } else { return false; } } } return len > 0; } public static boolean isNumber(char[] val) { int len = val.length; char c; boolean f = true; int i = 0; if (len > 1) { switch (val[0]) { case '-': if (val[1] == '-') i++; case '~': i++; } } for (; i < len; i++) { if (!isDigit(c = val[i])) { if (f && c == '.') { f = false; } else if (len != 1 && i == len - 1) { switch (c) { case 'l': case 'L': case 'f': case 'F': case 'd': case 'D': case 'I': case 'B': return true; case '.': throw new CompileException("invalid number literal: " + new String(val)); } return false; } else if (i == 1 && c == 'x' && val[0] == '0') { for (i++; i < len; i++) { if (!isDigit(c = val[i])) { if ((c < 'A' || c > 'F') && (c < 'a' || c > 'f')) { if (i == len - 1) { switch (c) { case 'l': case 'L': case 'I': case 'B': return true; } } return false; } } } return len - 2 > 0; } else if (i != 0 && (i + 1) < len && (c == 'E' || c == 'e')) { if (val[++i] == '-' || val[i] == '+') i++; } else { if (i != 0) throw new CompileException("invalid number literal: " + new String(val)); return false; } } } return len > 0; } public static int find(char[] c, char find) { for (int i = 0; i < c.length; i++) if (c[i] == find) return i; return -1; } public static int findLast(char[] c, char find) { for (int i = c.length - 1; i != -1; i--) if (c[i] == find) return i; return -1; } public static String createStringTrimmed(char[] s) { int start = 0, end = s.length; while (start != end && s[start] < '\u0020' + 1) start++; while (end != start && s[end - 1] < '\u0020' + 1) end--; return new String(s, start, end - start); } public static String createStringTrimmed(char[] s, int start, int length) { if ((length = start + length) > s.length) return new String(s); while (start != length && s[start] < '\u0020' + 1) { start++; } while (length != start && s[length - 1] < '\u0020' + 1) { length--; } return new String(s, start, length - start); } public static boolean endsWith(char[] c, char[] test) { if (test.length > c.length) return false; int tD = test.length - 1; int cD = c.length - 1; while (tD != -1) { if (c[cD--] != test[tD--]) return false; } return true; } public static boolean isIdentifierPart(final int c) { return ((c > 96 && c < 123) || (c > 64 && c < 91) || (c > 47 && c < 58) || (c == '_') || (c == '$') || Character.isJavaIdentifierPart(c)); } public static boolean isDigit(final int c) { return c > ('0' - 1) && c < ('9' + 1); } public static float similarity(String s1, String s2) { if (s1 == null || s2 == null) return s1 == null && s2 == null ? 1f : 0f; char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); char[] comp; char[] against; float same = 0; float baselength; int cur1 = 0; if (c1.length > c2.length) { baselength = c1.length; comp = c1; against = c2; } else { baselength = c2.length; comp = c2; against = c1; } while (cur1 < comp.length && cur1 < against.length) { if (comp[cur1] == against[cur1]) { same++; } cur1++; } return same / baselength; } public static int findAbsoluteLast(char[] array) { int depth = 0; for (int i = array.length - 1; i >= 0; i--) { if (array[i] == ']') { depth++; } if (array[i] == '[') { depth--; } if (depth == 0 && array[i] == '.' || array[i] == '[') return i; } return -1; } public static Class getBaseComponentType(Class cls) { while (cls.isArray()) { cls = cls.getComponentType(); } return cls; } public static Class getSubComponentType(Class cls) { if (cls.isArray()) { cls = cls.getComponentType(); } return cls; } public static boolean isJunct(char c) { switch (c) { case '[': case '(': return true; default: return isWhitespace(c); } } public static int opLookup(char c) { switch (c) { case '|': return Operator.BW_OR; case '&': return Operator.BW_AND; case '^': return Operator.BW_XOR; case '*': return Operator.MULT; case '/': return Operator.DIV; case '+': return Operator.ADD; case '%': return Operator.MOD; case '\u00AB': return Operator.BW_SHIFT_LEFT; case '\u00BB': return Operator.BW_SHIFT_RIGHT; case '\u00AC': return Operator.BW_USHIFT_RIGHT; } return -1; } /** * Check if the specified string is a reserved word in the parser. * * @param name - * @return - */ public static boolean isReservedWord(String name) { return LITERALS.containsKey(name) || AbstractParser.OPERATORS.containsKey(name); } /** * Check if the specfied string represents a valid name of label. * * @param name - * @return - */ public static boolean isNotValidNameorLabel(String name) { for (char c : name.toCharArray()) { if (c == '.') return true; else if (!isIdentifierPart(c)) return true; } return false; } public static final class WithStatementPair implements java.io.Serializable { private String parm; private String value; public WithStatementPair(String parm, String value) { this.parm = parm; this.value = value; } public String getParm() { return parm; } public void setParm(String parm) { this.parm = parm; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public void eval(Object ctx, VariableResolverFactory vrf) { if (parm == null) { MVEL.eval(value, ctx, vrf); } else { MVEL.setProperty(ctx, parm, MVEL.eval(value, ctx, vrf)); } } } public static void checkNameSafety(String name) { if (isReservedWord(name)) { throw new CompileException("illegal use of reserved word: " + name); } else if (isDigit(name.charAt(0))) { throw new CompileException("not an identifier"); } } public static FileWriter getDebugFileWriter() throws IOException { return new FileWriter(new File(getDebuggingOutputFileName()), true); } public static boolean isPrimitiveWrapper(Class clazz) { return clazz == Integer.class || clazz == Boolean.class || clazz == Long.class || clazz == Double.class || clazz == Float.class || clazz == Short.class || clazz == Byte.class || clazz == Character.class; } public static Serializable subCompileExpression(char[] expression) { return _optimizeTree(new ExpressionCompiler(expression)._compile()); } public static Serializable subCompileExpression(char[] expression, ParserContext ctx) { ExpressionCompiler c = new ExpressionCompiler(expression); if (ctx != null) c.setPCtx(ctx); return _optimizeTree(c._compile()); } public static Serializable subCompileExpression(String expression, ParserContext ctx) { ExpressionCompiler c = new ExpressionCompiler(expression); c.setPCtx(ctx); return _optimizeTree(c._compile()); } public static Serializable optimizeTree(final CompiledExpression compiled) { /** * If there is only one token, and it's an identifier, we can optimize this as an accessor expression. */ if (!compiled.isImportInjectionRequired() && compiled.getParserContext().isAllowBootstrapBypass() && compiled.isSingleNode()) { return _optimizeTree(compiled); } return compiled; } private static Serializable _optimizeTree(final CompiledExpression compiled) { /** * If there is only one token, and it's an identifier, we can optimize this as an accessor expression. */ if (compiled.isSingleNode()) { ASTNode tk = compiled.getFirstNode(); if (tk.isLiteral() && !tk.isThisVal()) { return new ExecutableLiteral(tk.getLiteralValue()); } return tk.canSerializeAccessor() ? new ExecutableAccessorSafe(tk, compiled.getKnownEgressType()) : new ExecutableAccessor(tk, compiled.getKnownEgressType()); } return compiled; } public static boolean isWhitespace(char c) { return c < '\u0020' + 1; } public static String repeatChar(char c, int times) { char[] n = new char[times]; for (int i = 0; i < times; i++) { n[i] = c; } return new String(n); } public static char[] loadFromFile(File file) throws IOException { return loadFromFile(file, null); } public static char[] loadFromFile(File file, String encoding) throws IOException { if (!file.exists()) throw new CompileException("cannot find file: " + file.getName()); FileInputStream inStream = null; ReadableByteChannel fc = null; try { fc = (inStream = new FileInputStream(file)).getChannel(); ByteBuffer buf = allocateDirect(10); StringAppender sb = new StringAppender((int) file.length(), encoding); int read = 0; while (read >= 0) { buf.rewind(); read = fc.read(buf); buf.rewind(); for (; read > 0; read--) { sb.append(buf.get()); } } //noinspection unchecked return sb.toChars(); } catch (FileNotFoundException e) { // this can't be thrown, we check for this explicitly. } finally { if (inStream != null) inStream.close(); if (fc != null) fc.close(); } return null; } public static char[] readIn(InputStream inStream, String encoding) throws IOException { try { byte[] buf = new byte[10]; StringAppender sb = new StringAppender(10, encoding); int bytesRead; while ((bytesRead = inStream.read(buf)) > 0) { for (int i = 0; i < bytesRead; i++) { sb.append(buf[i]); } } //noinspection unchecked return sb.toChars(); } finally { if (inStream != null) inStream.close(); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/SimpleIndexHashMapWrapper.java0000644000175000017500000001260411257005261026516 0ustar drazzibdrazzibpackage org.mvel2.util; import java.util.*; /** * As most use-cases of the VariableResolverFactory's rely on Maps, this is meant to implement a simple wrapper * which records index positions for use by the optimizing facilities. *

* This wrapper also ensures that the Map is only additive. You cannot remove an element once it's been added. * While this may seem like an odd limitation, it is consistent with the language semantics. (ie. it's not possible * to delete a variable at runtime once it's been declared). * * @author Mike Brock */ public class SimpleIndexHashMapWrapper implements Map { private int indexCounter; private final Map> wrappedMap; private final ArrayList> indexBasedLookup; public SimpleIndexHashMapWrapper() { this.wrappedMap = new HashMap>(); this.indexBasedLookup = new ArrayList>(); } public SimpleIndexHashMapWrapper(SimpleIndexHashMapWrapper wrapper, boolean allocateOnly) { this.indexBasedLookup = new ArrayList>(wrapper.indexBasedLookup.size()); this.wrappedMap = new HashMap>(); ValueContainer vc; int index = 0; if (allocateOnly) { for (ValueContainer key : wrapper.indexBasedLookup) { vc = new ValueContainer(index++, key.getKey(), null); indexBasedLookup.add(vc); wrappedMap.put(key.getKey(), vc); } } else { for (ValueContainer key : wrapper.indexBasedLookup) { vc = new ValueContainer(index++, key.getKey(), key.getValue()); indexBasedLookup.add(vc); wrappedMap.put(key.getKey(), vc); } } } public SimpleIndexHashMapWrapper(K[] keys) { this.wrappedMap = new HashMap>(keys.length * 2); this.indexBasedLookup = new ArrayList>(keys.length); initWithKeys(keys); } public SimpleIndexHashMapWrapper(K[] keys, int initialCapacity, float load) { this.wrappedMap = new HashMap>(initialCapacity * 2, load); this.indexBasedLookup = new ArrayList>(initialCapacity); initWithKeys(keys); } public void initWithKeys(K[] keys) { int index = 0; ValueContainer vc; for (K key : keys) { vc = new ValueContainer(index++, key, null); wrappedMap.put(key, vc); indexBasedLookup.add(vc); } } public void addKey(K key) { ValueContainer vc = new ValueContainer(indexCounter++, key, null); this.indexBasedLookup.add(vc); this.wrappedMap.put(key, vc); } public void addKey(K key, V value) { ValueContainer vc = new ValueContainer(indexCounter++, key, value); this.indexBasedLookup.add(vc); this.wrappedMap.put(key, vc); } public int size() { return wrappedMap.size(); } public boolean isEmpty() { return wrappedMap.isEmpty(); } public boolean containsKey(Object key) { return wrappedMap.containsKey(key); } public boolean containsValue(Object value) { return wrappedMap.containsValue(value); } public V get(Object key) { return wrappedMap.get(key).getValue(); } public V getByIndex(int index) { return indexBasedLookup.get(index).getValue(); } public K getKeyAtIndex(int index) { return indexBasedLookup.get(index).getKey(); } public int indexOf(K key) { return wrappedMap.get(key).getIndex(); } public V put(K key, V value) { ValueContainer vc = wrappedMap.get(key); if (vc == null) throw new RuntimeException("cannot add a new entry. you must allocate a new key with addKey() first."); indexBasedLookup.add(vc); return wrappedMap.put(key, vc).getValue(); } public void putAtIndex(int index, V value) { ValueContainer vc = indexBasedLookup.get(index); vc.setValue(value); } public V remove(Object key) { throw new UnsupportedOperationException("cannot remove keys"); } public void putAll(Map m) { // wrappedMap.put } public void clear() { throw new UnsupportedOperationException("cannot clear map"); } public Set keySet() { return wrappedMap.keySet(); } public Collection values() { throw new UnsupportedOperationException(); } public Set> entrySet() { throw new UnsupportedOperationException(); } private class ValueContainer { private int index; private K key; private V value; public ValueContainer(int index, K key, V value) { this.index = index; this.key = key; this.value = value; } public int getIndex() { return index; } public K getKey() { return key; } public V getValue() { return value; } void setKey(K key) { this.key = key; } void setValue(V value) { this.value = value; } } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/FastList.java0000644000175000017500000001746011174416767023247 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.ImmutableElementException; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; public class FastList extends AbstractList implements Externalizable { private E[] elements; private int size = 0; private boolean updated = false; public FastList(int size) { elements = (E[]) new Object[size == 0 ? 1 : size]; } public FastList(E[] elements) { this.size = (this.elements = elements).length; } public FastList() { this(10); } public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(size); for (int i = 0; i < size; i++) { out.writeObject(elements[i]); } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { elements = (E[]) new Object[size = in.readInt()]; for (int i = 0; i < size; i++) { elements[i] = (E) in.readObject(); } } public E get(int index) { return (E) elements[index]; } public int size() { return size; } public boolean add(E o) { if (size == elements.length) { increaseSize(elements.length * 2); } elements[size++] = o; return true; } public E set(int i, E o) { if (!updated) copyArray(); E old = elements[i]; elements[i] = o; return old; } public void add(int i, E o) { if (size == elements.length) { increaseSize(elements.length * 2); } for (int c = size; c != i; c--) { elements[c] = elements[c - 1]; } elements[i] = o; size++; } public E remove(int i) { E old = elements[i]; for (int c = i + 1; c < size; c++) { elements[c - 1] = elements[c]; elements[c] = null; } size--; return old; } public int indexOf(Object o) { if (o == null) return -1; for (int i = 0; i < elements.length; i++) { if (o.equals(elements[i])) return i; } return -1; } public int lastIndexOf(Object o) { if (o == null) return -1; for (int i = elements.length - 1; i != -1; i--) { if (o.equals(elements[i])) return i; } return -1; } public void clear() { elements = (E[]) new Object[1]; size = 0; } public boolean addAll(int i, Collection collection) { int offset = collection.size(); ensureCapacity(offset + size); if (i != 0) { // copy forward all elements that the insertion is occuring before for (int c = i; c != (i + offset); c++) { elements[c + offset + 1] = elements[c]; } } int c = size == 0 ? -1 : 0; for (E o : collection) { elements[offset + c++] = o; } size += offset; return true; } public Iterator iterator() { final int size = this.size; return new Iterator() { private int cursor = 0; public boolean hasNext() { return cursor < size; } public Object next() { return elements[cursor++]; } public void remove() { throw new ImmutableElementException("cannot change elements in immutable list"); } }; } public ListIterator listIterator() { return new ListIterator() { private int i = 0; public boolean hasNext() { return i < size; } public E next() { return elements[i++]; } public boolean hasPrevious() { return i > 0; } public E previous() { return elements[i--]; } public int nextIndex() { return i++; } public int previousIndex() { return i--; } public void remove() { throw new java.lang.UnsupportedOperationException(); } public void set(E o) { elements[i] = o; } public void add(Object o) { throw new java.lang.UnsupportedOperationException(); } }; } public ListIterator listIterator(int i) { return super.listIterator(i); } public List subList(int i, int i1) { return super.subList(i, i1); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List)) return false; ListIterator e1 = listIterator(); ListIterator e2 = ((List) o).listIterator(); while (e1.hasNext() && e2.hasNext()) { Object o1 = e1.next(); Object o2 = e2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) return false; } return !(e1.hasNext() || e2.hasNext()); } public int hashCode() { return super.hashCode(); } protected void removeRange(int i, int i1) { throw new RuntimeException("not implemented"); } public boolean isEmpty() { return size == 0; } public boolean contains(Object o) { return indexOf(o) != -1; } public Object[] toArray() { return toArray(new Object[size]); } public Object[] toArray(Object[] objects) { if (objects.length < size) objects = new Object[size]; for (int i = 0; i < size; i++) { objects[i] = elements[i]; } return objects; } public boolean remove(Object o) { throw new RuntimeException("not implemented"); } public boolean containsAll(Collection collection) { throw new RuntimeException("not implemented"); } public boolean addAll(Collection collection) { return addAll(size, collection); } public boolean removeAll(Collection collection) { throw new RuntimeException("not implemented"); } public boolean retainAll(Collection collection) { throw new RuntimeException("not implemented"); } private void ensureCapacity(int additional) { if ((size + additional) > elements.length) increaseSize((size + additional) * 2); } private void copyArray() { increaseSize(elements.length); } private void increaseSize(int newSize) { E[] newElements = (E[]) new Object[newSize]; for (int i = 0; i < elements.length; i++) newElements[i] = elements[i]; elements = newElements; updated = true; } public String toString() { return super.toString(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/ASTIterator.java0000644000175000017500000000343411354743601023641 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.ast.ASTNode; import java.io.Serializable; /** * The ASTIterator interface defines the functionality required by the enginer, for compiletime and runtime * operations. Unlike other script implementations, MVEL does not use a completely normalized AST tree for * it's execution. Instead, nodes are organized into a linear order and delivered via this iterator interface, * much like bytecode instructions. */ public interface ASTIterator extends Serializable { public void reset(); public ASTNode nextNode(); public void skipNode(); public ASTNode peekNext(); public ASTNode peekNode(); public ASTNode peekLast(); // public boolean peekNextTokenFlags(int flags); public void back(); public ASTNode nodesBack(int offset); public ASTNode nodesAhead(int offset); public boolean hasMoreNodes(); public String showNodeChain(); public ASTNode firstNode(); public int size(); public int index(); public void finish(); public void addTokenNode(ASTNode node); public void addTokenNode(ASTNode node1, ASTNode node2); } mvel-2.0.18.orig/src/main/java/org/mvel2/util/Soundex.java0000644000175000017500000000462611100376377023132 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.util.StringAppender; /** * An implementation of Knuth's soundex algorithm. Used by the soundslike operator. */ public class Soundex { /* Implements the mapping * from: AEHIOUWYBFPVCGJKQSXZDTLMNR * to: 00000000111122222222334556 */ public static final char[] MAP = { //A B C D E F G H I J K L M '0', '1', '2', '3', '0', '1', '2', '0', '0', '2', '2', '4', '5', //N O P W R S T U V W X Y Z '5', '0', '1', '2', '6', '2', '3', '0', '1', '0', '2', '0', '2' }; /** * Convert the given String to its Soundex code. * * @param s input string * @return null If the given string can't be mapped to Soundex. */ public static String soundex(String s) { char[] ca = s.toUpperCase().toCharArray(); StringAppender res = new StringAppender(); char c, prev = '?'; // Main loop: find up to 4 chars that map. for (int i = 0; i < ca.length && res.length() < 4 && (c = ca[i]) != ','; i++) { // Check to see if the given character is alphabetic. // Text is already converted to uppercase. Algorithm // only handles ASCII letters, do NOT use Character.isLetter()! // Also, skip double letters. if (c >= 'A' && c <= 'Z' && c != prev) { prev = c; char m = MAP[c - 'A']; if (m != '0') res.append(m); } } if (res.length() == 0) return null; for (int i = res.length(); i < 4; i++) res.append('0'); return res.toString(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/ASTLinkedList.java0000644000175000017500000001067711354743601024121 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.ast.ASTNode; public class ASTLinkedList implements ASTIterator { private ASTNode firstASTNode; private ASTNode current; private ASTNode last; private int size; public ASTLinkedList() { } public ASTLinkedList(ASTIterator iter) { this.current = this.firstASTNode = iter.firstNode(); } public ASTLinkedList(ASTNode firstASTNode) { this.current = this.firstASTNode = firstASTNode; } public ASTLinkedList(ASTNode firstASTNode, int size) { this.current = this.firstASTNode = firstASTNode; this.size = size; } public void addTokenNode(ASTNode astNode) { size++; if (this.firstASTNode == null) { this.firstASTNode = this.current = astNode; } else { this.last = this.current = (this.current.nextASTNode = astNode); } } public void addTokenNode(ASTNode astNode, ASTNode token2) { size += 2; if (this.firstASTNode == null) { this.last = this.current = ((this.firstASTNode = astNode).nextASTNode = token2); } else { this.last = this.current = (this.current.nextASTNode = astNode).nextASTNode = token2; } } public ASTNode firstNode() { return firstASTNode; } public boolean isSingleNode() { return size == 1 || (size == 2 && firstASTNode.fields == -1); } public ASTNode firstNonSymbol() { if (firstASTNode.fields == -1) { return firstASTNode.nextASTNode; } else { return firstASTNode; } } public void reset() { this.current = firstASTNode; } public boolean hasMoreNodes() { return this.current != null; } public ASTNode nextNode() { if (current == null) return null; try { return current; } finally { current = current.nextASTNode; } } public void skipNode() { if (current != null) current = current.nextASTNode; } public ASTNode peekNext() { if (current != null && current.nextASTNode != null) return current.nextASTNode; else return null; } public ASTNode peekNode() { if (current == null) return null; return current; } public void removeToken() { if (current != null) { current = current.nextASTNode; } } public ASTNode peekLast() { return last; } public ASTNode nodesBack(int offset) { throw new RuntimeException("unimplemented"); } public ASTNode nodesAhead(int offset) { if (current == null) return null; ASTNode cursor = null; for (int i = 0; i < offset; i++) { if ((cursor = current.nextASTNode) == null) return null; } return cursor; } public void back() { throw new RuntimeException("unimplemented"); } public String showNodeChain() { throw new RuntimeException("unimplemented"); } public int size() { return size; } public int index() { return -1; } public void setCurrentNode(ASTNode node) { this.current = node; } public void finish() { reset(); ASTNode last = null; ASTNode curr; while (hasMoreNodes()) { if ((curr = nextNode()).isDiscard()) { if (last == null) { last = firstASTNode = nextNode(); } else { last.nextASTNode = nextNode(); } continue; } if (!hasMoreNodes()) break; last = curr; } this.last = last; reset(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/PropertyTools.java0000644000175000017500000001363511167246104024347 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import static org.mvel2.DataConversion.canConvert; import org.mvel2.ParserContext; import org.mvel2.compiler.PropertyVerifier; import static org.mvel2.util.ParseTools.boxPrimitive; import static java.lang.String.valueOf; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.PUBLIC; import static java.lang.reflect.Modifier.isPublic; import java.util.Collection; import java.util.Map; public class PropertyTools { public static boolean isEmpty(Object o) { if (o != null) { if (o instanceof Object[]) { return ((Object[]) o).length == 0 || (((Object[]) o).length == 1 && isEmpty(((Object[]) o)[0])); } else { return ("".equals(valueOf(o))) || "null".equals(valueOf(o)) || (o instanceof Collection && ((Collection) o).size() == 0) || (o instanceof Map && ((Map) o).size() == 0); } } return true; } public static Method getSetter(Class clazz, String property) { property = ReflectionUtil.getSetter(property); for (Method meth : clazz.getMethods()) { if ((meth.getModifiers() & PUBLIC) != 0 && meth.getParameterTypes().length == 1 && property.equals(meth.getName())) { return meth; } } return null; } public static Method getSetter(Class clazz, String property, Class type) { property = ReflectionUtil.getSetter(property); for (Method meth : clazz.getMethods()) { if ((meth.getModifiers() & PUBLIC) != 0 && meth.getParameterTypes().length == 1 && property.equals(meth.getName()) && (type == null || canConvert(meth.getParameterTypes()[0], type))) { return meth; } } return null; } public static boolean hasGetter(Field field) { Method meth = getGetter(field.getDeclaringClass(), field.getName()); return meth != null && field.getType().isAssignableFrom(meth.getReturnType()); } public static boolean hasSetter(Field field) { Method meth = getSetter(field.getDeclaringClass(), field.getName()); return meth != null && meth.getParameterTypes().length == 1 && field.getType().isAssignableFrom(meth.getParameterTypes()[0]); } public static Method getGetter(Class clazz, String property) { String isGet = ReflectionUtil.getIsGetter(property); property = ReflectionUtil.getGetter(property); for (Method meth : clazz.getMethods()) { if ((meth.getModifiers() & PUBLIC) != 0 && meth.getParameterTypes().length == 0 && (property.equals(meth.getName()) || isGet.equals(meth.getName()))) { return meth; } } return null; } public static Class getReturnType(Class clazz, String property, ParserContext ctx) { return new PropertyVerifier(property, ctx, clazz).analyze(); } public static Member getFieldOrAccessor(Class clazz, String property) { for (Field f : clazz.getFields()) { if (property.equals(f.getName())) { if ((f.getModifiers() & PUBLIC) != 0) return f; break; } } return getGetter(clazz, property); } public static Member getFieldOrWriteAccessor(Class clazz, String property) { Field field; try { if ((field = clazz.getField(property)) != null && isPublic(field.getModifiers())) { return field; } } catch (NullPointerException e) { return null; } catch (NoSuchFieldException e) { // do nothing. } return getSetter(clazz, property); } public static Member getFieldOrWriteAccessor(Class clazz, String property, Class type) { for (Field f : clazz.getFields()) { if (property.equals(f.getName()) && (type == null || canConvert(f.getType(), type))) { return f; } } return getSetter(clazz, property, type); } public static boolean contains(Object toCompare, Object testValue) { if (toCompare == null) return false; else if (toCompare instanceof String) return ((String) toCompare).contains(valueOf(testValue)); // return ((String) toCompare).indexOf(valueOf(testValue)) > -1; else if (toCompare instanceof Collection) return ((Collection) toCompare).contains(testValue); else if (toCompare instanceof Map) return ((Map) toCompare).containsKey(testValue); else if (toCompare.getClass().isArray()) { for (Object o : ((Object[]) toCompare)) { if (testValue == null && o == null) return true; else if (o != null && o.equals(testValue)) return true; } } return false; } public static boolean isAssignable(Class to, Class from) { return (to.isPrimitive() ? boxPrimitive(to) : to).isAssignableFrom(from.isPrimitive() ? boxPrimitive(from) : from); } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/JITClassLoader.java0000644000175000017500000000307011234624777024250 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import sun.misc.Unsafe; import java.lang.reflect.Field; public class JITClassLoader extends ClassLoader implements MVELClassLoader { private static boolean sunJVM; private static Object sunUnsafe; static { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); sunUnsafe = f.get(null); sunJVM = true; } catch (Throwable t) { // t.printStackTrace(); sunJVM = false; } } public JITClassLoader(ClassLoader classLoader) { super(classLoader); } public Class defineClassX(String className, byte[] b, int off, int len) { if (sunJVM) { return ((Unsafe) sunUnsafe).defineClass(className, b, off, len); } else { return super.defineClass(className, b, off, len); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/FunctionParser.java0000644000175000017500000000736411253250512024440 0ustar drazzibdrazzibpackage org.mvel2.util; import org.mvel2.CompileException; import org.mvel2.ParserContext; import org.mvel2.compiler.AbstractParser; import org.mvel2.ast.EndOfStatement; import org.mvel2.ast.Function; import static org.mvel2.util.ParseTools.balancedCaptureWithLineAccounting; import static org.mvel2.util.ParseTools.createStringTrimmed; public class FunctionParser { private String name; private int cursor; private int endOffset; private char[] expr; private ParserContext pCtx; private ExecutionStack splitAccumulator; public FunctionParser(String functionName, int cursor, int endOffset, char[] expr, ParserContext pCtx, ExecutionStack splitAccumulator) { this.name = functionName; this.cursor = cursor; this.endOffset = endOffset; this.expr = expr; this.pCtx = pCtx; this.splitAccumulator = splitAccumulator; } public Function parse() { int start = cursor; int startCond = 0; int endCond = 0; int blockStart; int blockEnd; cursor = ParseTools.captureToNextTokenJunction(expr, cursor, pCtx); if (expr[cursor = ParseTools.nextNonBlank(expr, cursor)] == '(') { /** * If we discover an opening bracket after the function name, we check to see * if this function accepts parameters. */ endCond = cursor = balancedCaptureWithLineAccounting(expr, startCond = cursor, '(', pCtx); startCond++; cursor++; cursor = ParseTools.skipWhitespace(expr, cursor, pCtx); if (cursor >= endOffset) { throw new CompileException("incomplete statement", expr, cursor); } else if (expr[cursor] == '{') { blockEnd = cursor = balancedCaptureWithLineAccounting(expr, blockStart = cursor, '{', pCtx); } else { blockStart = cursor - 1; cursor = ParseTools.captureToEOS(expr, cursor, pCtx); blockEnd = cursor; } } else { /** * This function has not parameters. */ if (expr[cursor] == '{') { /** * This function is bracketed. We capture the entire range in the brackets. */ blockEnd = cursor = balancedCaptureWithLineAccounting(expr, blockStart = cursor, '{', pCtx); } else { /** * This is a single statement function declaration. We only capture the statement. */ blockStart = cursor - 1; cursor = ParseTools.captureToEOS(expr, cursor, pCtx); blockEnd = cursor; } } /** * Trim any whitespace from the captured block range. */ blockStart = ParseTools.trimRight(expr, start, blockStart + 1); blockEnd = ParseTools.trimLeft(expr, start, blockEnd); cursor++; /** * Check if the function is manually terminated. */ if (splitAccumulator != null && ParseTools.isStatementNotManuallyTerminated(expr, cursor)) { /** * Add an EndOfStatement to the split accumulator in the parser. */ splitAccumulator.add(new EndOfStatement()); } /** * Produce the funciton node. */ return new Function(name, ParseTools.subArray(expr, startCond, endCond), ParseTools.subArray(expr, blockStart, blockEnd), pCtx == null ? pCtx = AbstractParser.getCurrentThreadParserContext() : pCtx); } public String getName() { return name; } public int getCursor() { return cursor; } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/InternalNumber.java0000644000175000017500000000442311077460760024430 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; public class InternalNumber extends BigDecimal { public InternalNumber(char[] chars, int i, int i1) { super(chars, i, i1); } public InternalNumber(char[] chars, int i, int i1, MathContext mathContext) { super(chars, i, i1, mathContext); } public InternalNumber(char[] chars) { super(chars); } public InternalNumber(char[] chars, MathContext mathContext) { super(chars, mathContext); } public InternalNumber(String s) { super(s); } public InternalNumber(String s, MathContext mathContext) { super(s, mathContext); } public InternalNumber(double v) { super(v); } public InternalNumber(double v, MathContext mathContext) { super(v, mathContext); } public InternalNumber(BigInteger bigInteger) { super(bigInteger); } public InternalNumber(BigInteger bigInteger, MathContext mathContext) { super(bigInteger, mathContext); } public InternalNumber(BigInteger bigInteger, int i) { super(bigInteger, i); } public InternalNumber(BigInteger bigInteger, int i, MathContext mathContext) { super(bigInteger, i, mathContext); } public InternalNumber(int i) { super(i); } public InternalNumber(int i, MathContext mathContext) { super(i, mathContext); } public InternalNumber(long l) { super(l); } public InternalNumber(long l, MathContext mathContext) { super(l, mathContext); } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/ReflectionUtil.java0000644000175000017500000000710611313753100024416 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import static java.lang.System.arraycopy; import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Utilities for working with reflection. */ public class ReflectionUtil { private static final int CASE_OFFSET = ('z' - 'Z'); /** * This new method 'slightly' outperforms the old method, it was * essentially a perfect example of me wasting my time and a * premature optimization. But what the hell... * * @param s - * @return String */ public static String getSetter(String s) { char[] chars = new char[s.length() + 3]; chars[0] = 's'; chars[1] = 'e'; chars[2] = 't'; if (s.charAt(0) > 'Z') { chars[3] = (char) (s.charAt(0) - CASE_OFFSET); } else { chars[3] = s.charAt(0); } for (int i = s.length() - 1; i != 0; i--) { chars[i + 3] = s.charAt(i); } return new String(chars); } public static String getGetter(String s) { char[] c = s.toCharArray(); char[] chars = new char[c.length + 3]; chars[0] = 'g'; chars[1] = 'e'; chars[2] = 't'; if (c[0] > 'Z') { chars[3] = (char) (c[0] - CASE_OFFSET); } else { chars[3] = (c[0]); } arraycopy(c, 1, chars, 4, c.length - 1); return new String(chars); } public static String getIsGetter(String s) { char[] c = s.toCharArray(); char[] chars = new char[c.length + 2]; chars[0] = 'i'; chars[1] = 's'; if (c[0] > 'Z') { chars[2] = (char) (c[0] - CASE_OFFSET); } else { chars[2] = c[0]; } arraycopy(c, 1, chars, 3, c.length - 1); return new String(chars); } public static String getPropertyFromAccessor(String s) { char[] c = s.toCharArray(); char[] chars; if (c.length > 3 && c[1] == 'e' && c[2] == 't') { chars = new char[c.length - 3]; if (c[0] == 'g' || c[0] == 's') { if (c[3] < 'a') { chars[0] = (char) (c[3] + CASE_OFFSET); } else { chars[0] = c[3]; } for (int i = 1; i < chars.length; i++) { chars[i] = c[i + 3]; } return new String(chars); } else { return s; } } else if (c.length > 2 && c[0] == 'i' && c[1] == 's') { chars = new char[c.length - 2]; if (c[2] < 'a') { chars[0] = (char) (c[2] + CASE_OFFSET); } else { chars[0] = c[2]; } for (int i = 1; i < chars.length; i++) { chars[i] = c[i + 2]; } return new String(chars); } return s; } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/ArrayTools.java0000644000175000017500000000251711131056120023562 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; public class ArrayTools { public static boolean isLiteralOnly(char[] array, int start, int end) { end = start + (end - start); for (int i = start; i < end; i++) { if (!ParseTools.isIdentifierPart(array[i])) return false; } return true; } public static int findFirst(char c, char[] array) { for (int i = 0; i < array.length; i++) { if (array[i] == c) return i; } return -1; } public static int findLast(char c, char[] array) { for (int i = array.length - 1; i >= 0; i--) { if (array[i] == c) return i; } return -1; } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/MethodStub.java0000644000175000017500000000420111253250512023537 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.integration.VariableResolverFactory; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; public class MethodStub implements Serializable { private Class classReference; private String name; private transient Method method; public MethodStub() { } public MethodStub(Method method) { this.classReference = method.getDeclaringClass(); this.name = method.getName(); } public MethodStub(Class classReference, String methodName) { this.classReference = classReference; this.name = methodName; } public Class getClassReference() { return classReference; } public void setClassReference(Class classReference) { this.classReference = classReference; } public String getMethodName() { return name; } public void setMethodName(String methodName) { this.name = methodName; } public Method getMethod() { if (method == null) { for (Method method : classReference.getMethods()) { if (name.equals(method.getName())) return this.method = method; } } return method; } public Object call(Object ctx, Object thisCtx, VariableResolverFactory factory, Object[] parameters) throws IllegalAccessException, InvocationTargetException { return method.invoke(ctx, parameters); } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/CompilerTools.java0000644000175000017500000004471511356644701024305 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.CompileException; import org.mvel2.Operator; import static org.mvel2.Operator.PTABLE; import org.mvel2.ParserContext; import org.mvel2.ast.*; import static org.mvel2.compiler.AbstractParser.getCurrentThreadParserContext; import org.mvel2.compiler.*; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.ClassImportResolverFactory; import static org.mvel2.util.ParseTools.__resolveType; import static org.mvel2.util.ParseTools.boxPrimitive; import java.lang.management.OperatingSystemMXBean; import java.util.LinkedHashMap; import java.util.Map; public class CompilerTools { /** * Finalize the payload, by reducing any stack-based-operations to dedicated nodes where possible. * * @param astLinkedList - AST to be optimized. * @param secondPassOptimization - perform a second pass optimization to optimize boolean expressions. * @param ctx - The parser context * @return optimized AST */ public static ASTLinkedList finalizePayload(ASTLinkedList astLinkedList, boolean secondPassOptimization, ParserContext ctx) { ASTLinkedList optimizedAst = new ASTLinkedList(); ASTNode tk, tkOp, tkOp2; /** * Re-process the AST and optimize it. */ while (astLinkedList.hasMoreNodes()) { if ((tk = astLinkedList.nextNode()).getFields() == -1) { optimizedAst.addTokenNode(tk); } else if (astLinkedList.hasMoreNodes()) { if ((tkOp = astLinkedList.nextNode()).getFields() == -1) { optimizedAst.addTokenNode(tk, tkOp); } else if (tkOp.isOperator() && tkOp.getOperator() < 21) { int op = tkOp.getOperator(); int op2; if (op == -1) { throw new CompileException("illegal use of operator: " + tkOp.getName()); } ASTNode tk2 = astLinkedList.nextNode(); BinaryOperation bo; if (tk.getEgressType() == Integer.class && tk2.getEgressType() == Integer.class) { switch (op) { case Operator.ADD: bo = new IntAdd(tk, tk2); break; case Operator.SUB: bo = new IntSub(tk, tk2); break; case Operator.MULT: bo = new IntMult(tk, tk2); break; case Operator.DIV: bo = new IntDiv(tk, tk2); break; default: bo = new BinaryOperation(op, tk, tk2, ctx); break; } } else { /** * Let's see if we can simply the expression more. */ bo = null; boolean inv = tkOp.isOperator(Operator.SUB); boolean reduc = isReductionOpportunity(tkOp, tk2); boolean p_inv = false; while (reduc) { ASTNode oper = astLinkedList.nextNode(); ASTNode rightNode = astLinkedList.nextNode(); if (rightNode == null) break; Object val = new BinaryOperation(oper.getOperator(), inv ? new LiteralNode(signNumber(tk2.getLiteralValue())) : tk2, rightNode) .getReducedValueAccelerated(null, null, null); if (!astLinkedList.hasMoreNodes() && BlankLiteral.INSTANCE.equals(val)) { optimizedAst.addTokenNode(tk); continue; } reduc = astLinkedList.hasMoreNodes() && (reducacbleOperator(astLinkedList.peekNode().getOperator())) && astLinkedList.peekNext().isLiteral(); if (inv) p_inv = true; inv = false; if (!reduc) { bo = new BinaryOperation(tkOp.getOperator(), tk,new LiteralNode(p_inv ? signNumber(val) : val)); } else { tk2 = new LiteralNode(val); } } if (bo == null) bo = new BinaryOperation(op, tk, tk2, ctx); } tkOp2 = null; /** * If we have a chain of math/comparitive operators then we fill them into the tree * right here. */ while (astLinkedList.hasMoreNodes() && (tkOp2 = astLinkedList.nextNode()).isOperator() && tkOp2.getFields() != -1 && (op2 = tkOp2.getOperator()) != -1 && op2 < 21) { if (PTABLE[op2] > PTABLE[op]) { bo.setRightMost(new BinaryOperation(op2, bo.getRightMost(), astLinkedList.nextNode(), ctx)); } else if (bo.getOperation() != op2 && PTABLE[op] == PTABLE[op2]) { if (PTABLE[bo.getOperation()] == PTABLE[op2]) { bo = new BinaryOperation(op2, bo, astLinkedList.nextNode(), ctx); } else { tk2 = astLinkedList.nextNode(); if (isIntOptimizationviolation(bo, tk2)) { bo = new BinaryOperation(bo.getOperation(), bo.getLeft(), bo.getRight(), ctx); } bo.setRight(new BinaryOperation(op2, bo.getRight(), tk2, ctx)); } } else if (PTABLE[bo.getOperation()] >= PTABLE[op2]) { bo = new BinaryOperation(op2, bo, astLinkedList.nextNode(), ctx); } else { tk2 = astLinkedList.nextNode(); if (isIntOptimizationviolation(bo, tk2)) { bo = new BinaryOperation(bo.getOperation(), bo.getLeft(), bo.getRight(), ctx); } bo.setRight(new BinaryOperation(op2, bo.getRight(), tk2, ctx)); } op = op2; tkOp = tkOp2; } if (tkOp2 != null && tkOp2 != tkOp) { optimizeOperator(tkOp2.getOperator(), bo, tkOp2, astLinkedList, optimizedAst); } else { optimizedAst.addTokenNode(bo); } } else if (tkOp.isOperator()) { optimizeOperator(tkOp.getOperator(), tk, tkOp, astLinkedList, optimizedAst); } else if (!tkOp.isAssignment() && !tkOp.isOperator() && tk.getLiteralValue() instanceof Class) { optimizedAst.addTokenNode(new DeclTypedVarNode(tkOp.getName(), (Class) tk.getLiteralValue(), 0, ctx)); } else if (tkOp.isAssignment() && tk.getLiteralValue() instanceof Class) { tk.discard(); optimizedAst.addTokenNode(tkOp); } else if (astLinkedList.hasMoreNodes() && tkOp.getLiteralValue() instanceof Class && astLinkedList.peekNode().isAssignment()) { tkOp.discard(); optimizedAst.addTokenNode(tk, astLinkedList.nextNode()); } else { optimizedAst.addTokenNode(tk, tkOp); } } else { optimizedAst.addTokenNode(tk); } } if (secondPassOptimization) { /** * Perform a second pass optimization for boolean conditions. */ (astLinkedList = optimizedAst).reset(); optimizedAst = new ASTLinkedList(); while (astLinkedList.hasMoreNodes()) { if ((tk = astLinkedList.nextNode()).getFields() == -1) { optimizedAst.addTokenNode(tk); } else if (astLinkedList.hasMoreNodes()) { if ((tkOp = astLinkedList.nextNode()).getFields() == -1) { optimizedAst.addTokenNode(tk, tkOp); } else if (tkOp.isOperator() && (tkOp.getOperator() == Operator.AND || tkOp.getOperator() == Operator.OR)) { tkOp2 = null; BooleanNode bool; if (tkOp.getOperator() == Operator.AND) { bool = new And(tk, astLinkedList.nextNode(), ctx.isStrongTyping()); } else { bool = new Or(tk, astLinkedList.nextNode(), ctx.isStrongTyping()); } while (astLinkedList.hasMoreNodes() && (tkOp2 = astLinkedList.nextNode()).isOperator() && (tkOp2.isOperator(Operator.AND) || tkOp2.isOperator(Operator.OR))) { if ((tkOp = tkOp2).getOperator() == Operator.AND) { bool.setRightMost(new And(bool.getRightMost(), astLinkedList.nextNode(), ctx.isStrongTyping())); } else { bool = new Or(bool, astLinkedList.nextNode(), ctx.isStrongTyping()); } } optimizedAst.addTokenNode(bool); if (tkOp2 != null && tkOp2 != tkOp) { optimizedAst.addTokenNode(tkOp2); } } else { optimizedAst.addTokenNode(tk, tkOp); } } else { optimizedAst.addTokenNode(tk); } } } return optimizedAst; } private static boolean isReductionOpportunity(ASTNode oper, ASTNode node) { ASTNode n = node; return (n != null && n.isLiteral() && (n = n.nextASTNode) != null && reducacbleOperator(n.getOperator()) && PTABLE[oper.getOperator()] <= PTABLE[n.getOperator()] && (n = n.nextASTNode) != null && n.isLiteral() && n.getLiteralValue() instanceof Number); } private static boolean reducacbleOperator(int oper) { switch (oper) { case Operator.ADD: case Operator.SUB: return true; } return false; } private static void optimizeOperator(int operator, ASTNode tk, ASTNode tkOp, ASTLinkedList astLinkedList, ASTLinkedList optimizedAst) { switch (operator) { case Operator.REGEX: optimizedAst.addTokenNode(new RegExMatchNode(tk, astLinkedList.nextNode())); break; case Operator.CONTAINS: optimizedAst.addTokenNode(new Contains(tk, astLinkedList.nextNode())); break; case Operator.INSTANCEOF: optimizedAst.addTokenNode(new Instance(tk, astLinkedList.nextNode())); break; case Operator.CONVERTABLE_TO: optimizedAst.addTokenNode((new Convertable(tk, astLinkedList.nextNode()))); break; case Operator.SIMILARITY: optimizedAst.addTokenNode(new Strsim(tk, astLinkedList.nextNode())); break; case Operator.SOUNDEX: optimizedAst.addTokenNode(new Soundslike(tk, astLinkedList.nextNode())); break; default: optimizedAst.addTokenNode(tk, tkOp); } } private static boolean isIntOptimizationviolation(BooleanNode bn, ASTNode bn2) { return (bn instanceof IntOptimized && bn2.getEgressType() != Integer.class); } /** * Returns an ordered Map of all functions declared within an compiled script. * * @param compile * @return - ordered Map */ public static Map extractAllDeclaredFunctions(CompiledExpression compile) { Map allFunctions = new LinkedHashMap(); ASTIterator instructions = new ASTLinkedList(compile.getFirstNode()); ASTNode n; while (instructions.hasMoreNodes()) { if ((n = instructions.nextNode()) instanceof Function) { allFunctions.put(n.getName(), (Function) n); } } return allFunctions; } public static void expectType(Accessor expression, Class type, boolean compileMode) { Class retType = expression.getKnownEgressType(); if (compileMode) { if ((retType == null || !boxPrimitive(type).isAssignableFrom(boxPrimitive(retType))) && (!Object.class.equals(retType) || getCurrentThreadParserContext().isStrictTypeEnforcement())) { throw new CompileException("was expecting type: " + type.getName() + "; but found type: " + (retType != null ? retType.getName() : "null")); } } else if (retType == null || !Object.class.equals(retType) && !boxPrimitive(type).isAssignableFrom(boxPrimitive(retType))) { throw new CompileException("was expecting type: " + type.getName() + "; but found type: " + (retType != null ? retType.getName() : "null")); } } public static void expectType(ASTNode node, Class type, boolean compileMode) { Class retType = boxPrimitive(node.getEgressType()); if (compileMode) { if ((retType == null || !boxPrimitive(type).isAssignableFrom(retType)) && (!Object.class.equals(retType) && (getCurrentThreadParserContext().isStrictTypeEnforcement() || getCurrentThreadParserContext().isStrictTypeEnforcement()))) { throw new CompileException("was expecting type: " + type.getName() + "; but found type: " + (retType != null ? retType.getName() : "null")); } } else if (retType == null || !Object.class.equals(retType) && !boxPrimitive(type).isAssignableFrom(retType)) { throw new CompileException("was expecting type: " + type.getName() + "; but found type: " + (retType != null ? retType.getName() : "null")); } } public static Class getReturnTypeFromOp(int operation, Class left, Class right) { switch (operation) { case Operator.LETHAN: case Operator.LTHAN: case Operator.GETHAN: case Operator.GTHAN: case Operator.EQUAL: case Operator.NEQUAL: case Operator.AND: case Operator.OR: case Operator.CONTAINS: case Operator.CONVERTABLE_TO: return Boolean.class; case Operator.ADD: if (left == String.class) return String.class; case Operator.SUB: case Operator.MULT: case Operator.POWER: case Operator.MOD: case Operator.DIV: if (left == Object.class || right == Object.class) return Object.class; else return __resolveType(boxPrimitive(left)) < __resolveType(boxPrimitive(right)) ? right : left; case Operator.BW_AND: case Operator.BW_OR: case Operator.BW_XOR: case Operator.BW_SHIFT_RIGHT: case Operator.BW_SHIFT_LEFT: case Operator.BW_USHIFT_LEFT: case Operator.BW_USHIFT_RIGHT: case Operator.BW_NOT: return Integer.class; case Operator.STR_APPEND: return String.class; } return null; } public static Accessor extractAccessor(ASTNode n) { if (n instanceof LiteralNode) return new ExecutableLiteral(n.getLiteralValue()); else return new ExecutableAccessor(n, n.getEgressType()); } public static Map getInjectedImports(VariableResolverFactory factory) { if (factory == null) return null; do { if (factory instanceof ClassImportResolverFactory) { return ((ClassImportResolverFactory) factory).getImportedClasses(); } } while ((factory = factory.getNextFactory()) != null); return null; } public static Number signNumber(Object number) { if (number instanceof Integer) { return ((Integer) number) * -1; } else if (number instanceof Double) { return ((Double) number) * -1; } else if (number instanceof Float) { return ((Float) number) * -1; } else if (number instanceof Short) { return ((Short) number) * -1; } else { throw new CompileException("expected a numeric type but found: " + number.getClass().getName()); } } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/ProtoParser.java0000644000175000017500000002355011253516374023764 0ustar drazzibdrazzibpackage org.mvel2.util; import org.mvel2.CompileException; import org.mvel2.ParserContext; import org.mvel2.ast.ASTNode; import org.mvel2.ast.EndOfStatement; import org.mvel2.ast.Proto; import org.mvel2.compiler.ExecutableStatement; import static org.mvel2.util.ParseTools.*; import java.util.*; public class ProtoParser { private char[] expr; private ParserContext pCtx; private int endOffset; private int cursor; private String protoName; String tk1 = null; String tk2 = null; private Class type; private String name; private String deferredName; private boolean interpreted = false; private ExecutionStack splitAccumulator; private static ThreadLocal> deferred = new ThreadLocal>(); public ProtoParser(char[] expr, int offset, int offsetEnd, String protoName, ParserContext pCtx, int fields, ExecutionStack splitAccumulator) { this.expr = expr; this.cursor = offset; this.endOffset = offsetEnd; this.protoName = protoName; this.pCtx = pCtx; this.interpreted = (ASTNode.COMPILE_IMMEDIATE & fields) == 0; this.splitAccumulator = splitAccumulator; } public Proto parse() { Proto proto = new Proto(protoName); Mainloop: while (cursor < endOffset) { cursor = ParseTools.skipWhitespace(expr, cursor, pCtx); int start = cursor; if (tk2 == null) { while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++; if (cursor > start) { tk1 = new String(expr, start, cursor - start); if ("def".equals(tk1) || "function".equals(tk1)) { cursor++; cursor = ParseTools.skipWhitespace(expr, cursor, pCtx); start = cursor; while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++; if (start == cursor) { throw new CompileException("attempt to declare an anonymous function as a prototype member"); } FunctionParser parser = new FunctionParser(new String(expr, start, cursor - start), cursor, endOffset, expr, pCtx, null); proto.declareReceiver(parser.getName(), parser.parse()); cursor = parser.getCursor() + 1; tk1 = null; continue; } } cursor = ParseTools.skipWhitespace(expr, cursor, pCtx); } if (cursor > endOffset) { throw new CompileException("unexpected end of statement in proto declaration: " + protoName); } switch (expr[cursor]) { case ';': cursor++; calculateDecl(); if (interpreted && type == DeferredTypeResolve.class) { /** * If this type could not be immediately resolved, it may be a look-ahead case, so * we defer resolution of the type until later and place it in the wait queue. */ enqueueReceiverForLateResolution(deferredName, proto.declareReceiver(name, Proto.ReceiverType.DEFERRED, null), null); } else { proto.declareReceiver(name, type, null); } break; case '=': cursor++; cursor = ParseTools.skipWhitespace(expr, cursor, pCtx); start = cursor; Loop: while (cursor < endOffset) { switch (expr[cursor]) { case '{': case '[': case '(': case '\'': case '"': cursor = balancedCaptureWithLineAccounting(expr, cursor, expr[cursor], pCtx); break; case ';': break Loop; } cursor++; } calculateDecl(); String initString = new String(expr, start, cursor++ - start); if (interpreted && type == DeferredTypeResolve.class) { enqueueReceiverForLateResolution(deferredName, proto.declareReceiver(name, Proto.ReceiverType.DEFERRED, null), initString); } else { proto.declareReceiver(name, type, (ExecutableStatement) subCompileExpression(initString, pCtx)); } break; default: start = cursor; while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++; if (cursor > start) { tk2 = new String(expr, start, cursor - start); } } } cursor++; /** * Check if the function is manually terminated. */ if (splitAccumulator != null && ParseTools.isStatementNotManuallyTerminated(expr, cursor)) { /** * Add an EndOfStatement to the split accumulator in the parser. */ splitAccumulator.add(new EndOfStatement()); } return proto; } private void calculateDecl() { if (tk2 != null) { try { if (pCtx.hasProtoImport(tk1)) { type = Proto.class; } else { type = ParseTools.findClass(null, tk1, pCtx); } name = tk2; } catch (ClassNotFoundException e) { if (interpreted) { type = DeferredTypeResolve.class; deferredName = tk1; name = tk2; } else { throw new CompileException("could not resolve class: " + tk1, e); } } } else { type = Object.class; name = tk1; } tk1 = null; tk2 = null; } private interface DeferredTypeResolve { public boolean isWaitingFor(Proto proto); public String getName(); } private void enqueueReceiverForLateResolution(final String name, final Proto.Receiver receiver, final String initializer) { Queue recv = deferred.get(); if (recv == null) { deferred.set(recv = new LinkedList()); } recv.add(new DeferredTypeResolve() { public boolean isWaitingFor(Proto proto) { if (name.equals(proto.getName())) { receiver.setType(Proto.ReceiverType.PROPERTY); receiver.setInitValue((ExecutableStatement) subCompileExpression(initializer, pCtx)); return true; } return false; } public String getName() { return name; } }); } public static void notifyForLateResolution(final Proto proto) { if (deferred.get() != null) { Queue recv = deferred.get(); Set remove = new HashSet(); for (DeferredTypeResolve r : recv) { if (r.isWaitingFor(proto)) { remove.add(r); } } for (DeferredTypeResolve r : remove) { recv.remove(r); } } } public int getCursor() { return cursor; } /** * This is such a horrible hack, but it's more performant than any other horrible hack I can think of * right now. * * @param expr * @param cursor * @param pCtx */ public static void checkForPossibleUnresolvedViolations(char[] expr, int cursor, ParserContext pCtx) { if (isUnresolvedWaiting()) { LinkedHashMap imports = (LinkedHashMap) pCtx.getParserConfiguration().getImports(); Object o = imports.values().toArray()[imports.size() - 1]; if (o instanceof Proto) { Proto proto = (Proto) o; int last = proto.getCursorEnd(); cursor--; /** * We walk backwards to ensure that the last valid statement was a proto declaration. */ while (cursor > last && ParseTools.isWhitespace(expr[cursor])) cursor--; while (cursor > last && ParseTools.isIdentifierPart(expr[cursor])) cursor--; while (cursor > last && (ParseTools.isWhitespace(expr[cursor]) || expr[cursor] == ';')) cursor--; if (cursor != last) { throw new CompileException("unresolved reference (possible illegal forward-reference?): " + ProtoParser.getNextUnresolvedWaiting(), expr, proto.getCursorStart()); } } } } public static boolean isUnresolvedWaiting() { return deferred.get() != null && !deferred.get().isEmpty(); } public static String getNextUnresolvedWaiting() { if (deferred.get() != null && !deferred.get().isEmpty()) { return deferred.get().poll().getName(); } return null; } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/Make.java0000644000175000017500000000747211345736415022370 0ustar drazzibdrazzibpackage org.mvel2.util; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class Make { public static class Map { public static Map $() { return start(); } public static Map start() { return new Map(new HashMap()); } public static Map start(Class mapImpl) { try { return new Map(mapImpl.newInstance()); } catch (Throwable t) { throw new RuntimeException("error creating instance", t); } } private java.util.Map mapInstance; private Map(java.util.Map mapInstance) { this.mapInstance = mapInstance; } public Map _(K key, V value) { mapInstance.put(key, value); return this; } public java.util.Map _() { return finish(); } public java.util.Map finish() { return mapInstance; } } public static class String { public static String $() { return start(); } public static String start() { return new String(new StringAppender()); } public java.lang.String _() { return finish(); } public java.lang.String finish() { return stringAppender.toString(); } private StringAppender stringAppender; String(StringAppender stringAppender) { this.stringAppender = stringAppender; } public String _(char c) { stringAppender.append(c); return this; } public String _(CharSequence cs) { stringAppender.append(cs); return this; } public String _(String s) { stringAppender.append(s); return this; } } public static class List { public static List $() { return start(); } public static List start() { return new List(new ArrayList()); } public static List start(Class listImpl) { try { return new List(listImpl.newInstance()); } catch (Throwable t) { throw new RuntimeException("error creating instance", t); } } private java.util.List listInstance; List(java.util.List listInstance) { this.listInstance = listInstance; } public List _(V value) { listInstance.add(value); return this; } public java.util.List _() { return finish(); } public java.util.List finish() { return listInstance; } } public static class Set { public static Set $() { return start(); } public static Set start() { return new Set(new HashSet()); } public static Set start(Class listImpl) { try { return new Set(listImpl.newInstance()); } catch (Throwable t) { throw new RuntimeException("error creating instance", t); } } private java.util.Set listInstance; Set(java.util.Set listInstance) { this.listInstance = listInstance; } public Set _(V value) { listInstance.add(value); return this; } public java.util.Set _() { return finish(); } public java.util.Set finish() { return listInstance; } } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/CallableProxy.java0000644000175000017500000000042211253250512024223 0ustar drazzibdrazzibpackage org.mvel2.util; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.InvocationTargetException; public interface CallableProxy { public Object call(Object ctx, Object thisCtx, VariableResolverFactory factory, Object[] parameters); } mvel-2.0.18.orig/src/main/java/org/mvel2/util/ThisLiteral.java0000644000175000017500000000132711077460760023727 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; public class ThisLiteral { } mvel-2.0.18.orig/src/main/java/org/mvel2/util/ExecutionStack.java0000644000175000017500000001167511222666001024427 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.CompileException; import org.mvel2.math.MathProcessor; import static org.mvel2.math.MathProcessor.doOperations; import static java.lang.String.valueOf; public class ExecutionStack { private StackElement element; private int size = 0; public boolean isEmpty() { return size == 0; } public void add(Object o) { size++; StackElement el = element; if (el != null) { while (el.next != null) { el = el.next; } el.next = new StackElement(null, o); } else { element = new StackElement(null, o); } } public void push(Object o) { size++; element = new StackElement(element, o); } public Object pushAndPeek(Object o) { size++; element = new StackElement(element, o); return o; } public void push(Object obj1, Object obj2) { size += 2; element = new StackElement(new StackElement(element, obj1), obj2); } public void push(Object obj1, Object obj2, Object obj3) { size += 3; element = new StackElement(new StackElement(new StackElement(element, obj1), obj2), obj3); } public Object peek() { if (size == 0) return null; else return element.value; } public Boolean peekBoolean() { if (size == 0) return null; if (element.value instanceof Boolean) return (Boolean) element.value; throw new CompileException("expected Boolean; but found: " + (element.value == null ? "null" : element.value.getClass().getName())); } public void copy2(ExecutionStack es) { element = new StackElement(new StackElement(element, es.element.value), es.element.next.value); es.element = es.element.next.next; size += 2; es.size -= 2; } public void copyx2(ExecutionStack es) { element = new StackElement(new StackElement(element, es.element.next.value), es.element.value); es.element = es.element.next.next; size += 2; es.size -= 2; } public Object peek2() { return element.next.value; } public Object pop() { if (size-- == 0) { return null; } try { return element.value; } finally { element = element.next; } } public Boolean popBoolean() { if (size-- == 0) { return null; } try { if (element.value instanceof Boolean) return (Boolean) element.value; throw new CompileException("expected Boolean; but found: " + (element.value == null ? "null" : element.value.getClass().getName())); } finally { element = element.next; } } public Object pop2() { try { size -= 2; return element.value; } finally { element = element.next.next; } } public void discard() { if (size != 0) { size--; element = element.next; } } public int size() { return size; } public boolean isReduceable() { return size > 1; } public void clear() { size = 0; element = null; } public void xswap_op() { xswap(); op(); } public void op() { element = new StackElement(element.next.next.next, doOperations(element.next.next.value, (Integer) element.value, element.next.value)); size -= 2; } public void op(int operator) { element = new StackElement(element.next.next, doOperations(element.next.value, operator, element.value)); size--; } public void xswap() { StackElement e = element.next; StackElement relink = e.next; e.next = element; (element = e).next.next = relink; } public String toString() { StackElement el = element; if (element == null) return ""; StringAppender appender = new StringAppender().append("["); do { appender.append(valueOf(el.value)); if (el.next != null) appender.append(", "); } while ((el = el.next) != null); appender.append("]"); return appender.toString(); } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/CollectionParser.java0000644000175000017500000001743611222477143024756 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import org.mvel2.CompileException; import org.mvel2.DataConversion; import org.mvel2.ParserContext; import org.mvel2.compiler.ExecutableStatement; import static org.mvel2.util.ParseTools.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This is the inline collection sub-parser. It produces a skeleton model of the collection which is in turn translated * into a sequenced AST to produce the collection efficiently at runtime, and passed off to one of the JIT's if * configured. * * @author Christopher Brock */ public class CollectionParser { private char[] property; private int cursor; private int length; private int start; private int type; public static final int LIST = 0; public static final int ARRAY = 1; public static final int MAP = 2; private Class colType; // private boolean strongType; private ParserContext pCtx; private static final Object[] EMPTY_ARRAY = new Object[0]; public CollectionParser() { } public CollectionParser(int type) { this.type = type; } public Object parseCollection(char[] property, boolean subcompile, ParserContext pCtx) { this.cursor = 0; this.pCtx = pCtx; if ((this.length = (this.property = property).length) > 0) while (length > 0 && isWhitespace(property[length - 1])) length--; return parseCollection(subcompile); } public Object parseCollection(char[] property, boolean subcompile, Class colType, ParserContext pCtx) { if (colType != null) this.colType = getBaseComponentType(colType); this.cursor = 0; this.pCtx = pCtx; if ((this.length = (this.property = property).length) > 0) while (length > 0 && isWhitespace(property[length - 1])) length--; return parseCollection(subcompile); } private Object parseCollection(boolean subcompile) { if (length == 0) { if (type == LIST) return new ArrayList(); else return EMPTY_ARRAY; } Map map = null; List list = null; String ex; if (type != -1) { switch (type) { case ARRAY: case LIST: list = new ArrayList(); break; case MAP: map = new HashMap(); break; } } Object curr = null; int newType = -1; for (; cursor < length; cursor++) { switch (property[cursor]) { case '{': if (newType == -1) { newType = ARRAY; } case '[': if (cursor > 0 && isIdentifierPart(property[cursor - 1])) continue; if (newType == -1) { newType = LIST; } /** * Sub-parse nested collections. */ Object o = new CollectionParser(newType).parseCollection(subset(property, (start = cursor) + 1, cursor = balancedCapture(property, start, property[start])), subcompile, colType, pCtx); if (type == MAP) { map.put(curr, o); } else { list.add(curr = o); } if ((start = ++cursor) < (length - 1) && property[cursor] == ',') { start = cursor + 1; } continue; case '(': cursor = balancedCapture(property, cursor, '('); break; case '\"': case '\'': cursor = balancedCapture(property, cursor, property[cursor]); break; case ',': if (type != MAP) { list.add(ex = new String(property, start, cursor - start)); } else { map.put(curr, ex = createStringTrimmed(property, start, cursor - start)); } if (subcompile) { subCompile(ex); } start = cursor + 1; break; case ':': if (type != MAP) { map = new HashMap(); type = MAP; } curr = createStringTrimmed(property, start, cursor - start); if (subcompile) { subCompile((String) curr); } start = cursor + 1; break; case '.': cursor++; while (cursor != length && isWhitespace(property[cursor])) cursor++; if (cursor != length && property[cursor] == '{') { cursor = balancedCapture(property, cursor, '{'); } break; } } if (start < length) { if (cursor < (length - 1)) cursor++; if (type == MAP) { map.put(curr, ex = createStringTrimmed(property, start, cursor - start)); } else { if (cursor < length) cursor++; list.add(ex = createStringTrimmed(property, start, cursor - start)); } if (subcompile) subCompile(ex); } switch (type) { case MAP: return map; case ARRAY: return list.toArray(); default: return list; } } private void subCompile(String ex) { if (colType == null) { subCompileExpression(ex.toCharArray(), pCtx); } else { Class r = ((ExecutableStatement) subCompileExpression(ex.toCharArray(), pCtx)).getKnownEgressType(); if (!colType.isAssignableFrom(r) && (isStrongType() || !DataConversion.canConvert(r, colType))) { throw new CompileException("expected type: " + colType.getName() + "; but found: " + r.getName()); } } } private boolean isStrongType() { return pCtx != null && pCtx.isStrongTyping(); } private static char[] subset(char[] property, int start, int end) { while (start < (end - 1) && isWhitespace(property[start])) start++; char[] newA = new char[end - start]; int i = 0; while (i != newA.length) { newA[i] = property[i + start]; i++; } return newA; } public int getCursor() { return cursor; } } mvel-2.0.18.orig/src/main/java/org/mvel2/util/Stack.java0000644000175000017500000000233611077460760022551 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import java.io.Serializable; public interface Stack extends Serializable { public boolean isEmpty(); public Object peek(); public Object peek2(); public void add(Object obj); public void push(Object obj); public Object pushAndPeek(Object obj); public void push(Object obj1, Object obj2); public void push(Object obj1, Object obj2, Object obj3); public Object pop(); public Object pop2(); public void discard(); public void clear(); public int size(); public void showStack(); } mvel-2.0.18.orig/src/main/java/org/mvel2/util/StringAppender.java0000644000175000017500000001411611164527565024434 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2.util; import static java.lang.System.arraycopy; import java.io.UnsupportedEncodingException; import java.io.PrintWriter; import java.io.Writer; public class StringAppender implements CharSequence { private static final int DEFAULT_SIZE = 15; private char[] str; private int capacity; private int size = 0; private byte[] btr; private String encoding; public StringAppender() { str = new char[capacity = DEFAULT_SIZE]; } public StringAppender(int capacity) { str = new char[this.capacity = capacity]; } public StringAppender(int capacity, String encoding) { str = new char[this.capacity = capacity]; this.encoding = encoding; } public StringAppender(char c) { (str = new char[this.capacity = DEFAULT_SIZE])[0] = c; } public StringAppender(char[] s) { capacity = size = (str = s).length; } public StringAppender(CharSequence s) { str = new char[this.capacity = size = s.length()]; for (int i = 0; i < str.length; i++) str[i] = s.charAt(i); } public StringAppender(String s) { capacity = size = (str = s.toCharArray()).length; } public StringAppender append(char[] chars) { if (chars.length > (capacity - size)) grow(chars.length); for (int i = 0; i < chars.length; size++) { str[size] = chars[i++]; } return this; } public StringAppender append(byte[] chars) { if (chars.length > (capacity - size)) grow(chars.length); for (int i = 0; i < chars.length; size++) { str[size] = (char) chars[i++]; } return this; } public StringAppender append(char[] chars, int start, int length) { if (length > (capacity - size)) grow(length); int x = start + length; for (int i = start; i < x; i++) { str[size++] = chars[i]; } return this; } public StringAppender append(byte[] chars, int start, int length) { if (length > (capacity - size)) grow(length); int x = start + length; for (int i = start; i < x; i++) { str[size++] = (char) chars[i]; } return this; } public StringAppender append(Object o) { return append(String.valueOf(o)); } public StringAppender append(CharSequence s) { if (s.length() > (capacity - size)) grow(s.length()); for (int i = 0; i < s.length(); size++) { str[size] = s.charAt(i++); } return this; } public StringAppender append(String s) { if (s == null) return this; int len = s.length(); if (len > (capacity - size)) { grow(len); } s.getChars(0, len, str, size); size += len; return this; } public StringAppender append(char c) { if (size >= capacity) grow(1); str[size++] = c; return this; } public StringAppender append(byte b) { if (btr == null) btr = new byte[capacity = DEFAULT_SIZE]; if (size >= capacity) growByte(1); btr[size++] = b; return this; } public int length() { return size; } private void grow(int s) { if (capacity == 0) capacity = DEFAULT_SIZE; final char[] newArray = new char[capacity += s * 2]; arraycopy(str, 0, newArray, 0, size); str = newArray; } private void growByte(int s) { final byte[] newByteArray = new byte[capacity += s]; arraycopy(btr, 0, newByteArray, 0, size); btr = newByteArray; } public char[] getChars(int start, int count) { char[] chars = new char[count]; arraycopy(str, start, chars, 0, count); return chars; } public char[] toChars() { if (btr != null) { if (encoding == null) encoding = System.getProperty("file.encoding"); String s; try { s = new String(btr, encoding); } catch (UnsupportedEncodingException e) { s = new String(btr); } return s.toCharArray(); } char[] chars = new char[size]; arraycopy(str, 0, chars, 0, size); return chars; } public String toString() { if (btr != null) { if (encoding == null) encoding = System.getProperty("file.encoding"); String s; try { s = new String(btr, encoding); } catch (UnsupportedEncodingException e) { s = new String(btr); } return s; } if (size == capacity) return new String(str); else return new String(str, 0, size); } public void getChars(int start, int count, char[] target, int offset) { int delta = offset; for (int i = start; i < count; i++) { target[delta++] = str[i]; } } public void reset() { size = 0; } public char charAt(int index) { return str[index]; } public CharSequence subSequence(int start, int end) { return new String(str, start, (end - start)); } } mvel-2.0.18.orig/src/main/java/org/mvel2/OptimizationFailure.java0000644000175000017500000000213111077457613024521 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; public class OptimizationFailure extends RuntimeException { public OptimizationFailure() { super(); } public OptimizationFailure(String message) { super(message); } public OptimizationFailure(String message, Throwable cause) { super(message, cause); } public OptimizationFailure(Throwable cause) { super(cause); } } mvel-2.0.18.orig/src/main/java/org/mvel2/ParserContext.java0000644000175000017500000005727711331603414023332 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; import org.mvel2.ast.Function; import org.mvel2.ast.LineLabel; import org.mvel2.ast.Proto; import org.mvel2.integration.Interceptor; import org.mvel2.util.MethodStub; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.*; /** * The ParserContext is the main enviroment object used for sharing state throughout the entire * parser/compile process.

* The ParserContext is used to configure the parser/compiler. For example: *

 * ParserContext parserContext = new ParserContext();
 * parserContext.setStrongTyping(true); // turn on strong typing.
 * 

* Serializable comp = MVEL.compileExpression("foo.bar", parserContext); * */ public class ParserContext implements Serializable { private String sourceFile; private int lineCount = 1; private int lineOffset; private ParserConfiguration parserConfiguration = new ParserConfiguration(); private ArrayList indexedVariables; private HashMap variables; private Map inputs; private transient HashMap> typeParameters; private transient Type[] lastTypeParameters; private HashMap globalFunctions; private transient List errorList; private HashMap> sourceMap; private LineLabel lastLineLabel; private transient Object rootParser; private boolean compiled = false; private boolean strictTypeEnforcement = false; private boolean strongTyping = false; private boolean fatalError = false; private boolean retainParserState = false; private boolean debugSymbols = false; private boolean blockSymbols = false; private boolean executableCodeReached = false; private boolean indexAllocation = false; private boolean allowBootstrapBypass = true; public ParserContext() { } public ParserContext(boolean debugSymbols) { this.debugSymbols = debugSymbols; } public ParserContext(Object rootParser) { this.rootParser = rootParser; } public ParserContext(ParserConfiguration parserConfiguration) { this.parserConfiguration = parserConfiguration; } public ParserContext(Map imports, Map interceptors, String sourceFile) { this.sourceFile = sourceFile; this.parserConfiguration = new ParserConfiguration(imports, interceptors); } public ParserContext createSubcontext() { ParserContext ctx = new ParserContext(parserConfiguration); ctx.sourceFile = sourceFile; ctx.addInputs(inputs); ctx.addVariables(variables); ctx.addIndexedVariables(indexedVariables); ctx.addTypeParameters(typeParameters); ctx.sourceMap = sourceMap; ctx.lastLineLabel = lastLineLabel; ctx.globalFunctions = globalFunctions; ctx.lastTypeParameters = lastTypeParameters; ctx.errorList = errorList; ctx.rootParser = rootParser; ctx.lineCount = lineCount; ctx.lineOffset = lineOffset; ctx.compiled = compiled; ctx.strictTypeEnforcement = strictTypeEnforcement; ctx.strongTyping = strongTyping; ctx.fatalError = fatalError; ctx.retainParserState = retainParserState; ctx.debugSymbols = debugSymbols; ctx.blockSymbols = blockSymbols; ctx.executableCodeReached = executableCodeReached; ctx.indexAllocation = indexAllocation; return ctx; } /** * Tests whether or not a variable or input exists in the current parser context. * * @param name The name of the identifier. * @return boolean */ public boolean hasVarOrInput(String name) { return (variables != null && variables.containsKey(name)) || (inputs != null && inputs.containsKey(name)); } /** * Return the variable or input type froom the current parser context. Returns Object.class if the * type cannot be determined. * * @param name The name of the identifier * @return boolean */ public Class getVarOrInputType(String name) { if (variables != null && variables.containsKey(name)) { return variables.get(name); } else if (inputs != null && inputs.containsKey(name)) { return inputs.get(name); } return Object.class; } public Class getVarOrInputTypeOrNull(String name) { if (variables != null && variables.containsKey(name)) { return variables.get(name); } else if (inputs != null && inputs.containsKey(name)) { return inputs.get(name); } return null; } /** * Get total number of lines declared in the current context. * * @return int of lines */ public int getLineCount() { return lineCount; } /** * Set the current number of lines in the current context. (Generally only used by the compiler) * * @param lineCount The number of lines * @return int of lines */ public int setLineCount(int lineCount) { return this.lineCount = lineCount; } /** * Increments the current line count by the specified amount * * @param increment The number of lines to increment * @return int of lines */ public int incrementLineCount(int increment) { return this.lineCount += increment; } /** * Get the current line offset. This measures the number of cursor positions back to the beginning of the line. * * @return int offset */ public int getLineOffset() { return lineOffset; } /** * Sets the current line offset. (Generally only used by the compiler) * * @param lineOffset The offset amount */ public void setLineOffset(short lineOffset) { this.lineOffset = lineOffset; } /** * Sets both the current line count and line offset * * @param lineCount The line count * @param lineOffset The line offset */ public void setLineAndOffset(int lineCount, int lineOffset) { addKnownLine(this.lineCount = lineCount); this.lineOffset = lineOffset; } /** * Get an import that has been declared, either in the parsed script or programatically * * @param name The name identifier for the imported class (ie. "HashMap") * @return An instance of Class denoting the imported class. */ public Class getImport(String name) { return parserConfiguration.getImport(name); } /** * Get a {@link MethodStub} which wraps a static method import. * * @param name The name identifier * @return An instance of {@link MethodStub} */ public MethodStub getStaticImport(String name) { return parserConfiguration.getStaticImport(name); } /** * Returns either an instance of Class or {@link MethodStub} (whichever matches). * * @param name The name identifier. * @return An instance of Class or {@link MethodStub} */ public Object getStaticOrClassImport(String name) { return parserConfiguration.getStaticOrClassImport(name); } /** * Adds a package import to a parse session. * * @param packageName A fully qualified package (eg. java.util.concurrent). */ public void addPackageImport(String packageName) { parserConfiguration.addPackageImport(packageName); } /** * Tests to see if the specified import exists. * * @param name A name identifier * @return boolean */ public boolean hasImport(String name) { return parserConfiguration.hasImport(name); } public boolean hasProtoImport(String name) { if (parserConfiguration.getImports() == null) return false; Object o = parserConfiguration.getImports().get(name); return o != null && o instanceof Proto; } public Proto getProtoImport(String name) { return (Proto) parserConfiguration.getImports().get(name); } /** * Adds an import for the specified Class. * * @param cls The instance of the Class which represents the imported class. */ public void addImport(Class cls) { addImport(cls.getSimpleName(), cls); } public void addImport(Proto proto) { parserConfiguration.addImport(proto.getName(), proto); } /** * Adds an import for a specified Class using an alias. For example: *


     * parserContext.addImport("sys", System.class);
     * 
* ... doing this would allow an MVEL script to be written as such: *

     * sys.currentTimeMillis();
     * 
* * @param name The alias to use * @param cls The instance of the Class which represents the imported class. */ public void addImport(String name, Class cls) { parserConfiguration.addImport(name, cls); } /** * Adds an import for a specified Method representing a static method import using an alias. For example: *

     * parserContext.addImport("time", MVEL.getStaticMethod(System.class, "currentTimeMillis", new Class[0]));
     * 
* ... doing this allows the System.currentTimeMillis() method to be executed in a script simply by writing * time(). * * @param name The alias to use * @param method The instance of Method which represents the static import. */ public void addImport(String name, Method method) { addImport(name, new MethodStub(method)); } /** * Adds a static import for the specified {@link MethodStub} with an alias. * * @param name The alias to use * @param method The instance of Method which represents the static import. * @see #addImport(String, org.mvel2.util.MethodStub) */ public void addImport(String name, MethodStub method) { parserConfiguration.addImport(name, method); } /** * Initializes internal Maps. Called by the compiler. */ public void initializeTables() { if (variables == null) variables = new LinkedHashMap(); if (inputs == null) inputs = new LinkedHashMap(); } public void addVariable(String name, Class type, boolean failIfNewAssignment) { initializeTables(); if (variables.containsKey(name) && failIfNewAssignment) throw new CompileException("statically-typed variable already defined in scope: " + name); if (type == null) type = Object.class; variables.put(name, type); } public void addVariable(String name, Class type) { initializeTables(); if (variables.containsKey(name)) return; if (type == null) type = Object.class; variables.put(name, type); } public void addVariables(Map variables) { if (variables == null) return; initializeTables(); for (Map.Entry entry : variables.entrySet()) { addVariable(entry.getKey(), entry.getValue()); } } public void addInput(String name, Class type) { if (inputs == null) inputs = new LinkedHashMap(); if (inputs.containsKey(name) || (variables != null && variables.containsKey(name))) return; if (type == null) type = Object.class; inputs.put(name, type); } public void addInput(String name, Class type, Class[] typeParameters) { if (type == null) type = Object.class; addInput(name, type); if (this.typeParameters == null) { this.typeParameters = new LinkedHashMap>(); } if (this.typeParameters.get(name) == null) { this.typeParameters.put(name, new LinkedHashMap()); } Map t = this.typeParameters.get(name); if (typeParameters.length != type.getTypeParameters().length) { throw new RuntimeException("wrong number of type parameters for: " + type.getName()); } TypeVariable[] tvs = type.getTypeParameters(); for (int i = 0; i < typeParameters.length; i++) { t.put(tvs[i].getName(), typeParameters[i]); } } public void addInputs(Map inputs) { if (inputs == null) return; for (Map.Entry entry : inputs.entrySet()) { addInput(entry.getKey(), entry.getValue()); } } public void processTables() { for (String name : variables.keySet()) { inputs.remove(name); } } public Map getInputs() { return inputs; } public void setInputs(Map inputs) { this.inputs = inputs; } public List getErrorList() { return errorList; } public void setErrorList(List errorList) { this.errorList = errorList; } public void addError(ErrorDetail errorDetail) { if (errorList == null) errorList = new ArrayList(); if (errorDetail.isCritical()) fatalError = true; errorList.add(errorDetail); } public boolean isFatalError() { return fatalError; } public void setFatalError(boolean fatalError) { this.fatalError = fatalError; } public boolean isStrictTypeEnforcement() { return strictTypeEnforcement; } /** * Enables strict type enforcement - * * @param strictTypeEnforcement - */ public void setStrictTypeEnforcement(boolean strictTypeEnforcement) { this.strictTypeEnforcement = strictTypeEnforcement; } public boolean isStrongTyping() { return strongTyping; } /** * Enables strong type enforcement. * * @param strongTyping */ public void setStrongTyping(boolean strongTyping) { if (this.strongTyping = strongTyping) { // implies strict-type enforcement too this.strictTypeEnforcement = true; } } public boolean isRetainParserState() { return retainParserState; } public void setRetainParserState(boolean retainParserState) { this.retainParserState = retainParserState; } public Object getRootParser() { return rootParser; } public void setRootParser(Object rootParser) { this.rootParser = rootParser; } public String getSourceFile() { return sourceFile; } public void setSourceFile(String sourceFile) { if (sourceFile != null) this.sourceFile = sourceFile; } public Map getInterceptors() { return this.parserConfiguration.getInterceptors(); } public void setInterceptors(Map interceptors) { this.parserConfiguration.setInterceptors(interceptors); } public Map getImports() { return this.parserConfiguration.getImports(); } public void setImports(Map imports) { if (imports == null) return; Object val; for (Map.Entry entry : imports.entrySet()) { if ((val = entry.getValue()) instanceof Class) { addImport(entry.getKey(), (Class) val); } else if (val instanceof Method) { addImport(entry.getKey(), (Method) val); } else if (val instanceof MethodStub) { addImport(entry.getKey(), (MethodStub) val); } else { throw new RuntimeException("invalid element in imports map: " + entry.getKey() + " (" + val + ")"); } } } public HashMap getVariables() { return variables; } public void setVariables(HashMap variables) { this.variables = variables; } public boolean isCompiled() { return compiled; } public void setCompiled(boolean compiled) { this.compiled = compiled; } public boolean isDebugSymbols() { return debugSymbols; } public void setDebugSymbols(boolean debugSymbols) { this.debugSymbols = debugSymbols; } public boolean isKnownLine(String sourceName, int lineNumber) { return sourceMap != null && sourceMap.containsKey(sourceName) && sourceMap.get(sourceName).contains(lineNumber); } public void addKnownLine(String sourceName, int lineNumber) { if (sourceMap == null) sourceMap = new HashMap>(); if (!sourceMap.containsKey(sourceName)) sourceMap.put(sourceName, new HashSet()); sourceMap.get(sourceName).add(lineNumber); } public void addKnownLine(int lineNumber) { addKnownLine(sourceFile, lineNumber); } public LineLabel getLastLineLabel() { return lastLineLabel; } public LineLabel setLastLineLabel(LineLabel lastLineLabel) { return this.lastLineLabel = lastLineLabel; } public boolean hasImports() { return parserConfiguration.hasImports(); } public void declareFunction(Function function) { if (globalFunctions == null) globalFunctions = new LinkedHashMap(); globalFunctions.put(function.getName(), function); } public Function getFunction(String name) { if (globalFunctions == null) return null; return globalFunctions.get(name); } public Map getFunctions() { return globalFunctions; } public boolean hasFunction(String name) { return globalFunctions != null && globalFunctions.containsKey(name); } public boolean hasFunction() { return globalFunctions != null && globalFunctions.size() != 0; } public void addTypeParameters(String name, Class type) { if (typeParameters == null) typeParameters = new HashMap>(); Map newPkg = new HashMap(); for (Type t : type.getTypeParameters()) { newPkg.put(t.toString(), Object.class); } typeParameters.put(name, newPkg); } public void addTypeParameters(Map> typeParameters) { if (typeParameters == null) return; if (this.typeParameters == null) typeParameters = new HashMap>(); Map iMap; for (Map.Entry> e : typeParameters.entrySet()) { iMap = new HashMap(); for (Map.Entry ie : e.getValue().entrySet()) { iMap.put(ie.getKey(), ie.getValue()); } typeParameters.put(e.getKey(), iMap); } } public Map getTypeParameters(String name) { if (typeParameters == null) return null; return typeParameters.get(name); } public Type[] getTypeParametersAsArray(String name) { Class c = (variables != null && variables.containsKey(name)) ? variables.get(name) : inputs.get(name); if (c == null) return null; Type[] tp = c.getTypeParameters(); Type[] types = new Type[tp.length]; Map typeVars = getTypeParameters(name); if (typeVars == null) { return null; } for (int i = 0; i < tp.length; i++) { types[i] = typeVars.get(tp[i].toString()); } return types; } public boolean isBlockSymbols() { return blockSymbols; } public void setBlockSymbols(boolean blockSymbols) { this.blockSymbols = blockSymbols; } public boolean isExecutableCodeReached() { return executableCodeReached; } public void setExecutableCodeReached(boolean executableCodeReached) { this.executableCodeReached = executableCodeReached; } private void initIndexedVariables() { if (indexedVariables == null) indexedVariables = new ArrayList(); } public ArrayList getIndexedVariables() { initIndexedVariables(); return indexedVariables; } public void addIndexedVariables(String[] variables) { initIndexedVariables(); for (String s : variables) { if (!indexedVariables.contains(s)) indexedVariables.add(s); } } public void addIndexedVariable(String variable) { initIndexedVariables(); if (!indexedVariables.contains(variable)) indexedVariables.add(variable); } public void addIndexedVariables(Collection variables) { if (variables == null) return; initIndexedVariables(); for (String s : variables) { if (!indexedVariables.contains(s)) indexedVariables.add(s); } } public int variableIndexOf(String name) { return indexedVariables != null ? indexedVariables.indexOf(name) : -1; } public boolean hasIndexedVariables() { return indexedVariables != null && indexedVariables.size() != 0; } public boolean isIndexAllocation() { return indexAllocation; } public void setIndexAllocation(boolean indexAllocation) { this.indexAllocation = indexAllocation; } public ParserConfiguration getParserConfiguration() { return parserConfiguration; } public Type[] getLastTypeParameters() { return lastTypeParameters; } public void setLastTypeParameters(Type[] lastTypeParameters) { this.lastTypeParameters = lastTypeParameters; } public boolean isAllowBootstrapBypass() { return allowBootstrapBypass; } public void setAllowBootstrapBypass(boolean allowBootstrapBypass) { this.allowBootstrapBypass = allowBootstrapBypass; } public String[] getIndexedVarNames() { String[] s = new String[indexedVariables.size()]; indexedVariables.toArray(s); return s; } // Introduce some new Fluent API stuff here. public static ParserContext create() { return new ParserContext(); } public ParserContext stronglyTyped() { setStrongTyping(true); return this; } public ParserContext withInput(String name, Class type) { addInput(name, type); return this; } public ParserContext withInputs(Map inputs) { setInputs(inputs); return this; } public ParserContext withTypeParameter(String name, Class type) { addTypeParameters(name, type); return this; } public ParserContext withTypeParameters(Map> typeParameters) { addTypeParameters(typeParameters); return this; } public ParserContext withImport(Class clazz) { addImport(clazz); return this; } public ParserContext withIndexedVars(String[] varNames) { indexedVariables = new ArrayList(); for (String s : varNames) { indexedVariables.add(s); } return this; } } mvel-2.0.18.orig/src/main/java/org/mvel2/ParseException.java0000644000175000017500000000350411077457613023461 0ustar drazzibdrazzib/** * MVEL 2.0 * Copyright (C) 2007 The Codehaus * Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mvel2; public class ParseException extends RuntimeException { private int cursorPosition; private String message; public ParseException() { super(); } public ParseException(String message) { this.message = message; } public ParseException(String message, char[] expr, int cursorPosition) { super(); this.cursorPosition = cursorPosition; int start = cursorPosition - 15; int end = cursorPosition + 15; if (start < 0) { end += (0 - start); start = 0; } if (end > expr.length) { end = expr.length; } String nearCode = new String(expr, start, end - start); this.message = message + " (near code: << ... " + nearCode + " ...>>) (position: " + cursorPosition + ")"; } public ParseException(String message, Throwable cause) { super(cause); this.message = message; } public ParseException(Throwable cause) { super(cause); } public String getMessage() { return message; } public int getCursorPosition() { return cursorPosition; } } mvel-2.0.18.orig/src/test/0000755000175000017500000000000011412747040015146 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/resources/0000755000175000017500000000000011412747040017160 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/0000755000175000017500000000000011412747035016073 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/0000755000175000017500000000000011412747035016662 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/0000755000175000017500000000000011412747040017703 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/compiler/0000755000175000017500000000000011412747040021515 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/compiler/GenericsTypeInferenceTest.java0000644000175000017500000001214511162250032027433 0ustar drazzibdrazzibpackage org.mvel2.compiler; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.mvel2.MVEL; import org.mvel2.ParserContext; /** * Asserts that the element at the end of the parse chain has its type parameter correctly inferred * IF the egress type is a parametric type (i.e. generic). * * @author Dhanji R. Prasanna (dhanji@gmail com) */ public class GenericsTypeInferenceTest extends TestCase { private static final List STRINGS = Arrays.asList("hi", "there", "dude"); public final void testInferLastTypeParametersFromProperty() { ParserContext context = new ParserContext(); context.setStrongTyping(true); context.addInput("a", A.class); final CompiledExpression compiledExpression = new ExpressionCompiler("a.strings") .compile(context); final Object val = MVEL.executeExpression(compiledExpression, new AWrapper()); assertTrue("Expression did not evaluate correctly: " + val, STRINGS.equals(val)); assertTrue("No type parameters detected", null != context.getLastTypeParameters()); assertTrue("Wrong parametric type inferred", String.class.equals(context.getLastTypeParameters()[0])); } public final void testInferLastTypeParametersFromMethod() { ParserContext context = new ParserContext(); context.setStrongTyping(true); context.addInput("a", A.class); final CompiledExpression compiledExpression = new ExpressionCompiler("a.values()") .compile(context); final Object val = MVEL.executeExpression(compiledExpression, new AWrapper()); assertTrue("Expression did not evaluate correctly: " + val, STRINGS.equals(val)); assertTrue("No type parameters detected", null != context.getLastTypeParameters()); assertTrue("Wrong parametric type inferred", String.class.equals(context.getLastTypeParameters()[0])); } public final void testInferLastTypeParametersFromPropertyMethod() { ParserContext context = new ParserContext(); context.setStrongTyping(true); context.addInput("a", A.class); final CompiledExpression compiledExpression = new ExpressionCompiler("a.getFooMap()[\"key\"].someMethod()") .compile(context); final Object val = MVEL.executeExpression(compiledExpression, new AWrapper()); assertEquals("Expression did not evaluate correctly: ", "bar", val); assertNotNull("No type parameters detected", context.getLastTypeParameters()); assertEquals("Wrong parametric type inferred", String.class, context.getLastTypeParameters()[0]); } public final void testTypeByMethod() { ParserContext context = new ParserContext(); context.setStrongTyping(true); context.addInput("a", A.class); CompiledExpression compiledExpression = new ExpressionCompiler("!a.show").compile(context); assertEquals(Boolean.class, compiledExpression.getKnownEgressType()); } // public final void testInferLastTypeParametersFromPropertyMethod2() { // ParserContext context = new ParserContext(); // context.setStrictTypeEnforcement( true ); // // context.addInput("a", A.class); // // ExpressionCompiler compiler = new ExpressionCompiler("a.getBarMap()[\"key\"].someMethod();"); // final CompiledExpression compiledExpression = compiler.compile(context); // // Map vars = new HashMap(); // vars.put( "a", new A() ); // final Object val = MVEL.executeExpression(compiledExpression, vars); // // assertEquals("Expression did not evaluate correctly: ", "bar", val); // assertNotNull("No type parameters detected", context.getLastTypeParameters()); // assertEquals("Wrong parametric type inferred", String.class, context.getLastTypeParameters()[0]); // } public static class AWrapper { public A getA() { return new A(); } } public static class A { private boolean show; public boolean isShow() { return show; } public void setShow(boolean show) { this.show = show; } public List getStrings() { return STRINGS; } public List values() { return STRINGS; } public Map getFooMap() { Map map = new HashMap(); map.put( "key", new Foo(){ public String someMethod() { return "bar"; } } ); return map; } public Map getBarMap() { Map map = new HashMap(); map.put( "key", new FooImpl() ); return map; } } public static interface Foo { public String someMethod(); } public static class FooImpl implements Foo { public String someMethod() { return "bar"; } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/0000755000175000017500000000000011412747040021045 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/AccessorBMModel.java0000644000175000017500000000272211167215375024665 0ustar drazzibdrazzibpackage org.mvel2.tests; import java.util.List; import java.util.Map; import org.mvel2.DataConversion; import org.mvel2.compiler.Accessor; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.PropertyHandler; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.GlobalListenerFactory; import org.mvel2.tests.core.res.Foo; import org.mvel2.util.StringAppender; public class AccessorBMModel implements Accessor { private ExecutableStatement p0; public PropertyHandler nullPropertyHandler; public PropertyHandler nullMethodHandler; public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { StringAppender append = new StringAppender().append("foo").append(((String)ctx).toString().trim()); return append; } public Object setValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory, Object value) { GlobalListenerFactory.notifySetListeners(ctx, "foobie", variableFactory, value); return value; } public Class getKnownEgressType() { return Object.class; } public void setNullPropertyHandler(PropertyHandler handler) { this.nullPropertyHandler = handler; } public void setNullMethodHandler(PropertyHandler handler) { this.nullMethodHandler = handler; } public String toString() { return "FOFOSLDJALKJ"; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/0000755000175000017500000000000011412747040021775 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/WithTests.java0000644000175000017500000001157011246517502024605 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import static org.mvel2.MVEL.executeExpression; import org.mvel2.ParserContext; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.tests.core.res.Base; import org.mvel2.tests.core.res.Foo; import java.util.HashMap; import java.util.Map; public class WithTests extends AbstractTest { public void testWith() { assertEquals("OneTwo", test("with (foo) {aValue = 'One',bValue='Two'}; foo.aValue + foo.bValue;")); } public void testWith2() { assertEquals("OneTwoOne", test( "var y; with (foo) { \n" + "aValue = (y = 'One'), // this is a comment \n" + "bValue='Two' // this is also a comment \n" + "}; \n" + "foo.aValue + foo.bValue + y;")); } public void testWith3() { assertEquals("OneOneTwoTwo", test("with (foo) {aValue = 'One',bValue='Two'}; with (foo) {aValue += 'One', bValue += 'Two'}; foo.aValue + foo.bValue;")); } public void testWith4() { assertEquals(10, test("with (foo) {countTest += 5 }; with (foo) { countTest *= 2 }; foo.countTest")); } public void testWith5() { Foo foo = (Foo) test("with (foo) { countTest += 5, \n" + "// foobar!\n" + "aValue = 'Hello',\n" + "/** Comment! **/\n" + "bValue = 'Goodbye'\n }; with (foo) { countTest *= 2 }; foo"); assertEquals(10, foo.getCountTest()); assertEquals("Hello", foo.aValue); assertEquals("Goodbye", foo.bValue); } public void testInlineWith() { CompiledExpression expr = new ExpressionCompiler("foo.{name='poopy', aValue='bar'}").compile(); Foo f = (Foo) executeExpression(expr, createTestMap()); assertEquals("poopy", f.getName()); assertEquals("bar", f.aValue); } public void testInlineWith2() { CompiledExpression expr = new ExpressionCompiler("foo.{name = 'poopy', aValue = 'bar', bar.{name = 'foobie'}}").compile(); Foo f = (Foo) executeExpression(expr, createTestMap()); assertEquals("poopy", f.getName()); assertEquals("bar", f.aValue); assertEquals("foobie", f.getBar().getName()); } public void testInlineWith3() { CompiledExpression expr = new ExpressionCompiler("foo.{name = 'poopy', aValue = 'bar', bar.{name = 'foobie'}, toUC('doopy')}").compile(); Foo f = (Foo) executeExpression(expr, createTestMap()); assertEquals("poopy", f.getName()); assertEquals("bar", f.aValue); assertEquals("foobie", f.getBar().getName()); assertEquals("doopy", f.register); } public void testInlineWith3a() { CompiledExpression expr = new ExpressionCompiler("foo.{name='poopy',aValue='bar',bar.{name='foobie'},toUC('doopy')}").compile(); Foo f = (Foo) executeExpression(expr, createTestMap()); assertEquals("poopy", f.getName()); assertEquals("bar", f.aValue); assertEquals("foobie", f.getBar().getName()); assertEquals("doopy", f.register); } public void testInlineWith4() { OptimizerFactory.setDefaultOptimizer("ASM"); ExpressionCompiler expr = new ExpressionCompiler("new Foo().{ name = 'bar' }"); ParserContext pCtx = new ParserContext(); pCtx.addImport(Foo.class); CompiledExpression c = expr.compile(pCtx); Foo f = (Foo) executeExpression(c); assertEquals("bar", f.getName()); f = (Foo) executeExpression(c); assertEquals("bar", f.getName()); } public void testInlineWith5() { OptimizerFactory.setDefaultOptimizer("ASM"); ParserContext pCtx = new ParserContext(); pCtx.setStrongTyping(true); pCtx.addInput("foo", Foo.class); CompiledExpression expr = new ExpressionCompiler("foo.{name='poopy', aValue='bar'}").compile(pCtx); Foo f = (Foo) executeExpression(expr, createTestMap()); assertEquals("poopy", f.getName()); assertEquals("bar", f.aValue); } public void testInlineWithImpliedThis() { Base b = new Base(); ExpressionCompiler expr = new ExpressionCompiler(".{ data = 'foo' }"); CompiledExpression compiled = expr.compile(); executeExpression(compiled, b); assertEquals(b.data, "foo"); } public void testSingleMethodCall() { Base b = new Base(); Map map = new HashMap(); map.put("base", b); MVEL.eval("base.{ populate() }", map); assertEquals("sarah", b.barfoo); } public void testWithMultipleMethodCalls() { ParserContext ctx = ParserContext.create().stronglyTyped().withInput("foo", Foo.class); MVEL.compileExpression("with (foo) { setName('foo'), setBar(null) }", ctx); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/PropertyAccessUnitTest.java0000644000175000017500000000330211073524603027305 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import junit.framework.TestCase; import org.mvel2.PropertyAccessor; import org.mvel2.tests.core.res.Base; import org.mvel2.tests.core.res.Foo; public class PropertyAccessUnitTest extends TestCase { Base base = new Base(); public void testPropertyRead() { assertEquals("cat", PropertyAccessor.get("data", base)); } public void testDeepPropertyRead() { assertEquals("dog", PropertyAccessor.get("foo.bar.name", base)); } public void testWrite() { PropertyAccessor.set(base, "foo.bar.name", "cat"); assertEquals("cat", PropertyAccessor.get("foo.bar.name", base)); PropertyAccessor.set(base, "foo.bar.name", "dog"); } public void testCollectionsAccess() { PropertyAccessor.set(base, "funMap['foo'].bar.name", "cat"); assertEquals("cat", PropertyAccessor.get("funMap['foo'].bar.name", base)); } public void testMethodInvoke() { assertEquals("WOOF", PropertyAccessor.get("foo.toUC('woof')", base)); } public void testMethodInvoke2() { assertEquals("happyBar", PropertyAccessor.get("foo.happy()", base)); } public void testMapDirect() { assertTrue(PropertyAccessor.get("funMap['foo']", base) instanceof Foo); } public void testArrayAccess() { String[] a = new String[]{"foo", "bar",}; assertEquals("foo", PropertyAccessor.get("[0]", a)); } public void testArrayAccess2() { assertEquals("poo", PropertyAccessor.get("[0][0]", new Object[]{new String[]{"poo"}})); } public void testStaticMethodAccess() { assertEquals(String.class, PropertyAccessor.get("forName('java.lang.String')", Class.class)); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/SamplesTests.java0000644000175000017500000000527311172704121025272 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import static org.mvel2.MVEL.compileExpression; import static org.mvel2.MVEL.executeExpression; import static org.mvel2.util.ParseTools.loadFromFile; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; public class SamplesTests extends AbstractTest { public void testFunctionsScript1() throws IOException { MVEL.evalFile(new File("samples/scripts/functions1.mvel")); } public void testQuickSortScript1() throws IOException { MVEL.evalFile(new File("samples/scripts/quicksort.mvel")); } public void testQuickSortScriptFunctional() throws IOException { MVEL.evalFile(new File("samples/scripts/fquicksort.mvel")); } public void testQuickSortScript2() throws IOException { Object[] sorted = (Object[]) test(new String(loadFromFile(new File("samples/scripts/quicksort.mvel")))); int last = -1; for (Object o : sorted) { if (last == -1) { last = (Integer) o; } else { assertTrue(((Integer) o) > last); last = (Integer) o; } } } public void testQuickSortScript3() throws IOException { Object[] sorted = (Object[]) test(new String(loadFromFile(new File("samples/scripts/quicksort2.mvel")))); int last = -1; for (Object o : sorted) { if (last == -1) { last = (Integer) o; } else { assertTrue(((Integer) o) > last); last = (Integer) o; } } } public void testQuickSortScript4() throws IOException { Object[] sorted = (Object[]) MVEL.eval(new String(loadFromFile(new File("samples/scripts/quicksort3.mvel"))), new HashMap()); int last = -1; for (Object o : sorted) { if (last == -1) { last = (Integer) o; } else { assertTrue(((Integer) o) > last); last = (Integer) o; } } } public void testQuickSortScript5() throws IOException { List sorted = (List) executeExpression(compileExpression(loadFromFile(new File("samples/scripts/fquicksort.mvel"))), new HashMap()); int last = -1; for (Object o : sorted) { if (last == -1) { last = (Integer) o; } else { assertTrue(((Integer) o) > last); last = (Integer) o; } } } public void testMultiLineString() throws IOException { MVEL.evalFile(new File("samples/scripts/multilinestring.mvel")); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/ComparisonTests.java0000644000175000017500000001513511235611071025777 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import org.mvel2.tests.core.res.Foo; import java.util.HashMap; public class ComparisonTests extends AbstractTest { public void testBooleanOperator() { assertEquals(true, test("foo.bar.woof == true")); } public void testBooleanOperator2() { assertEquals(false, test("foo.bar.woof == false")); } public void testBooleanOperator3() { assertEquals(true, test("foo.bar.woof== true")); } public void testBooleanOperator4() { assertEquals(false, test("foo.bar.woof ==false")); } public void testBooleanOperator5() { assertEquals(true, test("foo.bar.woof == true")); } public void testBooleanOperator6() { assertEquals(false, test("foo.bar.woof==false")); } public void testTextComparison() { assertEquals(true, test("foo.bar.name == 'dog'")); } public void testNETextComparison() { assertEquals(true, test("foo.bar.name != 'foo'")); } public void testChor() { assertEquals("cat", test("a or b or c")); } public void testChorWithLiteral() { assertEquals("fubar", test("a or 'fubar'")); } public void testNullCompare() { assertEquals(true, test("c != null")); } public void testLessThan() { assertEquals(true, test("pi < 3.15")); assertEquals(true, test("pi <= 3.14")); assertEquals(false, test("pi > 3.14")); assertEquals(true, test("pi >= 3.14")); } public void testNegation() { assertEquals(true, test("!fun && !fun")); } public void testNegation2() { assertEquals(false, test("fun && !fun")); } public void testNegation3() { assertEquals(true, test("!(fun && fun)")); } public void testNegation4() { assertEquals(false, test("(fun && fun)")); } public void testNegation5() { assertEquals(true, test("!false")); } public void testNegation6() { assertEquals(false, test("!true")); } public void testNegation7() { assertEquals(true, test("s = false; t = !s; t")); } public void testNegation8() { assertEquals(true, test("s = false; t =! s; t")); } public void testRegEx() { assertEquals(true, test("foo.bar.name ~= '[a-z].+'")); } public void testRegExNegate() { assertEquals(false, test("!(foo.bar.name ~= '[a-z].+')")); } public void testRegEx2() { assertEquals(true, test("foo.bar.name ~= '[a-z].+' && foo.bar.name != null")); } public void testRegEx3() { assertEquals(true, test("foo.bar.name~='[a-z].+'&&foo.bar.name!=null")); } public void testBlank() { assertEquals(true, test("'' == empty")); } public void testBlank2() { assertEquals(true, test("BWAH == empty")); } public void testInstanceCheck1() { assertEquals(true, test("c is java.lang.String")); } public void testInstanceCheck2() { assertEquals(false, test("pi is java.lang.Integer")); } public void testInstanceCheck3() { assertEquals(true, test("foo is org.mvel2.tests.core.res.Foo")); } public void testContains1() { assertEquals(true, test("list contains 'Happy!'")); } public void testContains2() { assertEquals(false, test("list contains 'Foobie'")); } public void testContains3() { assertEquals(true, test("sentence contains 'fox'")); } public void testContains4() { assertEquals(false, test("sentence contains 'mike'")); } public void testContains5() { assertEquals(true, test("!(sentence contains 'mike')")); } public void testContains6() { assertEquals(true, test("bwahbwah = 'mikebrock'; testVar10 = 'mike'; bwahbwah contains testVar10")); } public void testSoundex() { assertTrue((Boolean) test("'foobar' soundslike 'fubar'")); } public void testSoundex2() { assertFalse((Boolean) test("'flexbar' soundslike 'fubar'")); } public void testSoundex3() { assertEquals(true, test("(c soundslike 'kat')")); } public void testSimilarity1() { assertEquals(0.6666667f, test("c strsim 'kat'")); } public void testSoundex4() { assertEquals(true, test("_xx1 = 'cat'; _xx2 = 'katt'; (_xx1 soundslike _xx2)")); } public void testSoundex5() { assertEquals(true, test("_type = 'fubar';_type soundslike \"foobar\"")); } public void testThisReference3() { assertEquals(true, test("this is org.mvel2.tests.core.res.Base")); } public void testThisReference4() { assertEquals(true, test("this.funMap instanceof java.util.Map")); } public void testThisReference5() { assertEquals(true, test("this.data == 'cat'")); } public void testDateComparison() { assertTrue((Boolean) test("dt1 < dt2")); } public void testConvertableTo() { assertEquals(true, test("pi convertable_to Integer")); } public void testStringEquals() { assertEquals(true, test("ipaddr == '10.1.1.2'")); } public void testCharComparison() { assertEquals(true, test("'z' > 'a'")); } public void testCharComparison2() { assertEquals(false, test("'z' < 'a'")); } public void testJIRA100b() { String expression = "(8 / 10) * 100 <= 80;"; assertEquals((8 / 10) * 100 <= 80, testCompiledSimple(expression, new HashMap())); } public void testJIRA92() { assertEquals(false, test("'stringValue' > null")); } public void testIsDefOperator() { assertEquals(true, test("_v1 = 'bar'; isdef _v1")); } public void testIsDefOperator2() { assertEquals(false, test("isdef _v1")); } public void testIsDefOperator3() { assertEquals(true, test("!(isdef _v1)")); } public void testIsDefOperator4() { assertEquals(true, test("! (isdef _v1)")); } public void testIsDefOperator5() { assertEquals(true, test("!isdef _v1")); } public void testIsDefOperator6() { Foo foo = new Foo(); assertEquals(true, MVEL.eval("isdef name", foo)); assertEquals(true, MVEL.executeExpression(MVEL.compileExpression("isdef name"), foo)); } public void testJIRA152() { assertEquals(true, MVEL.eval("1== -(-1)")); assertEquals(true, MVEL.executeExpression(MVEL.compileExpression("1==-(-1)"))); } public void testJIRA157() { assertEquals(true, MVEL.eval("1 == ((byte) 1)")); } public void testJIRA181() { assertEquals(false, MVEL.eval("0<-1")); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/ArithmeticTests.java0000644000175000017500000007252111356644701025772 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import static org.mvel2.MVEL.compileExpression; import static org.mvel2.MVEL.executeExpression; import org.mvel2.ParserContext; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.util.Make; import java.io.Serializable; import java.math.BigDecimal; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class ArithmeticTests extends AbstractTest { public void testMath() { assertEquals(188.4d, test("pi * hour")); } public void testMath2() { assertEquals(3, test("foo.number-1")); } public void testMath3() { assertEquals((10d * 5d) * 2d / 3d, test("(10 * 5) * 2 / 3")); } public void testMath4() { double val = ((100d % 3d) * 2d - 1d / 1d + 8d + (5d * 2d)); assertEquals(val, test("(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)")); } public void testMath4a() { String expression = "(100 % 90) * 20 - 15 / 16 + 80 + (50 * 21)"; System.out.println("Expression: " + expression); assertEquals(((100d % 90d) * 20d - 15d / 16d + 80d + (50d * 21d)), MVEL.eval(expression)); } public void testMath5() { assertEquals(300.5 / 5.3 / 2.1 / 1.5, test("300.5 / 5.3 / 2.1 / 1.5")); } public void testMath5a() { String expression = "300.5 / 5.3 / 2.1 / 1.5"; System.out.println("Expression: " + expression); assertEquals(300.5 / 5.3 / 2.1 / 1.5, MVEL.eval(expression)); } public void testMath6() { double val = (300 * 5 + 1) + 100 / 2 * 2; assertEquals(val, test("(300 * five + 1) + (100 / 2 * 2)")); } public void testMath7() { double val = ((100d % 3d) * 2d - 1d / 1d + 8d + (5d * 2d)); assertEquals(val, test("(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)")); } public void testMath8() { double val = 5d * (100.56d * 30.1d); assertEquals(val, test("5 * (100.56 * 30.1)")); } public void testPowerOf() { assertEquals(25, test("5 ** 2")); } public void testSignOperator() { assertEquals(-15, test("int x = 15; -x")); } public void testMath14() { assertEquals(10 - 5 * 2 + 5 * 8 - 4, test("10-5*2 + 5*8-4")); } public void testMath15() { String ex = "100-500*200 + 500*800-400"; assertEquals(100 - 500 * 200 + 500 * 800 - 400, test(ex)); } public void testMath16() { String ex = "100-500*200*150 + 500*800-400"; assertEquals(100 - 500 * 200 * 150 + 500 * 800 - 400, test(ex)); } public void testMath17() { String ex = "(100d * 50d) * 20d / 30d * 2d"; Object o = test(ex); assertEquals((100d * 50d) * 20d / 30d * 2d, o); } public void testMath18() { String ex = "a = 100d; b = 50d; c = 20d; d = 30d; e = 2d; (a * b) * c / d * e"; System.out.println("Expression: " + ex); assertEquals((100d * 50d) * 20d / 30d * 2d, testCompiledSimple(ex, new HashMap())); } public void testMath19() { String ex = "a = 100; b = 500; c = 200; d = 150; e = 500; f = 800; g = 400; a-b*c*d + e*f-g"; System.out.println("Expression: " + ex); assertEquals(100 - 500 * 200 * 150 + 500 * 800 - 400, testCompiledSimple(ex, new HashMap())); } public void testMath32() { String ex = "x = 20; y = 10; z = 5; x-y-z"; System.out.println("Expression: " + ex); assertEquals(20 - 10 - 5, testCompiledSimple(ex, new HashMap())); } public void testMath33() { String ex = "x = 20; y = 2; z = 2; x/y/z"; System.out.println("Expression: " + ex); assertEquals((double) 20 / 2 / 2, testCompiledSimple(ex, new HashMap())); } public void testMath20() { String ex = "10-5*7-3*8-6"; System.out.println("Expression: " + ex); assertEquals(10 - 5 * 7 - 3 * 8 - 6, test(ex)); } public void testMath21() { String expression = "100-50*70-30*80-60"; System.out.println("Expression: " + expression); assertEquals(100 - 50 * 70 - 30 * 80 - 60, test(expression)); } public void testMath22() { String expression = "(100-50)*70-30*(20-9)**3"; System.out.println("Expression: " + expression); assertEquals((int) ((100 - 50) * 70 - 30 * Math.pow(20 - 9, 3)), test(expression)); } public void testMath22b() { String expression = "a = 100; b = 50; c = 70; d = 30; e = 20; f = 9; g = 3; (a-b)*c-d*(e-f)**g"; System.out.println("Expression: " + expression); assertEquals((int) ((100 - 50) * 70 - 30 * Math.pow(20 - 9, 3)), testCompiledSimple(expression, new HashMap())); } public void testMath23() { String expression = "10 ** (3)*10**3"; System.out.println("Expression: " + expression); assertEquals((int) (Math.pow(10, 3) * Math.pow(10, 3)), test(expression)); } public void testMath24() { String expression = "51 * 52 * 33 / 24 / 15 + 45 * 66 * 47 * 28 + 19"; double val = 51d * 52d * 33d / 24d / 15d + 45d * 66d * 47d * 28d + 19d; System.out.println("Expression: " + expression); System.out.println("Expected Result: " + val); assertEquals(val, test(expression)); } public void testMath25() { String expression = "51 * (40 - 1000 * 50) + 100 + 50 * 20 / 10 + 11 + 12 - 80"; double val = 51 * (40 - 1000 * 50) + 100 + 50 * 20 / 10 + 11 + 12 - 80; System.out.println("Expression: " + expression); System.out.println("Expected Result: " + val); assertEquals(val, test(expression)); } public void testMath26() { String expression = "5 + 3 * 8 * 2 ** 2"; int val = (int) (5d + 3d * 8d * Math.pow(2, 2)); System.out.println("Expression: " + expression); System.out.println("Expected Result: " + val); Object result = test(expression); assertEquals(val, result); } public void testMath27() { String expression = "50 + 30 * 80 * 20 ** 3 * 51"; double val = 50 + 30 * 80 * Math.pow(20, 3) * 51; System.out.println("Expression: " + expression); System.out.println("Expected Result: " + val); Object result = test(expression); assertEquals((int) val, result); } public void testMath28() { String expression = "50 + 30 + 80 + 11 ** 2 ** 2 * 51"; double val = 50 + 30 + 80 + Math.pow(Math.pow(11, 2), 2) * 51; Object result = test(expression); assertEquals((int) val, result); } public void testMath29() { String expression = "10 + 20 / 4 / 4"; System.out.println("Expression: " + expression); double val = 10d + 20d / 4d / 4d; assertEquals(val, MVEL.eval(expression)); } public void testMath30() { String expression = "40 / 20 + 10 + 60 / 21"; System.out.println("Expression: " + expression); double val = 40d / 20d + 10d + 60d / 21d; assertEquals(val, MVEL.eval(expression)); } public void testMath31() { String expression = "40 / 20 + 5 - 4 + 8 / 2 * 2 * 6 ** 2 + 6 - 8"; double val = 40f / 20f + 5f - 4f + 8f / 2f * 2f * Math.pow(6, 2) + 6f - 8f; assertEquals( val, MVEL.eval(expression)); } public void testMath34() { String expression = "a+b-c*d*x/y-z+10"; Map map = new HashMap(); map.put("a", 200); map.put("b", 100); map.put("c", 150); map.put("d", 2); map.put("x", 400); map.put("y", 300); map.put("z", 75); Serializable s = compileExpression(expression); assertEquals((double) 200 + 100 - 150 * 2 * 400 / 300 - 75 + 10, executeExpression(s, map)); } public void testMath34_Interpreted() { String expression = "a+b-c*x/y-z"; Map map = new HashMap(); map.put("a", 200); map.put("b", 100); map.put("c", 150); map.put("x", 400); map.put("y", 300); map.put("z", 75); assertEquals((double) 200 + 100 - 150 * 400 / 300 - 75, MVEL.eval(expression, map)); } public void testMath35() { String expression = "b/x/b/b*y+a"; Map map = new HashMap(); map.put("a", 10); map.put("b", 20); map.put("c", 30); map.put("x", 40); map.put("y", 50); map.put("z", 60); assertNumEquals(20d / 40d / 20d / 20d * 50d + 10d, executeExpression(compileExpression(expression), map)); } public void testMath35_Interpreted() { String expression = "b/x/b/b*y+a"; Map map = new HashMap(); map.put("a", 10); map.put("b", 20); map.put("c", 30); map.put("x", 40); map.put("y", 50); map.put("z", 60); assertNumEquals(20d / 40d / 20d / 20d * 50d + 10d, MVEL.eval(expression, map)); } public void testMath36() { String expression = "b/x*z/a+x-b+x-b/z+y"; Map map = new HashMap(); map.put("a", 10); map.put("b", 20); map.put("c", 30); map.put("x", 40); map.put("y", 50); map.put("z", 60); Serializable s = compileExpression(expression); assertNumEquals(20d / 40d * 60d / 10d + 40d - 20d + 40d - 20d / 60d + 50d, executeExpression(s, map)); } public void testMath37() { String expression = "x+a*a*c/x*b*z+x/y-b"; Map map = new HashMap(); map.put("a", 10); map.put("b", 20); map.put("c", 30); map.put("x", 2); map.put("y", 2); map.put("z", 60); Serializable s = compileExpression(expression); assertNumEquals(2d + 10d * 10d * 30d / 2d * 20d * 60d + 2d / 2d - 20d, executeExpression(s, map)); } public void testMath38() { String expression = "100 + 200 - 300 + 400 - 500 + 105 / 205 - 405 + 305 * 206"; double res = 100d + 200d - 300d + 400d - 500d + 105d / 205d - 405d + 305d * 206d; System.out.println("Expression: " + expression); System.out.println("CorrectResult:" + res); assertEquals(res, MVEL.eval(expression)); } public void testMath39() { String expression = "147 + 60 / 167 % 448 + 36 * 23 / 166"; double res = 147d + 60d / 167d % 448d + 36d * 23d / 166d; System.out.println("Expression: " + expression); System.out.println("CorrectRes: " + res); assertEquals(res, MVEL.eval(expression)); } public void testMath40() { String expression = "228 - 338 % 375 - 103 + 260 + 412 * 177 + 121"; double res = 228d - 338d % 375d - 103d + 260d + 412d * 177d + 121d; System.out.println("Expression: " + expression); System.out.println("CorrectRes: " + res); assertEquals(res, MVEL.eval(expression, Double.class)); } public void testMath41() { String expression = "304d - 246d / 242d % 235d / 425d - 326d + 355d * 264d % 308d"; double res = 304d - 246d / 242d % 235d / 425d - 326d + 355d * 264d % 308d; System.out.println("Expression: " + expression); System.out.println("CorrectRes: " + res); assertEquals(res, MVEL.eval(expression)); } public void testMath42() { String expression = "11d - 7d / 3d * 18d % 14d * 8d * 11d - 2d - 11d / 13d + 14d"; double res = 11d - 7d / 3d * 18d % 14d * 8d * 11d - 2d - 11d / 13d + 14d; System.out.println("Expression: " + expression); System.out.println("CorrectRes: " + res); assertEquals(res, MVEL.eval(expression)); } public void testMath43() { String expression = "4d/3d*6d%8d*5d*8d+7d+9d*1d"; double res = 4d / 3d * 6d % 8d * 5d * 8d + 7d + 9d * 1d; System.out.println("Expression: " + expression); System.out.println("CorrectRes: " + res); assertEquals(res, MVEL.eval(expression)); } public void testMath44() { String expression = "6d+8d/9d*1d*9d*10d%4d*4d-4d*6d*3d"; double res = 6d + 8d / 9d * 1d * 9d * 10d % 4d * 4d - 4d * 6d * 3d; System.out.println("Expression: " + expression); System.out.println("CorrectRes: " + res); assertEquals(res, MVEL.eval(expression)); } public void testMath44b() { String expression = "a+b/c*d*e*f%g*h-i*j*k"; double res = 6d + 8d / 9d * 1d * 9d * 10d % 4d * 4d - 4d * 6d * 3d; Serializable s = compileExpression(expression); Map vars = new HashMap(); vars.put("a", 6d); vars.put("b", 8d); vars.put("c", 9d); vars.put("d", 1d); vars.put("e", 9d); vars.put("f", 10d); vars.put("g", 4d); vars.put("h", 4d); vars.put("i", 4d); vars.put("j", 6d); vars.put("k", 3d); assertEquals(res, executeExpression(s, vars)); } public void testOperatorPrecedence() { String ex = "_x_001 = 500.2; _x_002 = 200.8; _r_001 = 701; _r_001 == _x_001 + _x_002 || _x_001 == 500 + 0.1"; assertEquals(true, test(ex)); } public void testOperatorPrecedence2() { String ex = "_x_001 = 500.2; _x_002 = 200.8; _r_001 = 701; _r_001 == _x_001 + _x_002 && _x_001 == 500 + 0.2"; assertEquals(true, test(ex)); } public void testOperatorPrecedence3() { String ex = "_x_001 = 500.2; _x_002 = 200.9; _r_001 = 701; _r_001 == _x_001 + _x_002 && _x_001 == 500 + 0.2"; assertEquals(false, test(ex)); } public void testOperatorPrecedence4() { String ex = "_x_001 = 500.2; _x_002 = 200.9; _r_001 = 701; _r_001 == _x_001 + _x_002 || _x_001 == 500 + 0.2"; assertEquals(true, test(ex)); } public void testOperatorPrecedence5() { String ex = "_x_001 == _x_001 / 2 - _x_001 + _x_001 + _x_001 / 2 && _x_002 / 2 == _x_002 / 2"; Map vars = new HashMap(); vars.put("_x_001", 500.2); vars.put("_x_002", 200.9); vars.put("_r_001", 701); ExpressionCompiler compiler = new ExpressionCompiler(ex); assertEquals(true, executeExpression(compiler.compile(), vars)); } public void testModulus() { assertEquals(38392 % 2, test("38392 % 2")); } public void testBitwiseOr1() { assertEquals(6, test("2|4")); } public void testBitwiseOr2() { assertEquals(true, test("(2 | 1) > 0")); } public void testBitwiseOr3() { assertEquals(true, test("(2|1) == 3")); } public void testBitwiseOr4() { assertEquals(2 | 5, test("2|five")); } public void testBitwiseAnd1() { assertEquals(2, test("2 & 3")); } public void testBitwiseAnd2() { assertEquals(5 & 3, test("five & 3")); } public void testShiftLeft() { assertEquals(4, test("2 << 1")); } public void testShiftLeft2() { assertEquals(5 << 1, test("five << 1")); } public void testUnsignedShiftLeft() { assertEquals(2, test("-2 <<< 0")); } public void testShiftRight() { assertEquals(128, test("256 >> 1")); } public void testShiftRight2() { assertEquals(5 >> 1, test("five >> 1")); } public void testUnsignedShiftRight() { assertEquals(-5 >>> 1, test("-5 >>> 1")); } public void testUnsignedShiftRight2() { assertEquals(-5 >>> 1, test("(five - 10) >>> 1")); } public void testShiftRightAssign() { assertEquals(5 >> 2, test("_zZz = 5; _zZz >>= 2")); } public void testShiftLeftAssign() { assertEquals(10 << 2, test("_yYy = 10; _yYy <<= 2")); } public void testUnsignedShiftRightAssign() { assertEquals(-5 >>> 2, test("_xXx = -5; _xXx >>>= 2")); } public void testXOR() { assertEquals(3, test("1 ^ 2")); } public void testXOR2() { assertEquals(5 ^ 2, test("five ^ 2")); } public void testInvert() { assertEquals(~10, test("~10")); } public void testInvert2() { assertEquals(~(10 + 1), test("~(10 + 1)")); } public void testInvert3() { assertEquals(~10 + (1 + ~50), test("~10 + (1 + ~50)")); } public void testDeepPropertyAdd() { assertEquals(10, test("foo.countTest+ 10")); } public void testDeepAssignmentIncrement() { assertEquals(true, test("foo.countTest += 5; if (foo.countTest == 5) { foo.countTest = 0; return true; }" + " else { foo.countTest = 0; return false; }")); } public void testDeepAssignmentWithBlock() { assertEquals(true, test("with (foo) { countTest += 5 }; if (foo.countTest == 5) { foo.countTest = 0; return true; }" + " else { foo.countTest = 0; return false; }")); } public void testOperativeAssignMod() { int val = 5; assertEquals(val %= 2, test("int val = 5; val %= 2; val")); } public void testOperativeAssignDiv() { int val = 10; assertEquals(val /= 2, test("int val = 10; val /= 2; val")); } public void testOperativeAssignShift1() { int val = 5; assertEquals(val <<= 2, test("int val = 5; val <<= 2; val")); } public void testOperativeAssignShift2() { int val = 5; assertEquals(val >>= 2, test("int val = 5; val >>= 2; val")); } public void testOperativeAssignShift3() { int val = -5; assertEquals(val >>>= 2, test("int val = -5; val >>>= 2; val")); } public void testAssignPlus() { assertEquals(10, test("xx0 = 5; xx0 += 4; xx0 + 1")); } public void testAssignPlus2() { assertEquals(10, test("xx0 = 5; xx0 =+ 4; xx0 + 1")); } public void testAssignDiv() { assertEquals(2.0, test("xx0 = 20; xx0 /= 10; xx0")); } public void testAssignMult() { assertEquals(36, test("xx0 = 6; xx0 *= 6; xx0")); } public void testAssignSub() { assertEquals(11, test("xx0 = 15; xx0 -= 4; xx0")); } public void testAssignSub2() { assertEquals(-95, test("xx0 = 5; xx0 =- 100")); } public void testBooleanStrAppend() { assertEquals("footrue", test("\"foo\" + true")); } public void testStringAppend() { assertEquals("catbar", test("c + 'bar'")); } public void testNegation() { assertEquals(1, test("-(-1)")); } public void testStrongTypingModeComparison() { ParserContext parserContext = new ParserContext(); parserContext.setStrongTyping(true); parserContext.addInput("a", Long.class); CompiledExpression compiledExpression = new ExpressionCompiler("a==0").compile(parserContext); HashMap variables = new HashMap(); variables.put("a", 0l); MVEL.executeExpression(compiledExpression, variables); } public void testJIRA158() { Serializable s = MVEL.compileExpression("4/2 + Math.sin(1)"); assertEquals(4 / 2 + Math.sin(1), MVEL.executeExpression(s)); s = MVEL.compileExpression("(float) (4/2 + Math.sin(1))", ParserContext.create().stronglyTyped()); assertEquals((float) (4 / 2 + Math.sin(1)), MVEL.executeExpression(s)); } public void testJIRA162() { Serializable s = MVEL.compileExpression("1d - 2d + (3d * var1) * var1", ParserContext.create().withInput("var1", double.class)); Map vars = new HashMap(); vars.put("var1", 1d); assertEquals((1 - 2 + (3 * 1d) * 1), MVEL.executeExpression(s, vars)); } public void testJIRA161() { Serializable s = MVEL.compileExpression("1==-(-1)", ParserContext.create().stronglyTyped()); assertEquals(1 == -(-1), MVEL.executeExpression(s)); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); CompiledExpression compiledExpression = new ExpressionCompiler("1==-(-1)").compile(ctx); assertEquals(1 == -(-1), MVEL.executeExpression(compiledExpression)); } public void testJIRA163() { Serializable s = MVEL.compileExpression("1d - 2d + (3d * 4d) * var1", ParserContext.create().withInput("var1", double.class)); Map vars = new HashMap(); vars.put("var1", 1d); assertEquals((1 - 2 + (3 * 4) * 1d), MVEL.executeExpression(s, vars)); } public void testJIRA164() { Serializable s = MVEL.compileExpression("1 / (var1 + var1) * var1", ParserContext.create().stronglyTyped().withInput("var1", double.class)); Map vars = new HashMap(); double var1 = 1d; vars.put("var1", var1); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals((1 / (var1 + var1) * var1), MVEL.executeExpression(s, vars)); s = MVEL.compileExpression("1 / (var1 + var1) * var1", ParserContext.create().withInput("var1", double.class)); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals((1 / (var1 + var1) * var1), MVEL.executeExpression(s, vars)); } public void testJIRA164b() { Serializable s = MVEL.compileExpression("1 + 1 / (var1 + var1) * var1", ParserContext.create().stronglyTyped().withInput("var1", double.class)); Map vars = new HashMap(); double var1 = 1d; vars.put("var1", var1); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals((1 + 1 / (var1 + var1) * var1), MVEL.executeExpression(s, vars)); s = MVEL.compileExpression("1 + 1 / (var1 + var1) * var1", ParserContext.create().withInput("var1", double.class)); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals((1 + 1 / (var1 + var1) * var1), MVEL.executeExpression(s, vars)); } public void testJIRA164c() { Serializable s = MVEL.compileExpression("1 + 1 / (var1 + var1 + 2 + 3) * var1", ParserContext.create().stronglyTyped().withInput("var1", double.class)); Map vars = new HashMap(); double var1 = 1d; vars.put("var1", var1); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals((1 + 1 / (var1 + var1 + 2 + 3) * var1), MVEL.executeExpression(s, vars)); s = MVEL.compileExpression("1 + 1 / (var1 + var1 + 2 + 3) * var1", ParserContext.create().withInput("var1", double.class)); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals((1 + 1 / (var1 + var1 + 2 + 3) * var1), MVEL.executeExpression(s, vars)); } public void testJIRA164d() { Serializable s = MVEL.compileExpression("1 + 1 + 1 / (var1 + var1) * var1", ParserContext.create().stronglyTyped().withInput("var1", double.class)); Map vars = new HashMap(); double var1 = 1d; vars.put("var1", var1); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals((1 + 1 + 1 / (var1 + var1) * var1), MVEL.executeExpression(s, vars)); s = MVEL.compileExpression("1 + 1 + 1 / (var1 + var1) * var1", ParserContext.create().withInput("var1", double.class)); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals((1 + 1 + 1 / (var1 + var1) * var1), MVEL.executeExpression(s, vars)); } public void testJIRA164e() { Serializable s = MVEL.compileExpression("10 + 11 + 12 / (var1 + var1 + 51 + 71) * var1 + 13 + 14", ParserContext.create().stronglyTyped().withInput("var1", double.class)); Map vars = new HashMap(); double var1 = 1d; vars.put("var1", var1); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals((float) (10 + 11 + 12 / (var1 + var1 + 51 + 71) * var1 + 13 + 14), ((Double) MVEL.executeExpression(s, vars)).floatValue()); s = MVEL.compileExpression("10 + 11 + 12 / (var1 + var1 + 51 + 71) * var1 + 13 + 14", ParserContext.create().withInput("var1", double.class)); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals((float) (10 + 11 + 12 / (var1 + var1 + 51 + 71) * var1 + 13 + 14), ((Double) MVEL.executeExpression(s, vars)).floatValue()); } public void testJIRA164f() { Serializable s = MVEL.compileExpression("10 + 11 + 12 / (var1 + 1 + var1 + 51 + 71) * var1 + 13 + 14", ParserContext.create().stronglyTyped().withInput("var1", double.class)); Map vars = new HashMap(); double var1 = 1d; vars.put("var1", var1); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals((float) (10 + 11 + 12 / (var1 + 1 + var1 + 51 + 71) * var1 + 13 + 14), ((Double) MVEL.executeExpression(s, vars)).floatValue()); s = MVEL.compileExpression("10 + 11 + 12 / (var1 + 1 + var1 + 51 + 71) * var1 + 13 + 14", ParserContext.create().withInput("var1", double.class)); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals((float) (10 + 11 + 12 / (var1 + 1 + var1 + 51 + 71) * var1 + 13 + 14), ((Double) MVEL.executeExpression(s, vars)).floatValue()); } public void testJIRA164g() { Serializable s = MVEL.compileExpression("1 - 2 + (3 * var1) * var1", ParserContext.create().stronglyTyped().withInput("var1", double.class)); Map vars = new HashMap(); double var1 = 1d; vars.put("var1", var1); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals((float) (1 - 2 + (3 * var1) * var1), ((Double) MVEL.executeExpression(s, vars)).floatValue()); s = MVEL.compileExpression("1 - 2 + (3 * var1) * var1", ParserContext.create().withInput("var1", double.class)); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals((float) (1 - 2 + (3 * var1) * var1), ((Double) MVEL.executeExpression(s, vars)).floatValue()); } public void testJIRA164h() { Serializable s = MVEL.compileExpression("1 - var1 * (var1 * var1 * (var1 * var1) * var1) * var1", ParserContext.create().stronglyTyped().withInput("var1", double.class)); Map vars = new HashMap(); double var1 = 2d; vars.put("var1", var1); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals((float) (1 - var1 * (var1 * var1 * (var1 * var1) * var1) * var1), ((Double) MVEL.executeExpression(s, vars)).floatValue()); s = MVEL.compileExpression("1 - var1 * (var1 * var1 * (var1 * var1) * var1) * var1", ParserContext.create().withInput("var1", double.class)); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals((float) (1 - var1 * (var1 * var1 * (var1 * var1) * var1) * var1), ((Double) MVEL.executeExpression(s, vars)).floatValue()); } public void testJIRA180() { Serializable s = MVEL.compileExpression("-Math.sin(0)"); MVEL.executeExpression(s); } public void testJIRA208() { Map vars = new LinkedHashMap(); vars.put("bal", 999); String[] testCases = {"bal - 80 - 90 - 30", "bal-80-90-30", "100 + 80 == 180", "100+80==180"}; // System.out.println("bal = " + vars.get("bal")); Object val1, val2; for (String expr : testCases) { System.out.println("Evaluating '" + expr + "': ......"); val1 = MVEL.eval(expr, vars); // System.out.println("'" + expr + " ' = " + ret.toString()); assertNotNull(val1); Serializable compiled = MVEL.compileExpression(expr); val2 = executeExpression(compiled, vars); // System.out.println("'" + expr + " ' = " + ret.toString()); assertNotNull(val2); assertEquals("expression did not evaluate correctly: " + expr, val1, val2); } } public void testJIRA1208a() { assertEquals(799, executeExpression(compileExpression("bal - 80 - 90 - 30"), Make.Map.$()._("bal", 999)._())); } public void testJIRA208b() { Map vars = new LinkedHashMap(); vars.put("bal", 999); String[] testCases = { // "bal + 80 - 80", // "bal - 80 + 80", "bal * 80 / 80", "bal / 80 * 80" }; // System.out.println("bal = " + vars.get("bal")); Object val1, val2; for (String expr : testCases) { System.out.println("Evaluating '" + expr + "': ......"); val1 = MVEL.eval(expr, vars); // System.out.println("'" + expr + " ' = " + ret.toString()); assertNotNull(val1); Serializable compiled = MVEL.compileExpression(expr); val2 = executeExpression(compiled, vars); // System.out.println("'" + expr + " ' = " + ret.toString()); assertNotNull(val2); assertEquals("expression did not evaluate correctly: " + expr, val1, val2); } } public void testJIRA210() { Map vars = new LinkedHashMap(); vars.put("bal", new BigDecimal("999.99")); String[] testCases = {"bal - 1 + \"abc\"",}; Object val1, val2; for (String expr : testCases) { System.out.println("Evaluating '" + expr + "': ......"); val1 = MVEL.eval(expr, vars); // System.out.println("'" + expr + " ' = " + ret.toString()); assertNotNull(val1); Serializable compiled = MVEL.compileExpression(expr); val2 = executeExpression(compiled, vars); // System.out.println("'" + expr + " ' = " + ret.toString()); assertNotNull(val2); assertEquals("expression did not evaluate correctly: " + expr, val1, val2); } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/ProjectionsTests.java0000644000175000017500000000225111172704121026156 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import java.util.Collection; import java.util.Iterator; public class ProjectionsTests extends AbstractTest { public void testProjectionSupport() { assertEquals(true, test("(name in things)contains'Bob'")); } public void testProjectionSupport1() { assertEquals(true, test("(name in things) contains 'Bob'")); } public void testProjectionSupport2() { assertEquals(3, test("(name in things).size()")); } public void testProjectionSupport3() { assertEquals("FOO", test("(toUpperCase() in ['bar', 'foo'])[1]")); } public void testProjectionSupport4() { Collection col = (Collection) test("(toUpperCase() in ['zero', 'zen', 'bar', 'foo'] if ($ == 'bar'))"); assertEquals(1, col.size()); assertEquals("BAR", col.iterator().next()); } public void testProjectionSupport5() { Collection col = (Collection) test("(toUpperCase() in ['zero', 'zen', 'bar', 'foo'] if ($.startsWith('z')))"); assertEquals(2, col.size()); Iterator iter = col.iterator(); assertEquals("ZERO", iter.next()); assertEquals("ZEN", iter.next()); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/InlineCollectionsTests.java0000644000175000017500000000711711317165145027312 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import static org.mvel2.MVEL.compileExpression; import static org.mvel2.MVEL.executeExpression; import org.mvel2.MVEL; import java.util.List; import java.util.Map; public class InlineCollectionsTests extends AbstractTest { public void testListCreation2() { assertTrue(test("[\"test\"]") instanceof List); } public void testListCreation3() { assertTrue(test("[66]") instanceof List); } public void testListCreation4() { List ar = (List) test("[ 66 , \"test\" ]"); assertEquals(2, ar.size()); assertEquals(66, ar.get(0)); assertEquals("test", ar.get(1)); } public void testListCreationWithCall() { assertEquals(1, test("[\"apple\"].size()")); } public void testArrayCreationWithLength() { assertEquals(2, test("Array.getLength({'foo', 'bar'})")); } public void testEmptyList() { assertTrue(test("[]") instanceof List); } public void testEmptyArray() { assertTrue(((Object[]) test("{}")).length == 0); } public void testEmptyArray2() { assertTrue(((Object[]) test("{ }")).length == 0); } public void testArrayCreation() { assertEquals(0, test("arrayTest = {{1, 2, 3}, {2, 1, 0}}; arrayTest[1][2]")); } public void testMapCreation() { assertEquals("sarah", test("map = ['mike':'sarah','tom':'jacquelin']; map['mike']")); } public void testMapCreation2() { assertEquals("sarah", test("map = ['mike' :'sarah' ,'tom' :'jacquelin' ]; map['mike']")); } public void testMapCreation3() { assertEquals("foo", test("map = [1 : 'foo']; map[1]")); } public void testSizeOnInlineArray() { assertEquals(3, test("{1,2,3}.size()")); } public void testSimpleListCreation() { test("['foo', 'bar', 'foobar', 'FOOBAR']"); } public void testArrayCoercion() { assertEquals("gonk", test("funMethod( {'gonk', 'foo'} )")); } public void testArrayCoercion2() { assertEquals(10, test("sum({2,2,2,2,2})")); } public void testCompiledMapStructures() { executeExpression(compileExpression("['foo':'bar'] contains 'foo'"), null, (Map) null, Boolean.class); } public void testSubListInMap() { assertEquals("pear", test("map = ['test' : 'poo', 'foo' : [c, 'pear']]; map['foo'][1]")); } public void testForEach2() { assertEquals(6, test("total = 0; a = {1,2,3}; foreach(item : a) { total += item }; total")); } public void testForEach3() { assertEquals(true, test("a = {1,2,3}; foreach (i : a) { if (i == 1) { return true; } }")); } public void testForEach4() { assertEquals("OneTwoThreeFour", test("a = {1,2,3,4}; builder = ''; foreach (i : a) {" + " if (i == 1) { builder += 'One' } else if (i == 2) { builder += 'Two' } " + "else if (i == 3) { builder += 'Three' } else { builder += 'Four' }" + "}; builder;")); } public void testInlineCollectionNestedObjectCreation() { Map m = (Map) test("['Person.age' : [1, 2, 3, 4], 'Person.rating' : ['High', 'Low']," + " 'Person.something' : (new String('foo').toUpperCase())]"); assertEquals("FOO", m.get("Person.something")); } public void testInlineCollectionNestedObjectCreation1() { Map m = (Map) test("[new String('foo') : new String('bar')]"); assertEquals("bar", m.get("foo")); } public void testMVEL179() { assertTrue((Boolean) MVEL.eval("(($ in [2,4,8,16,32] if $ < 10) != empty)")); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/IntegrationTests.java0000644000175000017500000000413311236144601026145 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import org.mvel2.integration.PropertyHandler; import org.mvel2.integration.PropertyHandlerFactory; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.OptimizerFactory; public class IntegrationTests extends AbstractTest { class NullPropertyHandler implements PropertyHandler { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { return null; } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { return null; } } class MyClass { public String getWhatever() { return "foo"; } } class MySubClass extends MyClass { } interface MyInterface { } class MyInterfacedClass implements MyInterface { } class MyInterfacedSubClass extends MyInterfacedClass { } @Override protected void setUp() throws Exception { super.setUp(); MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE); PropertyHandlerFactory.registerPropertyHandler(MyClass.class, new NullPropertyHandler()); PropertyHandlerFactory.registerPropertyHandler(MyInterface.class, new NullPropertyHandler()); } @Override protected void tearDown() throws Exception { super.tearDown(); MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = false; PropertyHandlerFactory.unregisterPropertyHandler(MyClass.class); PropertyHandlerFactory.unregisterPropertyHandler(MyInterface.class); } public void test1() { // handler for subclass is not found, but its superclass handler is registered // why didn't use its superclass handler? assertEquals(null, MVEL.eval("whatever", new MySubClass())); } public void test2() { // "NullPointerException" fired assertEquals(null, MVEL.eval("whatever", new MyInterfacedSubClass())); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/ProtoTests.java0000644000175000017500000000474011260130011024754 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import junit.framework.TestCase; import org.mvel2.MVEL; import org.mvel2.ast.Proto; import org.mvel2.compiler.AbstractParser; import java.util.HashMap; public class ProtoTests extends TestCase { boolean run; public ProtoTests() { super(); run = AbstractParser.OPERATORS.containsKey("proto"); } public void testBasicProtoConstruct() { if (!run) return; assertTrue( MVEL.eval("proto Person { int age; String name; }; new Person();", new HashMap()) instanceof Proto.ProtoInstance); } public void testProtoFieldAccess() { if (!run) return; Object o = MVEL.eval("proto Person { int age = 5; String name; }; (p = new Person()).age", new HashMap()); assertEquals(5, o); } public void testProtoWithFunction() { if (!run) return; Object o = MVEL.eval("proto Person { " + " int age = 2; " + " def multAge() { " + " age * 10 " + " }; " + " };" + " p = new Person(); " + " p.multAge();", new HashMap()); assertEquals(20, o); } public void testProtoWithFunction2() { if (!run) return; String ex = "proto Adder {" + "int count = 0;" + "def accumulate() {" + "if (count < 10) {" + "System.out.println('counting:' + count);" + "count++;" + "accumulate();" + "}" + "}" + "};" + "adder = new Adder();" + "adder.accumulate();" + "adder.count;"; Object o = MVEL.eval(ex, new HashMap()); assertEquals(10, o); } public void testProtoWithOtherProtoRef() { if (!run) return; String ex = "proto Parent { Child child = new Child(); }; proto Child { Parent parent; }; " + "Parent parent = new Parent(); if (parent.child.parent == null) { 'YEP' } else { 'NOPE' }"; Object o = MVEL.eval(ex, new HashMap()); assertEquals("YEP", o); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/MutationsTests.java0000644000175000017500000001054011172704121025642 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import static org.mvel2.MVEL.compileExpression; import static org.mvel2.MVEL.executeExpression; import org.mvel2.ParserContext; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.tests.core.res.Foo; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import java.util.List; public class MutationsTests extends AbstractTest { public void testDeepAssignment() { Map map = createTestMap(); assertEquals("crap", testCompiledSimple("foo.bar.assignTest = 'crap'", map)); assertEquals("crap", testCompiledSimple("foo.bar.assignTest", map)); } public void testDeepAssignment2() { Map map = createTestMap(); ExpressionCompiler compiler = new ExpressionCompiler("foo.bar.age = 21"); ParserContext ctx = new ParserContext(); ctx.addInput("foo", Foo.class); ctx.setStrongTyping(true); CompiledExpression ce = compiler.compile(ctx); executeExpression(ce, map); assertEquals(((Foo) map.get("foo")).getBar().getAge(), 21); } public void testComplexExpression() { assertEquals("bar", test("a = 'foo'; b = 'bar'; c = 'jim'; list = {a,b,c}; list[1]")); } public void testAssignment() { assertEquals(true, test("populate(); blahfoo = 'sarah'; blahfoo == 'sarah'")); } public void testAssignment2() { assertEquals("sarah", test("populate(); blahfoo = barfoo")); } public void testAssignment3() { assertEquals(java.lang.Integer.class, test("blah = 5").getClass()); } public void testAssignment4() { assertEquals(102, test("a = 100 + 1 + 1")); } public void testAssignment6() { assertEquals("blip", test("array[zero] = array[zero+1]; array[zero]")); } public void testConstructor() { assertEquals("foo", test("a = 'foobar'; new String(a.toCharArray(), 0, 3)")); } public void testStaticVarAssignment() { assertEquals("1", test("String mikeBrock = 1; mikeBrock")); } public void testFunctionPointer() { assertEquals(2.0, test("squareRoot = java.lang.Math.sqrt; squareRoot(4)")); } public void testFunctionPointerAsParam() { assertEquals("2.0", test("squareRoot = Math.sqrt; new String(String.valueOf(squareRoot(4)));")); } public void testFunctionPointerInAssignment() { assertEquals(5.0, test("squareRoot = Math.sqrt; i = squareRoot(25); return i;")); } public void testIncrementOperator() { assertEquals(2, test("x = 1; x++; x")); } public void testPreIncrementOperator() { assertEquals(2, test("x = 1; ++x")); } public void testDecrementOperator() { assertEquals(1, test("x = 2; x--; x")); } public void testPreDecrementOperator() { assertEquals(1, test("x = 2; --x")); } public void testQualifiedStaticTyping() { Object val = 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; "); assertEquals(new BigDecimal(20), val); } public void testUnQualifiedStaticTyping() { CompiledExpression ce = (CompiledExpression) compileExpression("import java.math.BigDecimal; BigDecimal a = new BigDecimal( 10.0 ); BigDecimal b = new BigDecimal( 10.0 ); BigDecimal c = a + b; return c; "); assertEquals(new BigDecimal(20), testCompiledSimple("import java.math.BigDecimal; BigDecimal a = new BigDecimal( 10.0 ); BigDecimal b = new BigDecimal( 10.0 ); BigDecimal c = a + b; return c; ", new HashMap())); } public void testSubExpressionIndexer() { assertEquals("bar", test("xx = new java.util.HashMap(); xx.put('foo', 'bar'); prop = 'foo'; xx[prop];")); } public void testAssignListToBean() { OptimizerFactory.setDefaultOptimizer("reflective"); MockClass mock = new MockClass(); executeExpression(compileExpression("this.values = [0, 1, 2, 3, 4]"), mock); assertEquals(5, mock.getValues().size()); } public static class MockClass { List values; public List getValues() { return values; } public void setValues(List values) { this.values = values; } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/PropertyAccessTests.java0000644000175000017500000002435411325411717026643 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import static org.mvel2.MVEL.compileExpression; import static org.mvel2.MVEL.executeExpression; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.integration.PropertyHandler; import org.mvel2.integration.PropertyHandlerFactory; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.tests.core.res.Base; import org.mvel2.tests.core.res.Cake; import org.mvel2.tests.core.res.Foo; import java.io.Serializable; import java.util.*; public class PropertyAccessTests extends AbstractTest { public void testSingleProperty() { assertEquals(false, test("fun")); } public void testMethodOnValue() { assertEquals("DOG", test("foo.bar.name.toUpperCase()")); } public void testMethodOnValue2() { assertEquals("DOG", test("foo. bar. name.toUpperCase()")); } public void testSimpleProperty() { assertEquals("dog", test("foo.bar.name")); } public void testSimpleProperty2() { assertEquals("cat", test("DATA")); } public void testPropertyViaDerivedClass() { assertEquals("cat", test("derived.data")); } public void testThroughInterface() { assertEquals("FOOBAR!", test("testImpl.name")); } public void testThroughInterface2() { assertEquals(true, test("testImpl.foo")); } public void testMapAccessWithMethodCall() { assertEquals("happyBar", test("funMap['foo'].happy()")); } public void testUninitializedInt() { assertEquals(0, test("sarahl")); } public void testMethodAccess() { assertEquals("happyBar", test("foo.happy()")); } public void testMethodAccess2() { assertEquals("FUBAR", test("foo.toUC( 'fubar' )")); } public void testMethodAccess3() { assertEquals(true, test("equalityCheck(c, 'cat')")); } public void testMethodAccess4() { assertEquals(null, test("readBack(null)")); } public void testMethodAccess5() { assertEquals("nulltest", test("appendTwoStrings(null, 'test')")); } public void testMethodAccess6() { assertEquals(true, test(" equalityCheck( c \n , \n 'cat' ) ")); } public void testLiteralPassThrough() { assertEquals(true, test("true")); } public void testLiteralPassThrough2() { assertEquals(false, test("false")); } public void testLiteralPassThrough3() { assertEquals(null, test("null")); } public void testLiteralReduction1() { assertEquals("foo", test("null or 'foo'")); } public void testStrAppend() { assertEquals("foobarcar", test("'foo' + 'bar' + 'car'")); } public void testStrAppend2() { assertEquals("foobarcar1", test("'foobar' + 'car' + 1")); } public void testMapAccess() { assertEquals("dog", test("funMap['foo'].bar.name")); } public void testMapAccess2() { assertEquals("dog", test("funMap.foo.bar.name")); } public void testStaticMethodFromLiteral() { assertEquals(String.class.getName(), test("String.valueOf(Class.forName('java.lang.String').getName())")); } public void testObjectInstantiation() { test("new java.lang.String('foobie')"); } public void testObjectInstantiationWithMethodCall() { assertEquals("FOOBIE", test("new String('foobie') . toUpperCase()")); } public void testObjectInstantiation2() { test("new String() is String"); } public void testObjectInstantiation3() { test("new java.text.SimpleDateFormat('yyyy').format(new java.util.Date(System.currentTimeMillis()))"); } public void testThisReference() { assertEquals(true, test("this") instanceof Base); } public void testThisReference2() { assertEquals(true, test("this.funMap") instanceof Map); } public void testThisReferenceInMethodCall() { assertEquals(101, test("Integer.parseInt(this.number)")); } public void testThisReferenceInConstructor() { assertEquals("101", test("new String(this.number)")); } public void testStringEscaping() { assertEquals("\"Mike Brock\"", test("\"\\\"Mike Brock\\\"\"")); } public void testStringEscaping2() { assertEquals("MVEL's Parser is Fast", test("'MVEL\\'s Parser is Fast'")); } public void testCompiledMethodCall() { assertEquals(String.class, executeExpression(compileExpression("c.getClass()"), new Base(), createTestMap())); } public void testStaticNamespaceCall() { assertEquals(java.util.ArrayList.class, test("java.util.ArrayList")); } public void testStaticNamespaceClassWithMethod() { assertEquals("FooBar", test("java.lang.String.valueOf('FooBar')")); } public void testStaticNamespaceClassWithField() { assertEquals(Integer.MAX_VALUE, test("java.lang.Integer.MAX_VALUE")); } public void testStaticNamespaceClassWithField2() { assertEquals(Integer.MAX_VALUE, test("Integer.MAX_VALUE")); } public void testStaticFieldAsMethodParm() { assertEquals(String.valueOf(Integer.MAX_VALUE), test("String.valueOf(Integer.MAX_VALUE)")); } public void testMagicArraySize() { assertEquals(5, test("stringArray.size()")); } public void testMagicArraySize2() { assertEquals(5, test("intArray.size()")); } public void testObjectCreation() { assertEquals(6, test("new Integer( 6 )")); } public void testCompileTimeLiteralReduction() { assertEquals(1000, test("10 * 100")); } public void testStringAsCollection() { assertEquals('o', test("abc = 'foo'; abc[1]")); } public void testInterfaceResolution() { Serializable ex = compileExpression("foo.collectionTest.size()"); Map map = createTestMap(); Foo foo = (Foo) map.get("foo"); foo.setCollectionTest(new HashSet()); Object result1 = executeExpression(ex, foo, map); foo.setCollectionTest(new ArrayList()); Object result2 = executeExpression(ex, foo, map); assertEquals(result1, result2); } public void testReflectionCache() { assertEquals("happyBar", test("foo.happy(); foo.bar.happy()")); } public void testDynamicDeop() { Serializable s = compileExpression("name"); assertEquals("dog", executeExpression(s, new Foo())); assertEquals("dog", executeExpression(s, new Foo().getBar())); } public void testVirtProperty() { Map testMap = new HashMap(); testMap.put("test", "foo"); Map vars = new HashMap(); vars.put("mp", testMap); assertEquals("bar", executeExpression(compileExpression("mp.test = 'bar'; mp.test"), vars)); } public void testBindingCoercion() { List list = new LinkedList(); list.add("Apple"); list.add("Peach"); list.add("Icing"); Cake cake = new Cake(); MVEL.setProperty(cake, "ingredients", list); assertTrue(cake.getIngredients().contains("Apple")); assertTrue(cake.getIngredients().contains("Peach")); assertTrue(cake.getIngredients().contains("Icing")); } public void testMVELCompilerBoth() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; PropertyHandlerFactory.registerPropertyHandler(DynaBean.class, new DynaBeanPropertyHandler()); TestBean bean = new TestBean("value1"); Map vars = new LinkedHashMap(); vars.put("attr", bean); ParserContext parserContext = new ParserContext(); Object compiled = MVEL.compileExpression("attr.value", parserContext); assertEquals("value1", MVEL.executeExpression(compiled, null, vars)); DynaBean dyna = new LazyDynaBean(); dyna.set("value", "value2"); vars.put("attr", dyna); assertEquals("value2", MVEL.executeExpression(compiled, null, vars)); } public void testMVELCompilerBoth2() { PropertyHandlerFactory.registerPropertyHandler(DynaBean.class, new DynaBeanPropertyHandler()); Map vars = new LinkedHashMap(); ParserContext parserContext = new ParserContext(); Object compiled = MVEL.compileExpression("attr.value", parserContext); DynaBean dyna = new LazyDynaBean(); dyna.set("value", "value2"); vars.put("attr", dyna); assertEquals("value2", MVEL.executeExpression(compiled, null, vars)); TestBean bean = new TestBean("value1"); vars.put("attr", bean); assertEquals("value1", MVEL.executeExpression(compiled, null, vars)); } public static class TestBean { private String _value; public TestBean(String value) { _value = value; } public String getValue() { return _value; } public void setValue(String value) { _value = value; } } public static interface DynaBean { public void set(String key, Object value); public Object get(String key); } public static class LazyDynaBean implements DynaBean { private Map values = new HashMap(); public void set(String key, Object value) { values.put(key, value); } public Object get(String key) { return values.get(key); } } private static class DynaBeanPropertyHandler implements PropertyHandler { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { return ((DynaBean) contextObj).get(name); } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { ((DynaBean) contextObj).set(name, value); return value; } } public void testNullSafe() { Map> ctx = new HashMap>(); Map tmp = new HashMap(); // tmp.put("latitude", 0.5f); ctx.put("SessionSetupRequest", tmp); System.out.println("Result = " + MVEL.getProperty("SessionSetupRequest.?latitude", ctx)); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/ControlFlowTests.java0000644000175000017500000001163111215162052026130 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import org.mvel2.ParserContext; import org.mvel2.tests.core.res.Base; import org.mvel2.tests.core.res.Foo; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.io.Serializable; public class ControlFlowTests extends AbstractTest { public void testSimpleIfStatement() { test("if (true) { System.out.println(\"test!\") } \n"); } public void testAnd() { assertEquals(true, test("c != null && foo.bar.name == 'dog' && foo.bar.woof")); } public void testAnd2() { assertEquals(true, test("c!=null&&foo.bar.name=='dog'&&foo.bar.woof")); } public void testComplexAnd() { assertEquals(true, test("(pi * hour) > 0 && foo.happy() == 'happyBar'")); } public void testShortPathExpression() { assertEquals(null, MVEL.eval("3 > 4 && foo.toUC('test'); foo.register", new Base(), createTestMap())); } public void testShortPathExpression2() { assertEquals(true, test("4 > 3 || foo.toUC('test')")); } public void testShortPathExpression4() { assertEquals(true, test("4>3||foo.toUC('test')")); } public void testOr() { assertEquals(true, test("fun || true")); } public void testOrOperator() { assertEquals(true, test("true||true")); } public void testOrOperator2() { assertEquals(true, test("2 > 3 || 3 > 2")); } public void testOrOperator3() { assertEquals(true, test("pi > 5 || pi > 6 || pi > 3")); } public void testShortPathExpression3() { assertEquals(false, test("defnull != null && defnull.length() > 0")); } public void testMultiStatement() { assertEquals(true, test("populate(); barfoo == 'sarah'")); } public void testTernary() { assertEquals("foobie", test("zero==0?'foobie':zero")); } public void testTernary2() { assertEquals("blimpie", test("zero==1?'foobie':'blimpie'")); } public void testTernary3() { assertEquals("foobiebarbie", test("zero==1?'foobie':'foobie'+'barbie'")); } public void testTernary5() { assertEquals("skat!", test("isdef someWierdVar ? 'squid' : 'skat!';")); } public void testEmptyIf() { assertEquals(5, test("a = 5; if (a == 5) { }; return a;")); } public void testEmptyIf2() { assertEquals(5, test("a=5;if(a==5){};return a;")); } public void testIf() { assertEquals(10, test("if (5 > 4) { return 10; } else { return 5; }")); } public void testIf2() { assertEquals(10, test("if (5 < 4) { return 5; } else { return 10; }")); } public void testIf3() { assertEquals(10, test("if(5<4){return 5;}else{return 10;}")); } public void testIfAndElse() { assertEquals(true, test("if (false) { return false; } else { return true; }")); } public void testIfAndElseif() { assertEquals(true, test("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;")); } public void testIfAndElseif2() { assertEquals(true, MVEL.eval("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;")); } public void testIfAndElseIfCondensedGrammar() { assertEquals("Foo", test("if (false) return 'Bar'; else return 'Foo';")); } public void testTernary4() { assertEquals("", test("true ? '' : ''")); } public void testPrecedenceOrder1() { String ex = "50 > 60 && 20 < 10 || 100 > 90"; System.out.println("Expression: " + ex); assertTrue((Boolean) MVEL.eval(ex)); } public void testDoLoop() { assertEquals(10, test("i = 0; do { i++ } while (i != 10); i")); } public void testDoLoop2() { assertEquals(50, test("i=100;do{i--}until(i==50); i")); } public void testForLoop() { assertEquals("012345", test("String str = ''; for(i=0;i<6;i++) { str += i }; str")); } public void testForLoop2() { assertEquals("012345", MVEL.eval("String str='';for(i=0;i<6;i++){str+=i};str", new HashMap())); } public void testUntilLoop() { assertEquals("012345", test("String str = ''; int i = 0; until (i == 6) { str += i++; }; str")); } public void testQualifiedForLoop() { ParserContext pCtx = new ParserContext(); pCtx.setStrongTyping(true); pCtx.addImport(Foo.class); pCtx.addInput("l", ArrayList.class, new Class[] { Foo.class }); List l = new ArrayList(); l.add(new Foo()); l.add(new Foo()); l.add(new Foo()); Map vars = new HashMap(); vars.put("l", l); Serializable s = MVEL.compileExpression("String s = ''; for (Foo f : l) { s += f.name }; s", pCtx); String r = (String) MVEL.executeExpression(s, vars); assertEquals("dogdogdog", r); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/PropertyHandlerTests.java0000644000175000017500000003323611172704121027010 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import junit.framework.TestCase; import org.mvel2.MVEL; import org.mvel2.PropertyAccessor; import org.mvel2.asm.MethodVisitor; import static org.mvel2.asm.Opcodes.*; import org.mvel2.integration.*; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.optimizers.impl.asm.ProducesBytecode; import org.mvel2.tests.core.res.Bar; import org.mvel2.tests.core.res.Base; import org.mvel2.tests.core.res.Foo; import java.io.Serializable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PropertyHandlerTests extends TestCase { Base base = new Base(); public class TestPropertyHandler implements PropertyHandler, ProducesBytecode { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { assertNotNull(contextObj); assertEquals("0", name); assertTrue(contextObj instanceof List); return "gotcalled"; } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { assertNotNull(contextObj); assertEquals("0", name); assertTrue(contextObj instanceof List); ((List) contextObj).set(0, "set"); return null; } public void produceBytecodeGet(MethodVisitor mv, String propertyName, VariableResolverFactory factory) { mv.visitLdcInsn("gotcalled"); } public void produceBytecodePut(MethodVisitor mv, String propertyName, VariableResolverFactory factory) { mv.visitTypeInsn(CHECKCAST, "java/util/List"); mv.visitInsn(ICONST_0); mv.visitLdcInsn("set"); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "set", "(ILjava/lang/Object;)Ljava/lang/Object;"); mv.visitInsn(POP); mv.visitInsn(ACONST_NULL); } } @Override protected void setUp() throws Exception { PropertyHandlerFactory.registerPropertyHandler(List.class, new TestPropertyHandler()); } @Override protected void tearDown() throws Exception { GlobalListenerFactory.disposeAll(); PropertyHandlerFactory.disposeAll(); } public void testListPropertyHandler() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; assertEquals("gotcalled", PropertyAccessor.get("list[0]", base)); PropertyAccessor.set(base, "list[0]", "hey you"); assertEquals("set", base.list.get(0)); MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = false; } public void testListPropertyHandler2() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; Serializable s = MVEL.compileSetExpression("list[0]"); Base b; MVEL.executeSetExpression(s, new Base(), "hey you"); MVEL.executeSetExpression(s, b = new Base(), "hey you"); assertEquals("set", b.list.get(0)); } public void testListPropertyHandler3() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; OptimizerFactory.setDefaultOptimizer("ASM"); Serializable s = MVEL.compileSetExpression("list[0]"); Base b; MVEL.executeSetExpression(s, new Base(), "hey you"); MVEL.executeSetExpression(s, b = new Base(), "hey you"); assertEquals("set", b.list.get(0)); } public void testListPropertyHandler4() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; OptimizerFactory.setDefaultOptimizer("ASM"); final String[] res = new String[1]; GlobalListenerFactory.registerGetListener(new Listener() { public void onEvent(Object context, String contextName, VariableResolverFactory variableFactory, Object value) { System.out.println("Listener Fired:" + contextName); res[0] = contextName; } }); Serializable s = MVEL.compileSetExpression("list[0]"); Base b; MVEL.executeSetExpression(s, new Base(), "hey you"); res[0] = null; MVEL.executeSetExpression(s, b = new Base(), "hey you"); assertEquals("set", b.list.get(0)); assertEquals("list", res[0]); } public void testNullPropertyHandler() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; OptimizerFactory.setDefaultOptimizer("ASM"); PropertyHandlerFactory.setNullPropertyHandler(new PropertyHandler() { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { return "NULL"; } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { return "NULL"; } }); Foo foo = new Foo(); Bar bar = foo.getBar(); foo.setBar(null); Map map = new HashMap(); map.put("foo", foo); Serializable s = MVEL.compileExpression("foo.bar"); assertEquals("NULL", MVEL.executeExpression(s, map)); assertEquals("NULL", MVEL.executeExpression(s, map)); foo.setBar(bar); assertEquals(bar, MVEL.executeExpression(s, map)); } public void testNullPropertyHandler2() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; OptimizerFactory.setDefaultOptimizer("reflective"); PropertyHandlerFactory.setNullPropertyHandler(new PropertyHandler() { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { return "NULL"; } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { return "NULL"; } }); Foo foo = new Foo(); Bar bar = foo.getBar(); foo.setBar(null); Map map = new HashMap(); map.put("foo", foo); Serializable s = MVEL.compileExpression("foo.bar"); assertEquals("NULL", MVEL.executeExpression(s, map)); assertEquals("NULL", MVEL.executeExpression(s, map)); foo.setBar(bar); assertEquals(bar, MVEL.executeExpression(s, map)); } public void testMapPropertyHandler() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; PropertyHandlerFactory.registerPropertyHandler(Map.class, new PropertyHandler() { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { assertNotNull(contextObj); assertEquals("'key'", name); assertTrue(contextObj instanceof Map); return "gotcalled"; } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { assertNotNull(contextObj); assertEquals("'key'", name); assertTrue(contextObj instanceof Map); ((Map) contextObj).put("key", "set"); return null; } }); assertEquals("gotcalled", PropertyAccessor.get("funMap['key']", base)); PropertyAccessor.set(base, "funMap['key']", "hey you"); assertEquals("set", base.funMap.get("key")); MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = false; } public void testArrayPropertyHandler() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; PropertyHandlerFactory.registerPropertyHandler(Array.class, new PropertyHandler() { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { assertNotNull(contextObj); assertEquals("0", name); assertTrue(contextObj.getClass().isArray()); return "gotcalled"; } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { assertNotNull(contextObj); assertEquals("0", name); assertTrue(contextObj.getClass().isArray()); Array.set(contextObj, 0, "set"); return null; } }); assertEquals("gotcalled", PropertyAccessor.get("stringArray[0]", base)); PropertyAccessor.set(base, "stringArray[0]", "hey you"); assertEquals("set", base.stringArray[0]); MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = false; } public void testSetListListener() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; class MyListener implements Listener { public int counter; public void onEvent(Object context, String contextName, VariableResolverFactory variableFactory, Object value) { counter++; } } class MyBean { private List someList; public List getSomeList() { return someList; } } MyListener listener = new MyListener(); GlobalListenerFactory.registerGetListener(listener); MVEL.getProperty("someList", new MyBean()); MVEL.getProperty("someList", new MyBean()); assertEquals(2, listener.counter); } public void testListener() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; class MyListener implements Listener { public int count; public void onEvent(Object context, String contextName, VariableResolverFactory variableFactory, Object value) { count++; } } MyListener listener = new MyListener(); GlobalListenerFactory.registerGetListener(listener); PropertyHandlerFactory.setNullPropertyHandler(new PropertyHandler() { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { List someList = new ArrayList(); someList.add(new Foo()); return someList; } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { return null; } }); PropertyHandlerFactory.registerPropertyHandler(List.class, new PropertyHandler() { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { List list = (List) contextObj; int index = Integer.valueOf(name); while (index >= list.size()) { list.add(new Foo()); } return list.get(index); } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { return null; } }); Foo foo = new Foo(); final Serializable fooExpr0 = MVEL.compileSetExpression("collectionTest[0].name"); final Serializable fooExpr1 = MVEL.compileSetExpression("collectionTest[1].name"); MVEL.executeSetExpression(fooExpr0, foo, "John Galt"); MVEL.executeSetExpression(fooExpr1, foo, "The Joker"); assertEquals(2, listener.count); MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = false; } public class WorkObject { Map map = new HashMap(); public boolean hasFieldName(String name) { return map.containsKey(name); } public Object getFieldValue(String name) { return map.get(name); } public void setFieldValue(String name, Object value, boolean bool) { map.put(name, value); } } public class WebPropertyHandler implements PropertyHandler { public Object getProperty(String arg0, Object arg1, VariableResolverFactory arg2) { WorkObject wob = (WorkObject) arg1; if (wob.hasFieldName(arg0)) { return wob.getFieldValue(arg0); } else return null; } public Object setProperty(String arg0, Object arg1, VariableResolverFactory arg2, Object arg3) { WorkObject wob = (WorkObject) arg1; wob.setFieldValue(arg0, arg3, true); return arg3; } } public void testPropertyHandlerSetting() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; PropertyHandlerFactory.registerPropertyHandler(WorkObject.class, new WebPropertyHandler()); Map vars = new HashMap(); WorkObject wo = new WorkObject(); vars.put("wobj", wo); MVEL.setProperty(vars, "wobj.foo", "foobie"); assertEquals("foobie", wo.getFieldValue("foo")); } }mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/MVELThreadTest.java0000644000175000017500000000422411073524603025376 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import org.mvel2.optimizers.OptimizerFactory; import java.io.Serializable; public class MVELThreadTest { public static void main(String[] args) { MVELThreadTest threadTest = new MVELThreadTest(); threadTest.start(); } public void start() { //Create two of the same expressions final String expression = "firstname"; final String expression2 = "lastname"; //Create a bean to run expressions against final Bean bean = new Bean(); //Use reflection mode OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE); //Compile the expressions Serializable mvelExp1 = MVEL.compileExpression(expression); Serializable mvelExp2 = MVEL.compileExpression(expression2); //run the threads runThreads(bean, mvelExp1, mvelExp2); } public void runThreads(final Bean bean, final Serializable mvelExpr1, final Serializable mvelExpr2) { //Start 5 threads, each executing the specified MVEL expressions for (int i = 0; i < 5; i++) { Thread t = new Thread() { public void run() { testMvel(bean, mvelExpr1, mvelExpr2); } }; t.start(); } } //by synchronizing the testMvel method, the exception does not occur public void testMvel(Bean bean, Serializable mvelExpr1, Serializable mvelExpr2) { int iterations = 100; for (int i = 0; i < iterations; i++) { MVEL.executeExpression(mvelExpr1, bean); MVEL.executeExpression(mvelExpr2, bean); } } /** * Bean */ public static class Bean { private String firstname; private String lastname; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/CoreConfidenceTests.java0000644000175000017500000047434411371320442026546 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import junit.framework.TestCase; import org.mvel2.*; import org.mvel2.ast.ASTNode; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.integration.Interceptor; import org.mvel2.integration.PropertyHandlerFactory; import org.mvel2.integration.ResolverTools; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.ClassImportResolverFactory; import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.integration.impl.StaticMethodImportResolverFactory; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.tests.core.res.*; import org.mvel2.tests.core.res.res2.ClassProvider; import org.mvel2.tests.core.res.res2.Outer; import org.mvel2.tests.core.res.res2.PublicClass; import org.mvel2.util.Make; import org.mvel2.util.MethodStub; import org.mvel2.util.ReflectionUtil; import java.awt.*; import java.io.BufferedReader; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import static java.util.Collections.unmodifiableCollection; import static org.mvel2.MVEL.*; @SuppressWarnings({"ALL"}) public class CoreConfidenceTests extends AbstractTest { public void testWhileUsingImports() { Map imports = new HashMap(); imports.put("ArrayList", java.util.ArrayList.class); imports.put("List", java.util.List.class); ParserContext context = new ParserContext(imports, null, "testfile"); ExpressionCompiler compiler = new ExpressionCompiler("List list = new ArrayList(); return (list == empty)"); assertTrue((Boolean) executeExpression(compiler.compile(context), new DefaultLocalVariableResolverFactory())); } public void testBooleanModeOnly2() { assertEquals(false, (Object) DataConversion.convert(test("BWAH"), Boolean.class)); } public void testBooleanModeOnly4() { assertEquals(true, test("hour == (hour + 0)")); } // interpreted public void testThisReferenceMapVirtualObjects() { Map map = new HashMap(); map.put("foo", "bar"); VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap()); factory.createVariable("this", map); assertEquals(true, eval("this.foo == 'bar'", map, factory)); } // compiled - reflective public void testThisReferenceMapVirtualObjects1() { // Create our root Map object Map map = new HashMap(); map.put("foo", "bar"); VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap()); factory.createVariable("this", map); OptimizerFactory.setDefaultOptimizer("reflective"); // Run test assertEquals(true, executeExpression(compileExpression("this.foo == 'bar'"), map, factory)); } // compiled - asm public void testThisReferenceMapVirtualObjects2() { // Create our root Map object Map map = new HashMap(); map.put("foo", "bar"); VariableResolverFactory factory = new MapVariableResolverFactory(new HashMap()); factory.createVariable("this", map); // I think we can all figure this one out. if (!Boolean.getBoolean("mvel2.disable.jit")) OptimizerFactory.setDefaultOptimizer("ASM"); // Run test assertEquals(true, executeExpression(compileExpression("this.foo == 'bar'"), map, factory)); } public void testEvalToBoolean() { assertEquals(true, (boolean) evalToBoolean("true ", "true")); assertEquals(true, (boolean) evalToBoolean("true ", "true")); } public void testImport() { assertEquals(HashMap.class, test("import java.util.HashMap; HashMap;")); } public void testImport2() { HashMap[] maps = (HashMap[]) MVEL.eval("import java.util.*; HashMap[] maps = new HashMap[10]; maps", new HashMap()); // HashMap[] maps = (HashMap[]) test("import java.util.*; HashMap[] maps = new HashMap[10]; maps"); assertEquals(10, maps.length); } public void testStaticImport() { assertEquals(2.0, test("import_static java.lang.Math.sqrt; sqrt(4)")); } /** * Start collections framework based compliance tests */ public void testCreationOfSet() { assertEquals("foo bar foo bar", test("set = new java.util.LinkedHashSet(); " + "set.add('foo');" + "set.add('bar');" + "output = '';" + "foreach (item : set) {" + "output = output + item + ' ';" + "} " + "foreach (item : set) {" + "output = output + item + ' ';" + "} " + "output = output.trim();" + "if (set.size() == 2) { return output; }")); } public void testCreationOfList() { assertEquals(5, test("l = new java.util.LinkedList(); l.add('fun'); l.add('happy'); l.add('fun'); l.add('slide');" + "l.add('crap'); poo = new java.util.ArrayList(l); poo.size();")); } public void testMapOperations() { assertEquals("poo5", test("l = new java.util.ArrayList(); l.add('plop'); l.add('poo'); m = new java.util.HashMap();" + "m.put('foo', l); m.put('cah', 'mah'); m.put('bar', 'foo'); m.put('sarah', 'mike');" + "m.put('edgar', 'poe'); if (m.edgar == 'poe') { return m.foo[1] + m.size(); }")); } public void testStackOperations() { assertEquals(10, test("stk = new java.util.Stack();" + "stk.push(5);" + "stk.push(5);" + "stk.pop() + stk.pop();")); } public void testSystemOutPrint() { test("a = 0;\r\nSystem.out.println('This is a test');"); } public void testVarInputs() { ParserContext pCtx = ParserContext.create(); MVEL.analysisCompile("test != foo && bo.addSomething(trouble) " + "&& 1 + 2 / 3 == 1; String bleh = foo; twa = bleh;", pCtx); assertEquals(4, pCtx.getInputs().size()); assertTrue(pCtx.getInputs().containsKey("test")); assertTrue(pCtx.getInputs().containsKey("foo")); assertTrue(pCtx.getInputs().containsKey("bo")); assertTrue(pCtx.getInputs().containsKey("trouble")); assertEquals(2, pCtx.getVariables().size()); assertTrue(pCtx.getVariables().containsKey("bleh")); assertTrue(pCtx.getVariables().containsKey("twa")); assertEquals(String.class, pCtx.getVarOrInputType("bleh")); } public void testVarInputs2() { ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;"); ParserContext ctx = new ParserContext(); compiler.compile(ctx); System.out.println(ctx.getVarOrInputType("bleh")); } public void testVarInputs3() { ExpressionCompiler compiler = new ExpressionCompiler("addresses['home'].street"); compiler.compile(); assertFalse(compiler.getParserContextState().getInputs().keySet().contains("home")); } public void testVarInputs4() { ExpressionCompiler compiler = new ExpressionCompiler("System.out.println( message );"); compiler.compile(); assertTrue(compiler.getParserContextState().getInputs().keySet().contains("message")); } public void testVarInputs5() { ParserContext pCtx = ParserContext.create().withInput("list", List.class); MVEL.analysisCompile("String nodeName = list[0];\nSystem.out.println(nodeName);nodeName = list[1];\nSystem.out.println(nodeName);", pCtx); assertEquals(1, pCtx.getInputs().size()); assertTrue(pCtx.getInputs().containsKey("list")); assertEquals(1, pCtx.getVariables().size()); assertTrue(pCtx.getVariables().containsKey("nodeName")); assertEquals(List.class, pCtx.getVarOrInputType("list")); assertEquals(String.class, pCtx.getVarOrInputType("nodeName")); } public void testAnalyzer() { ParserContext ctx = new ParserContext(); MVEL.compileExpression("order.id == 10", ctx); for (String input : ctx.getInputs().keySet()) { System.out.println("input>" + input); } assertEquals(1, ctx.getInputs().size()); assertTrue(ctx.getInputs().containsKey("order")); } public void testClassImportViaFactory() { MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap()); ClassImportResolverFactory classes = new ClassImportResolverFactory(); classes.addClass(HashMap.class); ResolverTools.appendFactory(mvf, classes); assertTrue(executeExpression(compileExpression("HashMap map = new HashMap()", classes.getImportedClasses()), mvf) instanceof HashMap); } public void testSataticClassImportViaFactory() { MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap()); ClassImportResolverFactory classes = new ClassImportResolverFactory(); classes.addClass(Person.class); ResolverTools.appendFactory(mvf, classes); assertEquals("tom", executeExpression(compileExpression("p = new Person('tom'); return p.name;", classes.getImportedClasses()), mvf)); } public void testSataticClassImportViaFactoryAndWithModification() { OptimizerFactory.setDefaultOptimizer("ASM"); MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap()); ClassImportResolverFactory classes = new ClassImportResolverFactory(); classes.addClass(Person.class); ResolverTools.appendFactory(mvf, classes); assertEquals(21, executeExpression( compileExpression("p = new Person('tom'); p.age = 20; " + "with( p ) { age = p.age + 1 }; return p.age;", classes.getImportedClasses()), mvf)); } public void testCheeseConstructor() { MapVariableResolverFactory mvf = new MapVariableResolverFactory(createTestMap()); ClassImportResolverFactory classes = new ClassImportResolverFactory(); classes.addClass(Cheese.class); ResolverTools.appendFactory(mvf, classes); assertTrue(executeExpression(compileExpression("cheese = new Cheese(\"cheddar\", 15);", classes.getImportedClasses()), mvf) instanceof Cheese); } public void testInterceptors() { Interceptor testInterceptor = new Interceptor() { public int doBefore(ASTNode node, VariableResolverFactory factory) { System.out.println("BEFORE Node: " + node.getName()); return 0; } public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) { System.out.println("AFTER Node: " + node.getName()); return 0; } }; Map interceptors = new HashMap(); interceptors.put("test", testInterceptor); executeExpression(compileExpression("@test System.out.println('MIDDLE');", null, interceptors)); } public void testExecuteCoercionTwice() { OptimizerFactory.setDefaultOptimizer("reflective"); Map vars = new HashMap(); vars.put("foo", new Foo()); vars.put("$value", new Long(5)); ExpressionCompiler compiler = new ExpressionCompiler("with (foo) { countTest = $value };"); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test.mv"); ctx.setDebugSymbols(true); CompiledExpression compiled = compiler.compile(ctx); executeExpression(compiled, null, vars); executeExpression(compiled, null, vars); } public void testExecuteCoercionTwice2() { OptimizerFactory.setDefaultOptimizer("ASM"); Map vars = new HashMap(); vars.put("foo", new Foo()); vars.put("$value", new Long(5)); ExpressionCompiler compiler = new ExpressionCompiler("with (foo) { countTest = $value };"); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test.mv"); ctx.setDebugSymbols(true); CompiledExpression compiled = compiler.compile(ctx); executeExpression(compiled, null, vars); executeExpression(compiled, null, vars); } public void testComments() { assertEquals(10, test("// This is a comment\n5 + 5")); } public void testComments2() { assertEquals(20, test("10 + 10; // This is a comment")); } public void testComments3() { assertEquals(30, test("/* This is a test of\r\n" + "MVEL's support for\r\n" + "multi-line comments\r\n" + "*/\r\n 15 + 15")); } public void testComments4() { assertEquals(((10 + 20) * 2) - 10, test("/** This is a fun test script **/\r\n" + "a = 10;\r\n" + "/**\r\n" + "* Here is a useful variable\r\n" + "*/\r\n" + "b = 20; // set b to '20'\r\n" + "return ((a + b) * 2) - 10;\r\n" + "// last comment\n")); } public void testComments5() { assertEquals("dog", test("foo./*Hey!*/name")); } public void testSubtractNoSpace1() { assertEquals(59, test("hour-1")); } public void testStrictTypingCompilation() { ExpressionCompiler compiler = new ExpressionCompiler("a.foo;\nb.foo;\n x = 5"); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); try { compiler.compile(ctx); } catch (CompileException e) { e.printStackTrace(); assertEquals(2, e.getErrors().size()); return; } assertTrue(false); } public void testStrictStaticMethodCall() { ExpressionCompiler compiler = new ExpressionCompiler("Bar.staticMethod()"); ParserContext ctx = new ParserContext(); ctx.addImport("Bar", Bar.class); ctx.setStrictTypeEnforcement(true); Serializable s = compiler.compile(ctx); assertEquals(1, executeExpression(s)); } public void testStrictTypingCompilation2() throws Exception { ParserContext ctx = new ParserContext(); //noinspection RedundantArrayCreation ctx.addImport("getRuntime", new MethodStub(Runtime.class.getMethod("getRuntime", new Class[]{}))); ctx.setStrictTypeEnforcement(true); ExpressionCompiler compiler = new ExpressionCompiler("getRuntime()"); StaticMethodImportResolverFactory si = new StaticMethodImportResolverFactory(ctx); Serializable expression = compiler.compile(ctx); serializationTest(expression); assertTrue(executeExpression(expression, si) instanceof Runtime); } public void testStrictTypingCompilation3() throws NoSuchMethodException { ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ExpressionCompiler compiler = new ExpressionCompiler("message='Hello';b=7;\nSystem.out.println(message + ';' + b);\n" + "System.out.println(message + ';' + b); b"); assertEquals(7, executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory())); } public void testStrictTypingCompilation4() throws NoSuchMethodException { ParserContext ctx = new ParserContext(); ctx.addImport(Foo.class); ctx.setStrictTypeEnforcement(true); ExpressionCompiler compiler = new ExpressionCompiler("x_a = new Foo()"); compiler.compile(ctx); assertEquals(Foo.class, ctx.getVariables().get("x_a")); } public void testStrictStrongTypingCompilationErrors1() throws Exception { ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setStrongTyping(true); ctx.addImport(Foo.class); ctx.addInput("$bar", Bar.class); try { ExpressionCompiler compiler = new ExpressionCompiler("System.out.println( $ba );"); compiler.compile(ctx); fail("This should not compile"); } catch (Exception e) { } } public void testStrictStrongTypingCompilationErrors2() throws Exception { ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setStrongTyping(true); ctx.addImport(Foo.class); ctx.addInput("$bar", Bar.class); try { MVEL.compileExpression("x_a = new Foo( $ba ); x_a.equals($ba);", ctx); fail("This should not compile"); } catch (Exception e) { e.printStackTrace(); } } public void testDetermineRequiredInputsInConstructor() throws Exception { ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(false); ctx.setStrongTyping(false); ctx.addImport(Foo.class); ExpressionCompiler compiler = new ExpressionCompiler("new Foo( $bar, $bar.age );"); Serializable compiled = compiler.compile(ctx); Set requiredInputs = compiler.getParserContextState().getInputs().keySet(); assertEquals(1, requiredInputs.size()); assertTrue(requiredInputs.contains("$bar")); } public void testProvidedExternalTypes() { ExpressionCompiler compiler = new ExpressionCompiler("foo.bar"); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.addInput("foo", Foo.class); compiler.compile(ctx); } public void testEqualityRegression() { ExpressionCompiler compiler = new ExpressionCompiler("price == (new Integer( 5 ) + 5 ) "); compiler.compile(); } public void testEvaluationRegression() { ExpressionCompiler compiler = new ExpressionCompiler("(p.age * 2)"); compiler.compile(); assertTrue(compiler.getParserContextState().getInputs().containsKey("p")); } public void testAssignmentRegression() { ExpressionCompiler compiler = new ExpressionCompiler("total = total + $cheese.price"); compiler.compile(); } public void testTypeRegression() { ExpressionCompiler compiler = new ExpressionCompiler("total = 0"); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); compiler.compile(ctx); assertEquals(Integer.class, compiler.getParserContextState().getVarOrInputType("total")); } public void testMapPropertyCreateCondensed() { assertEquals("foo", test("map = new java.util.HashMap(); map['test'] = 'foo'; map['test'];")); } public void testClassLiteral() { assertEquals(String.class, test("java.lang.String")); } public void testDeepMethod() { assertEquals(false, test("foo.bar.testList.add(new String()); foo.bar.testList == empty")); } public void testArrayAccessorAssign() { assertEquals("foo", test("a = {'f00', 'bar'}; a[0] = 'foo'; a[0]")); } public void testListAccessorAssign() { assertEquals("bar", test("a = new java.util.ArrayList(); a.add('foo'); a.add('BAR'); a[1] = 'bar'; a[1]")); } public void testBracketInString() { test("System.out.println('1)your guess was:');"); } public void testNesting() { assertEquals("foo", test("new String(new String(new String(\"foo\")));")); } public void testTypeCast() { assertEquals("10", test("(String) 10")); } public void testTypeCast2() { assertEquals(0, test("map = new java.util.HashMap(); map.put('doggie', new java.util.ArrayList());" + " ((java.util.ArrayList) map['doggie']).size()")); } public void testTypeCast3() { Map map = new HashMap(); map.put("foo", new Foo()); ParserContext pCtx = new ParserContext(); pCtx.setStrongTyping(true); pCtx.addInput("foo", Foo.class); Serializable s = MVEL.compileExpression("((org.mvel2.tests.core.res.Bar) foo.getBar()).name != null", pCtx); assertEquals(true, executeExpression(s, map)); assertEquals(1, pCtx.getInputs().size()); assertEquals(true, pCtx.getInputs().containsKey("foo")); } public void testMapAccessSemantics() { Map outermap = new HashMap(); Map innermap = new HashMap(); innermap.put("test", "foo"); outermap.put("innermap", innermap); assertEquals("foo", testCompiledSimple("innermap['test']", outermap, null)); } public void testMapBindingSemantics() { Map outermap = new HashMap(); Map innermap = new HashMap(); innermap.put("test", "foo"); outermap.put("innermap", innermap); setProperty(outermap, "innermap['test']", "bar"); assertEquals("bar", testCompiledSimple("innermap['test']", outermap, null)); } public void testMapNestedInsideList() { ParserContext ctx = new ParserContext(); ctx.addImport("User", User.class); ExpressionCompiler compiler = new ExpressionCompiler("users = [ 'darth' : new User('Darth', 'Vadar')," + "\n'bobba' : new User('Bobba', 'Feta') ]; [ users.get('darth'), users.get('bobba') ]"); // Serializable s = compiler.compile(ctx); List list = (List) executeExpression(compiler.compile(ctx), new HashMap()); User user = (User) list.get(0); assertEquals("Darth", user.getFirstName()); user = (User) list.get(1); assertEquals("Bobba", user.getFirstName()); compiler = new ExpressionCompiler("users = [ 'darth' : new User('Darth', 'Vadar')," + "\n'bobba' : new User('Bobba', 'Feta') ]; [ users['darth'], users['bobba'] ]"); list = (List) executeExpression(compiler.compile(ctx), new HashMap()); user = (User) list.get(0); assertEquals("Darth", user.getFirstName()); user = (User) list.get(1); assertEquals("Bobba", user.getFirstName()); } public void testListNestedInsideList() { ParserContext ctx = new ParserContext(); ctx.addImport("User", User.class); ExpressionCompiler compiler = new ExpressionCompiler("users = [ new User('Darth', 'Vadar'), " + "new User('Bobba', 'Feta') ]; [ users.get( 0 ), users.get( 1 ) ]"); List list = (List) executeExpression(compiler.compile(ctx), new HashMap()); User user = (User) list.get(0); assertEquals("Darth", user.getFirstName()); user = (User) list.get(1); assertEquals("Bobba", user.getFirstName()); compiler = new ExpressionCompiler("users = [ new User('Darth', 'Vadar'), " + "new User('Bobba', 'Feta') ]; [ users[0], users[1] ]"); list = (List) executeExpression(compiler.compile(ctx), new HashMap()); user = (User) list.get(0); assertEquals("Darth", user.getFirstName()); user = (User) list.get(1); assertEquals("Bobba", user.getFirstName()); } public void testSetSemantics() { Bar bar = new Bar(); Foo foo = new Foo(); assertEquals("dog", MVEL.getProperty("name", bar)); assertEquals("dog", MVEL.getProperty("name", foo)); } public void testMapBindingSemantics2() { OptimizerFactory.setDefaultOptimizer("ASM"); Map outermap = new HashMap(); Map innermap = new HashMap(); innermap.put("test", "foo"); outermap.put("innermap", innermap); executeSetExpression(compileSetExpression("innermap['test']"), outermap, "bar"); assertEquals("bar", testCompiledSimple("innermap['test']", outermap, null)); } public void testDynamicImports() { ParserContext ctx = new ParserContext(); ctx.addPackageImport("java.util"); ExpressionCompiler compiler = new ExpressionCompiler("HashMap"); Serializable s = compiler.compile(ctx); assertEquals(HashMap.class, executeExpression(s)); compiler = new ExpressionCompiler("map = new HashMap(); map.size()"); s = compiler.compile(ctx); assertEquals(0, executeExpression(s, new DefaultLocalVariableResolverFactory())); } public void testDynamicImports3() { String expression = "import java.util.*; HashMap map = new HashMap(); map.size()"; ExpressionCompiler compiler = new ExpressionCompiler(expression); Serializable s = compiler.compile(); assertEquals(0, executeExpression(s, new DefaultLocalVariableResolverFactory())); assertEquals(0, MVEL.eval(expression, new HashMap())); } public void testDynamicImportsInList() { ParserContext ctx = new ParserContext(); ctx.addPackageImport("org.mvel2.tests.core.res"); ExpressionCompiler compiler = new ExpressionCompiler("[ new User('Bobba', 'Feta') ]"); List list = (List) executeExpression(compiler.compile(ctx)); User user = (User) list.get(0); assertEquals("Bobba", user.getFirstName()); } public void testDynamicImportsInMap() { ParserContext ctx = new ParserContext(); ctx.addPackageImport("org.mvel2.tests.core.res"); ExpressionCompiler compiler = new ExpressionCompiler("[ 'bobba' : new User('Bobba', 'Feta') ]"); Map map = (Map) executeExpression(compiler.compile(ctx)); User user = (User) map.get("bobba"); assertEquals("Bobba", user.getFirstName()); } public void testDynamicImportsOnNestedExpressions() { ParserContext ctx = new ParserContext(); ctx.addPackageImport("org.mvel2.tests.core.res"); ExpressionCompiler compiler = new ExpressionCompiler("new Cheesery(\"bobbo\", new Cheese(\"cheddar\", 15))"); Cheesery p1 = new Cheesery("bobbo", new Cheese("cheddar", 15)); Cheesery p2 = (Cheesery) executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory()); assertEquals(p1, p2); } public void testDynamicImportsWithNullConstructorParam() { ParserContext ctx = new ParserContext(); ctx.addPackageImport("org.mvel2.tests.core.res"); ExpressionCompiler compiler = new ExpressionCompiler("new Cheesery(\"bobbo\", null)"); Cheesery p1 = new Cheesery("bobbo", null); Cheesery p2 = (Cheesery) executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory()); assertEquals(p1, p2); } public void testDynamicImportsWithIdentifierSameAsClassWithDiffCase() { ParserContext ctx = new ParserContext(); ctx.addPackageImport("org.mvel2.tests.core.res"); ctx.setStrictTypeEnforcement(false); ExpressionCompiler compiler = new ExpressionCompiler("bar.add(\"hello\")"); compiler.compile(ctx); } public void testTypedAssignment() { assertEquals("foobar", test("java.util.Map map = new java.util.HashMap(); map.put('conan', 'foobar'); map['conan'];")); } public void testFQCNwithStaticInList() { assertEquals(Integer.MIN_VALUE, test("list = [java.lang.Integer.MIN_VALUE]; list[0]")); } public void testPrecedenceOrder() { assertTrue((Boolean) test("5 > 6 && 2 < 1 || 10 > 9")); } @SuppressWarnings({"unchecked"}) public void testDifferentImplSameCompile() { Serializable compiled = compileExpression("a.funMap.hello"); Map testMap = new HashMap(); for (int i = 0; i < 100; i++) { Base b = new Base(); b.funMap.put("hello", "dog"); testMap.put("a", b); assertEquals("dog", executeExpression(compiled, testMap)); b = new Base(); b.funMap.put("hello", "cat"); testMap.put("a", b); assertEquals("cat", executeExpression(compiled, testMap)); } } @SuppressWarnings({"unchecked"}) public void testInterfaceMethodCallWithSpace() { Map map = new HashMap(); DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper(); map.put("drools", helper); Cheese cheese = new Cheese("stilton", 15); map.put("cheese", cheese); executeExpression(compileExpression("drools.retract (cheese)"), map); assertSame(cheese, helper.retracted.get(0)); } @SuppressWarnings({"unchecked"}) public void testInterfaceMethodCallWithMacro() { Map macros = new HashMap(1); macros.put("retract", new Macro() { public String doMacro() { return "drools.retract"; } }); Map map = new HashMap(); DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper(); map.put("drools", helper); Cheese cheese = new Cheese("stilton", 15); map.put("cheese", cheese); executeExpression(compileExpression(parseMacros("retract(cheese)", macros)), map); assertSame(cheese, helper.retracted.get(0)); } @SuppressWarnings({"UnnecessaryBoxing"}) public void testToList() { String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1'," + " c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )"; List list = (List) test(text); assertSame("dog", list.get(0)); assertEquals("hello", list.get(1)); assertEquals(new Integer(42), list.get(2)); Map map = (Map) list.get(3); assertEquals("value1", map.get("key1")); List nestedList = (List) map.get("cat"); assertEquals(14, nestedList.get(0)); assertEquals("car", nestedList.get(1)); assertEquals(42, nestedList.get(2)); nestedList = (List) list.get(4); assertEquals(42, nestedList.get(0)); map = (Map) nestedList.get(1); assertEquals("value1", map.get("cat")); } @SuppressWarnings({"UnnecessaryBoxing"}) public void testToListStrictMode() { String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1'," + " c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )"; ParserContext ctx = new ParserContext(); ctx.addInput("misc", MiscTestClass.class); ctx.addInput("foo", Foo.class); ctx.addInput("c", String.class); ctx.setStrictTypeEnforcement(true); ExpressionCompiler compiler = new ExpressionCompiler(text); List list = (List) executeExpression(compiler.compile(ctx), createTestMap()); assertSame("dog", list.get(0)); assertEquals("hello", list.get(1)); assertEquals(new Integer(42), list.get(2)); Map map = (Map) list.get(3); assertEquals("value1", map.get("key1")); List nestedList = (List) map.get("cat"); assertEquals(14, nestedList.get(0)); assertEquals("car", nestedList.get(1)); assertEquals(42, nestedList.get(2)); nestedList = (List) list.get(4); assertEquals(42, nestedList.get(0)); map = (Map) nestedList.get(1); assertEquals("value1", map.get("cat")); } public void testParsingStability1() { assertEquals(true, test("( order.number == 1 || order.number == ( 1+1) || order.number == $id )")); } public void testParsingStability2() { ExpressionCompiler compiler = new ExpressionCompiler("( dim.height == 1 || dim.height == ( 1+1) || dim.height == x )"); Map imports = new HashMap(); imports.put("java.awt.Dimension", Dimension.class); final ParserContext parserContext = new ParserContext(imports, null, "sourceFile"); parserContext.setStrictTypeEnforcement(false); compiler.compile(parserContext); } public void testParsingStability3() { assertEquals(false, test("!( [\"X\", \"Y\"] contains \"Y\" )")); } public void testParsingStability4() { assertEquals(true, test("vv=\"Edson\"; !(vv ~= \"Mark\")")); } public void testConcatWithLineBreaks() { ExpressionCompiler parser = new ExpressionCompiler("\"foo\"+\n\"bar\""); ParserContext ctx = new ParserContext(); ctx.setDebugSymbols(true); ctx.setSourceFile("source.mv"); assertEquals("foobar", executeExpression(parser.compile(ctx))); } public void testMapWithStrictTyping() { ExpressionCompiler compiler = new ExpressionCompiler("map['KEY1'] == $msg"); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setStrongTyping(true); ctx.addInput("$msg", String.class); ctx.addInput("map", Map.class); Serializable expr = compiler.compile(ctx); Map map = new HashMap(); map.put("KEY1", "MSGONE"); Map vars = new HashMap(); vars.put("$msg", "MSGONE"); vars.put("map", map); Boolean bool = (Boolean) executeExpression(expr, map, vars); assertEquals(Boolean.TRUE, bool); } public void testMapAsContextWithStrictTyping() { ExpressionCompiler compiler = new ExpressionCompiler("this['KEY1'] == $msg"); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setStrongTyping(true); ctx.addInput("$msg", String.class); ctx.addInput("this", Map.class); Serializable expr = compiler.compile(ctx); Map map = new HashMap(); map.put("KEY1", "MSGONE"); Map vars = new HashMap(); vars.put("$msg", "MSGONE"); Boolean bool = (Boolean) executeExpression(expr, map, vars); assertEquals(Boolean.TRUE, bool); } /** * Community provided test cases */ @SuppressWarnings({"unchecked"}) public void testCalculateAge() { Calendar c1 = Calendar.getInstance(); c1.set(1999, 0, 10); // 1999 jan 20 Map objectMap = new HashMap(1); Map propertyMap = new HashMap(1); propertyMap.put("GEBDAT", c1.getTime()); objectMap.put("EV_VI_ANT1", propertyMap); assertEquals("N", testCompiledSimple( "new org.mvel2.tests.core.res.PDFFieldUtil().calculateAge(EV_VI_ANT1.GEBDAT) >= 25 ? 'Y' : 'N'", null, objectMap)); } /** * Provided by: Alex Roytman */ public void testMethodResolutionWithNullParameter() { Context ctx = new Context(); ctx.setBean(new Bean()); Map vars = new HashMap(); System.out.println("bean.today: " + eval("bean.today", ctx, vars)); System.out.println("formatDate(bean.today): " + eval("formatDate(bean.today)", ctx, vars)); //calling method with string param with null parameter works System.out.println("formatString(bean.nullString): " + eval("formatString(bean.nullString)", ctx, vars)); System.out.println("bean.myDate = bean.nullDate: " + eval("bean.myDate = bean.nullDate; return bean.nullDate;", ctx, vars)); //calling method with Date param with null parameter fails System.out.println("formatDate(bean.myDate): " + eval("formatDate(bean.myDate)", ctx, vars)); //same here System.out.println(eval("formatDate(bean.nullDate)", ctx, vars)); } /** * Provided by: Phillipe Ombredanne */ public void testCompileParserContextShouldNotLoopIndefinitelyOnValidJavaExpression() { String expr = " System.out.println( message );\n" + // "m.setMessage( \"Goodbye cruel world\" );\n" + // "System.out.println(m.getStatus());\n" + // "m.setStatus( Message.GOODBYE );\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.setStrictTypeEnforcement(false); context.addImport("Message", Message.class); context.addInput("System", void.class); context.addInput("message", Object.class); context.addInput("m", Object.class); compiler.compile(context); } public void testStaticNested() { assertEquals(1, eval("org.mvel2.tests.core.AbstractTest$Message.GOODBYE", new HashMap())); } public void testStaticNestedWithImport() { String expr = "Message.GOODBYE;\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.setStrictTypeEnforcement(false); context.addImport("Message", Message.class); assertEquals(1, executeExpression(compiler.compile(context))); } public void testStaticNestedWithMethodCall() { String expr = "item = new Item( \"Some Item\"); $msg.addItem( item ); return $msg"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.setStrictTypeEnforcement(false); context.addImport("Message", Message.class); context.addImport("Item", Item.class); // Serializable compiledExpression = compiler.compile(context); Map vars = new HashMap(); vars.put("$msg", new Message()); Message msg = (Message) executeExpression(compiler.compile(context), vars); Item item = (Item) msg.getItems().get(0); assertEquals("Some Item", item.getName()); } public void testsequentialAccessorsThenMethodCall() { String expr = "System.out.println(drools.workingMemory); " + "drools.workingMemory.ruleBase.removeRule(\"org.drools.examples\", \"some rule\"); "; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.setStrictTypeEnforcement(true); context.addInput("drools", KnowledgeHelper.class); RuleBase ruleBase = new RuleBaseImpl(); WorkingMemory wm = new WorkingMemoryImpl(ruleBase); KnowledgeHelper drools = new DefaultKnowledgeHelper(wm); Map vars = new HashMap(); vars.put("drools", drools); executeExpression(compiler.compile(context), vars); } /** * Provided by: Aadi Deshpande */ public void testPropertyVerfierShoudldNotLoopIndefinately() { String expr = "\t\tmodel.latestHeadlines = $list;\n" + "model.latestHeadlines.add( 0, (model.latestHeadlines[2]) );"; ExpressionCompiler compiler = new ExpressionCompiler(expr); compiler.setVerifying(true); ParserContext pCtx = new ParserContext(); pCtx.addInput("$list", List.class); pCtx.addInput("model", Model.class); compiler.compile(pCtx); } public void testCompileWithNewInsideMethodCall() { String expr = " p.name = \"goober\";\n" + " System.out.println(p.name);\n" + " drools.insert(new Address(\"Latona\"));\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.setStrictTypeEnforcement(false); context.addImport("Person", Person.class); context.addImport("Address", Address.class); context.addInput("p", Person.class); context.addInput("drools", Drools.class); compiler.compile(context); } /** * Submitted by: cleverpig */ public void testBug4() { ClassA A = new ClassA(); ClassB B = new ClassB(); System.out.println(MVEL.getProperty("date", A)); System.out.println(MVEL.getProperty("date", B)); } /** * Submitted by: Michael Neale */ public void testInlineCollectionParser1() { assertEquals("q", ((Map) test("['Person.age' : [1, 2, 3, 4],'Person.rating' : 'q']")).get("Person.rating")); assertEquals("q", ((Map) test("['Person.age' : [1, 2, 3, 4], 'Person.rating' : 'q']")).get("Person.rating")); } public void testIndexer() { assertEquals("foobar", testCompiledSimple("import java.util.LinkedHashMap; LinkedHashMap map = new LinkedHashMap();" + " map.put('a', 'foo'); map.put('b', 'bar'); s = ''; " + "foreach (key : map.keySet()) { System.out.println(map[key]); s += map[key]; }; return s;", createTestMap())); } public void testLateResolveOfClass() { ExpressionCompiler compiler = new ExpressionCompiler("System.out.println(new Foo());"); ParserContext ctx = new ParserContext(); ctx.addImport(Foo.class); compiler.removeParserContext(); System.out.println(executeExpression(compiler.compile(ctx))); } public void testClassAliasing() { assertEquals("foobar", test("Foo = String; new Foo('foobar')")); } public void testRandomExpression1() { assertEquals("HelloWorld", test("if ((x15 = foo.bar) == foo.bar && x15 == foo.bar) { return 'HelloWorld'; } " + "else { return 'GoodbyeWorld' } ")); } public void testRandomExpression2() { assertEquals(11, test("counterX = 0; foreach (item:{1,2,3,4,5,6,7,8,9,10}) { counterX++; }; return counterX + 1;")); } public void testRandomExpression3() { assertEquals(0, test("counterX = 10; foreach (item:{1,1,1,1,1,1,1,1,1,1}) { counterX -= item; } return counterX;")); } public void testRandomExpression4() { assertEquals(true, test("result = org.mvel2.MVEL.eval('10 * 3'); result == (10 * 3);")); } public void testRandomExpression5() { assertEquals(true, test("FooClassRef = foo.getClass(); fooInst = new FooClassRef();" + " name = org.mvel2.MVEL.eval('name', fooInst); return name == 'dog'")); } public void testRandomExpression6() { assertEquals(500, test("exprString = '250' + ' ' + '*' + ' ' + '2'; " + "compiledExpr = org.mvel2.MVEL.compileExpression(exprString);" + " return org.mvel2.MVEL.executeExpression(compiledExpr);")); } public void testRandomExpression7() { assertEquals("FOOBAR", test("'foobar'.toUpperCase();")); } public void testRandomExpression8() { assertEquals(true, test("'someString'.intern(); 'someString'.hashCode() == 'someString'.hashCode();")); } public void testRandomExpression9() { assertEquals(false, test("_abc = 'someString'.hashCode(); _xyz = _abc + 1; _abc == _xyz")); } public void testRandomExpression10() { assertEquals(false, test("(_abc = (_xyz = 'someString'.hashCode()) + 1); _abc == _xyz")); } /** * Submitted by: Guerry Semones */ private Map outerMap; private Map innerMap; public void testAddIntToMapWithMapSyntax() throws Throwable { outerMap = new HashMap(); innerMap = new HashMap(); outerMap.put("innerMap", innerMap); // fails because mvel2 checks for 'tak' in the outerMap, // rather than inside innerMap in outerMap PropertyAccessor.set(outerMap, "innerMap['foo']", 42); // instead of here assertEquals(42, innerMap.get("foo")); } public void testUpdateIntInMapWithMapSyntax() throws Throwable { outerMap = new HashMap(); innerMap = new HashMap(); outerMap.put("innerMap", innerMap); // fails because mvel2 checks for 'tak' in the outerMap, // rather than inside innerMap in outerMap innerMap.put("foo", 21); PropertyAccessor.set(outerMap, "innerMap['foo']", 42); // instead of updating it here assertEquals(42, innerMap.get("foo")); } private HashMap context = new HashMap(); public void before() { HashMap map = new HashMap(); MyBean bean = new MyBean(); bean.setVar(4); map.put("bean", bean); context.put("map", map); } public void testDeepProperty() { before(); Object obj = executeExpression(compileExpression("map.bean.var"), context); assertEquals(4, obj); } public void testDeepProperty2() { before(); Object obj = executeExpression(compileExpression("map.bean.getVar()"), context); assertEquals(4, obj); } public class MyBean { int var; public int getVar() { return var; } public void setVar(int var) { this.var = var; } } public static class TargetClass { private short _targetValue = 5; public short getTargetValue() { return _targetValue; } } public void testNestedMethodCall() { List elements = new ArrayList(); elements.add(new TargetClass()); Map variableMap = new HashMap(); variableMap.put("elements", elements); eval("results = new java.util.ArrayList(); foreach (element : elements) { " + "if( {5} contains element.targetValue.intValue()) { results.add(element); } }; results", variableMap); } public void testBooleanEvaluation() { assertEquals(true, test("true||false||false")); } public void testBooleanEvaluation2() { assertEquals(true, test("equalityCheck(1,1)||fun||ackbar")); } /** * Submitted by: Dimitar Dimitrov */ public void testFailing() { Map map = new HashMap(); map.put("os", "windows"); assertTrue((Boolean) eval("os ~= 'windows|unix'", map)); } public void testSuccess() { Map map = new HashMap(); map.put("os", "windows"); assertTrue((Boolean) eval("'windows' ~= 'windows|unix'", map)); assertFalse((Boolean) eval("time ~= 'windows|unix'", new java.util.Date())); } public void testStaticWithExplicitParam() { PojoStatic pojo = new PojoStatic("10"); eval("org.mvel2.tests.core.res.AStatic.Process('10')", pojo, new HashMap()); } public void testSimpleExpression() { PojoStatic pojo = new PojoStatic("10"); eval("value!= null", pojo, new HashMap()); } public void testStaticWithExpressionParam() { PojoStatic pojo = new PojoStatic("10"); assertEquals("java.lang.String", eval("org.mvel2.tests.core.res.AStatic.Process(value.getClass().getName().toString())", pojo)); } public void testStringIndex() { assertEquals(true, test("a = 'foobar'; a[4] == 'a'")); } public void testArrayConstructionSupport1() { assertTrue(test("new String[5]") instanceof String[]); } public void testArrayConstructionSupport2() { assertTrue((Boolean) test("xStr = new String[5]; xStr.size() == 5")); } public void testArrayConstructionSupport3() { assertEquals("foo", test("xStr = new String[5][5]; xStr[4][0] = 'foo'; xStr[4][0]")); } public void testArrayConstructionSupport4() { assertEquals(10, test("xStr = new String[5][10]; xStr[4][0] = 'foo'; xStr[4].length")); } public void testAssertKeyword() { ExpressionCompiler compiler = new ExpressionCompiler("assert 1 == 2;"); Serializable s = compiler.compile(); try { executeExpression(s); } catch (AssertionError e) { return; } assertTrue(false); } public void testNullSafe() { Foo foo = new Foo(); Map map = new HashMap(); map.put("foo", foo); String expression = "foo.?bar.name == null"; Serializable compiled = compileExpression(expression); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals(false, executeExpression(compiled, map)); foo.setBar(null); assertEquals(true, executeExpression(compiled, map)); // execute a second time (to search for optimizer problems) OptimizerFactory.setDefaultOptimizer("ASM"); compiled = compileExpression(expression); foo.setBar(new Bar()); assertEquals(false, executeExpression(compiled, map)); foo.setBar(null); assertEquals(true, executeExpression(compiled, map)); // execute a second time (to search for optimizer problems) assertEquals(true, eval(expression, map)); } /** * MVEL-57 (Submitted by: Rognvald Eaversen) -- Slightly modified by cbrock to include a positive testcase. */ public void testMethodInvocationWithCollectionElement() { context = new HashMap(); context.put("pojo", new POJO()); context.put("number", "1192800637980"); Object result = MVEL.eval("pojo.function(pojo.dates[0].time)", context); assertEquals(String.valueOf(((POJO) context.get("pojo")).getDates().iterator().next().getTime()), result); } public void testNestedWithInList() { Recipient recipient1 = new Recipient(); recipient1.setName("userName1"); recipient1.setEmail("user1@domain.com"); Recipient recipient2 = new Recipient(); recipient2.setName("userName2"); recipient2.setEmail("user2@domain.com"); List list = new ArrayList(); list.add(recipient1); list.add(recipient2); String text = "array = [" + "(with ( new Recipient() ) {name = 'userName1', email = 'user1@domain.com' })," + "(with ( new Recipient() ) {name = 'userName2', email = 'user2@domain.com' })];\n"; ParserContext context = new ParserContext(); context.addImport(Recipient.class); ExpressionCompiler compiler = new ExpressionCompiler(text); Serializable execution = compiler.compile(context); List result = (List) executeExpression(execution, new HashMap()); assertEquals(list, result); } public void testNestedWithInComplexGraph3() { Recipients recipients = new Recipients(); Recipient recipient1 = new Recipient(); recipient1.setName("user1"); recipient1.setEmail("user1@domain.com"); recipients.addRecipient(recipient1); Recipient recipient2 = new Recipient(); recipient2.setName("user2"); recipient2.setEmail("user2@domain.com"); recipients.addRecipient(recipient2); EmailMessage msg = new EmailMessage(); msg.setRecipients(recipients); msg.setFrom("from@domain.com"); String text = ""; text += "new EmailMessage().{ "; text += " recipients = new Recipients().{ "; text += " recipients = [ new Recipient().{ name = 'user1', email = 'user1@domain.com' }, "; text += " new Recipient().{ name = 'user2', email = 'user2@domain.com' } ] "; text += " }, "; text += " from = 'from@domain.com' }"; ParserContext context; context = new ParserContext(); context.addImport(Recipient.class); context.addImport(Recipients.class); context.addImport(EmailMessage.class); OptimizerFactory.setDefaultOptimizer("ASM"); ExpressionCompiler compiler = new ExpressionCompiler(text); Serializable execution = compiler.compile(context); assertEquals(msg, executeExpression(execution)); assertEquals(msg, executeExpression(execution)); assertEquals(msg, executeExpression(execution)); OptimizerFactory.setDefaultOptimizer("reflective"); context = new ParserContext(context.getParserConfiguration()); compiler = new ExpressionCompiler(text); execution = compiler.compile(context); assertEquals(msg, executeExpression(execution)); assertEquals(msg, executeExpression(execution)); assertEquals(msg, executeExpression(execution)); } public static class Recipient { private String name; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Recipient other = (Recipient) obj; if (email == null) { if (other.email != null) return false; } else if (!email.equals(other.email)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } public static class Recipients { private List list = Collections.EMPTY_LIST; public void setRecipients(List recipients) { this.list = recipients; } public boolean addRecipient(Recipient recipient) { if (list == Collections.EMPTY_LIST) { this.list = new ArrayList(); } if (!this.list.contains(recipient)) { this.list.add(recipient); return true; } return false; } public boolean removeRecipient(Recipient recipient) { return this.list.remove(recipient); } public List getRecipients() { return this.list; } public Recipient[] toArray() { return list.toArray(new Recipient[list.size()]); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((list == null) ? 0 : list.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Recipients other = (Recipients) obj; if (list == null) { if (other.list != null) return false; } return list.equals(other.list); } } public static class EmailMessage { private Recipients recipients; private String from; public EmailMessage() { } public Recipients getRecipients() { return recipients; } public void setRecipients(Recipients recipients) { this.recipients = recipients; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((from == null) ? 0 : from.hashCode()); result = prime * result + ((recipients == null) ? 0 : recipients.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final EmailMessage other = (EmailMessage) obj; if (from == null) { if (other.from != null) return false; } else if (!from.equals(other.from)) return false; if (recipients == null) { if (other.recipients != null) return false; } else if (!recipients.equals(other.recipients)) return false; return true; } } public class POJO { private Set dates = new HashSet(); public POJO() { dates.add(new Date()); } public Set getDates() { return dates; } public void setDates(Set dates) { this.dates = dates; } public String function(long num) { return String.valueOf(num); } } public void testSubEvaluation() { HashMap map = new HashMap(); map.put("EV_BER_BER_NR", "12345"); map.put("EV_BER_BER_PRIV", Boolean.FALSE); assertEquals("12345", testCompiledSimple("EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')", null, map)); map.put("EV_BER_BER_PRIV", Boolean.TRUE); assertEquals("12345/PRIVAT", testCompiledSimple("EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')", null, map)); } public void testNestedMethod1() { Vector vectorA = new Vector(); Vector vectorB = new Vector(); vectorA.add("Foo"); Map map = new HashMap(); map.put("vecA", vectorA); map.put("vecB", vectorB); testCompiledSimple("vecB.add(vecA.remove(0)); vecA.add('Foo');", null, map); assertEquals("Foo", vectorB.get(0)); } public void testNegativeArraySizeBug() throws Exception { 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"; 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"; List targets = new ArrayList(); targets.add(new Target(1)); targets.add(new Target(999)); Map vars = new HashMap(); vars.put("elements", targets); assertEquals(1, ((List) testCompiledSimple(expressionString1, null, vars)).size()); assertEquals(1, ((List) testCompiledSimple(expressionString2, null, vars)).size()); } public static final class Target { private int _attribute; public Target(int attribute_) { _attribute = attribute_; } public int getAttribute() { return _attribute; } } public void testDynamicImports2() { assertEquals(BufferedReader.class, test("import java.io.*; BufferedReader")); } public void testStringWithTernaryIf() { test("System.out.print(\"Hello : \" + (foo != null ? \"FOO!\" : \"NO FOO\") + \". Bye.\");"); } public void testCompactIfElse() { assertEquals("foo", test("if (false) 'bar'; else 'foo';")); } public void testAndOpLiteral() { assertEquals(true, test("true && true")); } public void testAnonymousFunctionDecl() { assertEquals(3, test("anonFunc = function (a,b) { return a + b; }; anonFunc(1,2)")); } public void testFunctionSemantics() { assertEquals(true, test("function fooFunction(a) { return a; }; x__0 = ''; 'boob' == fooFunction(x__0 = 'boob') " + "&& x__0 == 'boob';")); } public void testUseOfVarKeyword() { assertEquals("FOO_BAR", test("var barfoo = 'FOO_BAR'; return barfoo;")); } public void testAssignment5() { assertEquals(15, test("x = (10) + (5); x")); } public void testSetExpressions1() { Map myMap = new HashMap(); final Serializable fooExpr = compileSetExpression("foo"); executeSetExpression(fooExpr, myMap, "blah"); assertEquals("blah", myMap.get("foo")); executeSetExpression(fooExpr, myMap, "baz"); assertEquals("baz", myMap.get("foo")); } public void testEgressType() { ExpressionCompiler compiler = new ExpressionCompiler("( $cheese )"); ParserContext context = new ParserContext(); context.addInput("$cheese", Cheese.class); assertEquals(Cheese.class, compiler.compile(context).getKnownEgressType()); } public void testDuplicateVariableDeclaration() { ExpressionCompiler compiler = new ExpressionCompiler("String x = \"abc\"; Integer x = new Integer( 10 );"); ParserContext context = new ParserContext(); try { compiler.compile(context); fail("Compilation must fail with duplicate variable declaration exception."); } catch (CompileException ce) { // success } } public void testFullyQualifiedTypeAndCast() { assertEquals(1, test("java.lang.Integer number = (java.lang.Integer) '1';")); } public void testThreadSafetyInterpreter1() { //First evaluation System.out.println("First evaluation: " + MVEL.eval("true")); new Thread(new Runnable() { public void run() { // Second evaluation - this succeeds only if the first evaluation is not commented out System.out.println("Second evaluation: " + MVEL.eval("true")); } }).start(); } public void testArrayList() throws SecurityException, NoSuchMethodException { Collection collection = new ArrayList(); collection.add("I CAN HAS CHEEZBURGER"); assertEquals(collection.size(), MVEL.eval("size()", collection)); } public void testUnmodifiableCollection() throws SecurityException, NoSuchMethodException { Collection collection = new ArrayList(); collection.add("I CAN HAS CHEEZBURGER"); collection = unmodifiableCollection(collection); assertEquals(collection.size(), MVEL.eval("size()", collection)); } public void testSingleton() throws SecurityException, NoSuchMethodException { Collection collection = Collections.singleton("I CAN HAS CHEEZBURGER"); assertEquals(collection.size(), MVEL.eval("size()", collection)); } public void testRegExMatch() { assertEquals(true, MVEL.eval("$test = 'foo'; $ex = 'f.*'; $test ~= $ex", new HashMap())); } public static class TestClass2 { public void addEqualAuthorizationConstraint(Foo leg, Bar ctrlClass, Integer authorization) { } } public void testJIRA93() { Map testMap = createTestMap(); testMap.put("testClass2", new TestClass2()); Serializable s = compileExpression("testClass2.addEqualAuthorizationConstraint(foo, foo.bar, 5)"); for (int i = 0; i < 5; i++) { executeExpression(s, testMap); } } public void testJIRA96() { ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.addInput("fooString", String[].class); ExpressionCompiler compiler = new ExpressionCompiler("fooString[0].toUpperCase()"); compiler.compile(ctx); } public void testStrongTyping() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); try { new ExpressionCompiler("blah").compile(ctx); } catch (Exception e) { // should fail return; } assertTrue(false); } public void testStrongTyping2() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("blah", String.class); try { new ExpressionCompiler("1-blah").compile(ctx); } catch (Exception e) { e.printStackTrace(); return; } assertTrue(false); } public void testStringToArrayCast() { Object o = test("(char[]) 'abcd'"); assertTrue(o instanceof char[]); } public void testStringToArrayCast2() { assertTrue((Boolean) test("_xyxy = (char[]) 'abcd'; _xyxy[0] == 'a'")); } public void testStaticallyTypedArrayVar() { assertTrue((Boolean) test("char[] _c___ = new char[10]; _c___ instanceof char[]")); } public void testParserErrorHandling() { final ParserContext ctx = new ParserContext(); ExpressionCompiler compiler = new ExpressionCompiler("a["); try { compiler.compile(ctx); } catch (Exception e) { return; } assertTrue(false); } public void testJIRA99_Interpreted() { Map map = new HashMap(); map.put("x", 20); map.put("y", 10); map.put("z", 5); assertEquals(20 - 10 - 5, MVEL.eval("x - y - z", map)); } public void testJIRA99_Compiled() { Map map = new HashMap(); map.put("x", 20); map.put("y", 10); map.put("z", 5); assertEquals(20 - 10 - 5, testCompiledSimple("x - y - z", map)); } public void testJIRA100() { assertEquals(new BigDecimal(20), test("java.math.BigDecimal axx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal bxx = " + "new java.math.BigDecimal( 10.0 ); java.math.BigDecimal cxx = axx + bxx; return cxx; ")); } public void testJIRA100b() { Serializable s = MVEL.compileExpression("java.math.BigDecimal axx = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal bxx = " + "new java.math.BigDecimal( 10.0 ); java.math.BigDecimal cxx = axx + bxx; return cxx; "); assertEquals(new BigDecimal(20), executeExpression(s, new HashMap())); } public void testAssignToBean() { Person person = new Person(); MVEL.eval("this.name = 'foo'", person); assertEquals("foo", person.getName()); executeExpression(compileExpression("this.name = 'bar'"), person); assertEquals("bar", person.getName()); } public void testParameterizedTypeInStrictMode() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("foo", HashMap.class, new Class[]{String.class, String.class}); ExpressionCompiler compiler = new ExpressionCompiler("foo.get('bar').toUpperCase()"); compiler.compile(ctx); } public void testParameterizedTypeInStrictMode2() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("ctx", Object.class); ExpressionCompiler compiler = new ExpressionCompiler("org.mvel2.DataConversion.convert(ctx, String).toUpperCase()"); assertEquals(String.class, compiler.compile(ctx).getKnownEgressType()); } public void testParameterizedTypeInStrictMode3() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("base", Base.class); ExpressionCompiler compiler = new ExpressionCompiler("base.list"); assertTrue(compiler.compile(ctx).getParserContext().getLastTypeParameters()[0].equals(String.class)); } public void testParameterizedTypeInStrictMode4() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("base", Base.class); ExpressionCompiler compiler = new ExpressionCompiler("base.list.get(1).toUpperCase()"); CompiledExpression ce = compiler.compile(ctx); assertEquals(String.class, ce.getKnownEgressType()); } public void testMapAssignmentNestedExpression() { Map map = new HashMap(); map.put("map", new HashMap()); String ex = "map[java.lang.Integer.MAX_VALUE] = 'bar'; map[java.lang.Integer.MAX_VALUE];"; assertEquals("bar", executeExpression(compileExpression(ex), map)); assertEquals("bar", MVEL.eval(ex, map)); } public void testMapAssignmentNestedExpression2() { Map map = new HashMap(); map.put("x", "bar"); map.put("map", new HashMap()); String ex = "map[x] = 'foo'; map['bar'];"; assertEquals("foo", executeExpression(compileExpression(ex), map)); assertEquals("foo", MVEL.eval(ex, map)); } /** * MVEL-103 */ public static class MvelContext { public boolean singleCalled; public boolean arrayCalled; public String[] regkeys; public void methodForTest(String string) { System.out.println("sigle param method called!"); singleCalled = true; } public void methodForTest(String[] strings) { System.out.println("array param method called!"); arrayCalled = true; } public void setRegkeys(String[] regkeys) { this.regkeys = regkeys; } public void setRegkeys(String regkey) { this.regkeys = regkey.split(","); } } public void testMethodResolutionOrder() { MvelContext mvelContext = new MvelContext(); MVEL.eval("methodForTest({'1','2'})", mvelContext); MVEL.eval("methodForTest('1')", mvelContext); assertTrue(mvelContext.arrayCalled && mvelContext.singleCalled); } public void testOKQuoteComment() throws Exception { // ' in comments outside of blocks seem OK compileExpression("// ' this is OK!"); compileExpression("// ' this is OK!\n"); compileExpression("// ' this is OK!\nif(1==1) {};"); } public void testOKDblQuoteComment() throws Exception { // " in comments outside of blocks seem OK compileExpression("// \" this is OK!"); compileExpression("// \" this is OK!\n"); compileExpression("// \" this is OK!\nif(1==1) {};"); } public void testIfComment() throws Exception { // No quote? OK! compileExpression("if(1 == 1) {\n" + " // Quote & Double-quote seem to break this expression\n" + "}"); } public void testIfQuoteCommentBug() throws Exception { // Comments in an if seem to fail if they contain a ' compileExpression("if(1 == 1) {\n" + " // ' seems to break this expression\n" + "}"); } public void testIfDblQuoteCommentBug() throws Exception { // Comments in a foreach seem to fail if they contain a ' compileExpression("if(1 == 1) {\n" + " // ' seems to break this expression\n" + "}"); } public void testForEachQuoteCommentBug() throws Exception { // Comments in a foreach seem to fail if they contain a ' compileExpression("foreach ( item : 10 ) {\n" + " // The ' character causes issues\n" + "}"); } public void testForEachDblQuoteCommentBug() throws Exception { // Comments in a foreach seem to fail if they contain a ' compileExpression("foreach ( item : 10 ) {\n" + " // The \" character causes issues\n" + "}"); } public void testForEachCommentOK() throws Exception { // No quote? OK! compileExpression("foreach ( item : 10 ) {\n" + " // The quote & double quote characters cause issues\n" + "}"); } public void testElseIfCommentBugPreCompiled() throws Exception { // Comments can't appear before else if() - compilation works, but evaluation fails executeExpression(compileExpression("// This is never true\n" + "if (1==0) {\n" + " // Never reached\n" + "}\n" + "// This is always true...\n" + "else if (1==1) {" + " System.out.println('Got here!');" + "}\n")); } public void testElseIfCommentBugEvaluated() throws Exception { // Comments can't appear before else if() MVEL.eval("// This is never true\n" + "if (1==0) {\n" + " // Never reached\n" + "}\n" + "// This is always true...\n" + "else if (1==1) {" + " System.out.println('Got here!');" + "}\n"); } public void testRegExpOK() throws Exception { // This works OK intepreted assertEquals(Boolean.TRUE, MVEL.eval("'Hello'.toUpperCase() ~= '[A-Z]{0,5}'")); assertEquals(Boolean.TRUE, MVEL.eval("1 == 0 || ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')")); // This works OK if toUpperCase() is avoided in pre-compiled assertEquals(Boolean.TRUE, executeExpression(compileExpression("'Hello' ~= '[a-zA-Z]{0,5}'"))); } public void testRegExpPreCompiledBug() throws Exception { // If toUpperCase() is used in the expression then this fails; returns null not // a boolean. Object ser = compileExpression("'Hello'.toUpperCase() ~= '[a-zA-Z]{0,5}'"); assertEquals(Boolean.TRUE, executeExpression(ser)); } public void testRegExpOrBug() throws Exception { // This fails during execution due to returning null, I think... assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 0 || ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')"))); } public void testRegExpAndBug() throws Exception { // This also fails due to returning null, I think... // Object ser = MVEL.compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')"); assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')"))); } public void testLiteralUnionWithComparison() { assertEquals(Boolean.TRUE, executeExpression(compileExpression("1 == 1 && ('Hello'.toUpperCase() ~= '[A-Z]{0,5}')"))); } public static final List STRINGS = Arrays.asList("hi", "there"); public static class A { public void foo(String s) { } public void bar(String s) { } public List getStrings() { return STRINGS; } } public static class B extends A { @Override public void foo(String s) { super.foo(s); } public void bar(int s) { } } public static class C extends A { } public final void testDetermineEgressParametricType() { final ParserContext parserContext = new ParserContext(); parserContext.setStrongTyping(true); parserContext.addInput("strings", List.class, new Class[]{String.class}); final CompiledExpression expr = new ExpressionCompiler("strings").compile(parserContext); assertTrue(STRINGS.equals(executeExpression(expr, new A()))); final Type[] typeParameters = expr.getParserContext().getLastTypeParameters(); assertTrue(typeParameters != null); assertTrue(String.class.equals(typeParameters[0])); } public final void testDetermineEgressParametricType2() { final ParserContext parserContext = new ParserContext(); parserContext.setStrongTyping(true); parserContext.addInput("strings", List.class, new Class[]{String.class}); final CompiledExpression expr = new ExpressionCompiler("strings", parserContext).compile(); assertTrue(STRINGS.equals(executeExpression(expr, new A()))); final Type[] typeParameters = expr.getParserContext().getLastTypeParameters(); assertTrue(null != typeParameters); assertTrue(String.class.equals(typeParameters[0])); } public void testCustomPropertyHandler() { MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true; PropertyHandlerFactory.registerPropertyHandler(SampleBean.class, new SampleBeanAccessor()); assertEquals("dog", test("foo.sampleBean.bar.name")); PropertyHandlerFactory.unregisterPropertyHandler(SampleBean.class); MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = false; } public void testSetAccessorOverloadedEqualsStrictMode() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("foo", Foo.class); try { CompiledExpression expr = new ExpressionCompiler("foo.bar = 0").compile(ctx); } catch (CompileException e) { // should fail. e.printStackTrace(); return; } assertTrue(false); } public void testSetAccessorOverloadedEqualsStrictMode2() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("foo", Foo.class); try { CompiledExpression expr = new ExpressionCompiler("foo.aValue = 'bar'").compile(ctx); } catch (CompileException e) { assertTrue(false); } } public void testAnalysisCompile() { ParserContext pCtx = new ParserContext(); ExpressionCompiler e = new ExpressionCompiler("foo.aValue = 'bar'"); e.setVerifyOnly(true); e.compile(pCtx); assertTrue(pCtx.getInputs().keySet().contains("foo")); assertEquals(1, pCtx.getInputs().size()); assertEquals(0, pCtx.getVariables().size()); } public void testDataConverterStrictMode() throws Exception { OptimizerFactory.setDefaultOptimizer("ASM"); DataConversion.addConversionHandler(Date.class, new MVELDateCoercion()); ParserContext ctx = new ParserContext(); ctx.addImport("Cheese", Cheese.class); ctx.setStrongTyping(true); ctx.setStrictTypeEnforcement(true); Locale.setDefault(Locale.US); Cheese expectedCheese = new Cheese(); expectedCheese.setUseBy(new SimpleDateFormat("dd-MMM-yyyy").parse("10-Jul-1974")); ExpressionCompiler compiler = new ExpressionCompiler("c = new Cheese(); c.useBy = '10-Jul-1974'; return c"); Cheese actualCheese = (Cheese) executeExpression(compiler.compile(ctx), createTestMap()); assertEquals(expectedCheese.getUseBy(), actualCheese.getUseBy()); } public static class MVELDateCoercion implements ConversionHandler { public boolean canConvertFrom(Class cls) { if (cls == String.class || cls.isAssignableFrom(Date.class)) { return true; } else { return false; } } public Object convertFrom(Object o) { try { SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); if (o instanceof String) { return sdf.parse((String) o); } else { return o; } } catch (Exception e) { throw new RuntimeException("Exception was thrown", e); } } } private static final KnowledgeHelperFixer fixer = new KnowledgeHelperFixer(); public void testSingleLineCommentSlash() { String result = fixer.fix(" //System.out.println( \"help\" );\r\n " + " System.out.println( \"help\" ); \r\n list.add( $person );"); assertEquals(" //System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n " + " list.add( $person );", result); } public void testSingleLineCommentHash() { String result = fixer.fix(" #System.out.println( \"help\" );\r\n " + " System.out.println( \"help\" ); \r\n list.add( $person );"); assertEquals(" #System.out.println( \"help\" );\r\n System.out.println( \"help\" ); \r\n " + " list.add( $person );", result); } public void testMultiLineComment() { String result = fixer.fix(" /*System.out.println( \"help\" );\r\n*/ " + " System.out.println( \"help\" ); \r\n list.add( $person );"); assertEquals(" /*System.out.println( \"help\" );\r\n*/ System.out.println( \"help\" ); \r\n " + " list.add( $person );", result); } public void testAdd__Handle__Simple() { String result = fixer.fix("update(myObject );"); assertEqualsIgnoreWhitespace("drools.update(myObject );", result); result = fixer.fix("update ( myObject );"); assertEqualsIgnoreWhitespace("drools.update( myObject );", result); } public void testAdd__Handle__withNewLines() { final String result = fixer.fix("\n\t\n\tupdate( myObject );"); assertEqualsIgnoreWhitespace("\n\t\n\tdrools.update( myObject );", result); } public void testAdd__Handle__rComplex() { String result = fixer.fix("something update( myObject); other"); assertEqualsIgnoreWhitespace("something drools.update( myObject); other", result); result = fixer.fix("something update ( myObject );"); assertEqualsIgnoreWhitespace("something drools.update( myObject );", result); result = fixer.fix(" update( myObject ); x"); assertEqualsIgnoreWhitespace(" drools.update( myObject ); x", result); //should not touch, as it is not a stand alone word result = fixer.fix("xxupdate(myObject ) x"); assertEqualsIgnoreWhitespace("xxupdate(myObject ) x", result); } public void testMultipleMatches() { String result = fixer.fix("update(myObject); update(myObject );"); assertEqualsIgnoreWhitespace("drools.update(myObject); drools.update(myObject );", result); result = fixer.fix("xxx update(myObject ); update( myObject ); update( yourObject ); yyy"); assertEqualsIgnoreWhitespace("xxx drools.update(myObject ); " + "drools.update( myObject ); drools.update( yourObject ); yyy", result); } public void testAssert1() { final String raw = "insert( foo );"; final String result = "drools.insert( foo );"; assertEqualsIgnoreWhitespace(result, fixer.fix(raw)); } public void testAssert2() { final String raw = "some code; insert( new String(\"foo\") );\n More();"; final String result = "some code; drools.insert( new String(\"foo\") );\n More();"; assertEqualsIgnoreWhitespace(result, fixer.fix(raw)); } public void testAssertLogical() { final String raw = "some code; insertLogical(new String(\"foo\"));\n More();"; final String result = "some code; drools.insertLogical(new String(\"foo\"));\n More();"; assertEqualsIgnoreWhitespace(result, fixer.fix(raw)); } public void testModifyRetractModifyInsert() { final String raw = "some code; insert( bar ); modifyRetract( foo );\n More();" + " retract( bar ); modifyInsert( foo );"; final String result = "some code; drools.insert( bar ); drools.modifyRetract( foo );\n More();" + " drools.retract( bar ); drools.modifyInsert( foo );"; assertEqualsIgnoreWhitespace(result, fixer.fix(raw)); } public void testAllActionsMushedTogether() { String result = fixer.fix("insert(myObject ); update(ourObject);\t retract(herObject);"); assertEqualsIgnoreWhitespace("drools.insert(myObject ); drools.update(ourObject);\t drools.retract(herObject);", result); result = fixer.fix("insert( myObject ); update(ourObject);\t retract(herObject );\n" + "insert( myObject ); update(ourObject);\t retract( herObject );"); assertEqualsIgnoreWhitespace("drools.insert( myObject ); drools.update(ourObject);\t " + "drools.retract(herObject );\ndrools.insert( myObject ); drools.update(ourObject);\t" + " drools.retract( herObject );", result); } public void testLeaveLargeAlone() { final String original = "yeah yeah yeah minsert( xxx ) this is a long() thing Person" + " (name=='drools') modify a thing"; final String result = fixer.fix(original); assertEqualsIgnoreWhitespace(original, result); } public void testWithNull() { final String original = null; final String result = fixer.fix(original); assertEqualsIgnoreWhitespace(original, result); } public void testLeaveAssertAlone() { final String original = "drools.insert(foo)"; assertEqualsIgnoreWhitespace(original, fixer.fix(original)); } public void testLeaveAssertLogicalAlone() { final String original = "drools.insertLogical(foo)"; assertEqualsIgnoreWhitespace(original, fixer.fix(original)); } public void testWackyAssert() { final String raw = "System.out.println($person1.getName() + \" and \" + $person2.getName() " + "+\" are sisters\");\n" + "insert($person1.getName(\"foo\") + \" and \" + $person2.getName() " + "+\" are sisters\"); yeah();"; final String expected = "System.out.println($person1.getName() + \" and \" + $person2.getName()" + " +\" are sisters\");\n" + "drools.insert($person1.getName(\"foo\") + \" and \" + $person2.getName() " + "+\" are sisters\"); yeah();"; assertEqualsIgnoreWhitespace(expected, fixer.fix(raw)); } public void testMoreAssertCraziness() { final String raw = "foobar(); (insert(new String(\"blah\").get()); bangBangYudoHono();)"; assertEqualsIgnoreWhitespace("foobar(); (drools.insert(new String(\"blah\").get()); bangBangYudoHono();)", fixer.fix(raw)); } public void testRetract() { final String raw = "System.out.println(\"some text\");retract(object);"; assertEqualsIgnoreWhitespace("System.out.println(\"some text\");drools.retract(object);", fixer.fix(raw)); } private void assertEqualsIgnoreWhitespace(final String expected, final String actual) { if (expected == null || actual == null) { assertEquals(expected, actual); return; } final String cleanExpected = expected.replaceAll("\\s+", ""); final String cleanActual = actual.replaceAll("\\s+", ""); assertEquals(cleanExpected, cleanActual); } public void testReturnType1() { assertEquals(Double.class, new ExpressionCompiler("100.5").compile().getKnownEgressType()); } public void testReturnType2() { assertEquals(Integer.class, new ExpressionCompiler("1").compile().getKnownEgressType()); } public void testStrongTyping3() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); try { new ExpressionCompiler("foo.toUC(100.5").compile(ctx); } catch (Exception e) { // should fail. return; } assertTrue(false); } public void testEgressType1() { assertEquals(Boolean.class, new ExpressionCompiler("foo != null").compile().getKnownEgressType()); } public void testIncrementInBooleanStatement() { assertEquals(true, test("hour++ < 61 && hour == 61")); } public void testIncrementInBooleanStatement2() { assertEquals(true, test("++hour == 61")); } public void testDeepNestedLoopsInFunction() { assertEquals(10, test("def increment(i) { i + 1 }; def ff(i) { x = 0; while (i < 1) { " + "x++; " + "while (i < 10) { i = increment(i); } }; if (x == 1) return i; else -1; }; i = 0; ff(i);")); } public void testArrayDefinitionWithInitializer() { String[] compareTo = new String[]{"foo", "bar"}; String[] results = (String[]) test("new String[] { 'foo', 'bar' }"); for (int i = 0; i < compareTo.length; i++) { if (!compareTo[i].equals(results[i])) throw new AssertionError("arrays do not match."); } } public void testStaticallyTypedItemInForEach() { assertEquals("1234", test("StringBuffer sbuf = new StringBuffer(); foreach (int i : new int[] { 1,2,3,4 })" + " { sbuf.append(i); }; sbuf.toString()")); } public void testArrayDefinitionWithCoercion() { Double[] d = (Double[]) test("new double[] { 1,2,3,4 }"); assertEquals(2d, d[1]); } public void testArrayDefinitionWithCoercion2() { Float[] d = (Float[]) test("new float[] { 1,2,3,4 }"); assertEquals(2f, d[1]); } public void testStaticallyTypedLong() { assertEquals(10l, test("10l")); } public void testCompileTimeCoercion() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("foo", Foo.class); assertEquals(true, executeExpression(new ExpressionCompiler("foo.bar.woof == 'true'").compile(ctx), createTestMap())); } public void testHexCharacter() { assertEquals(0x0A, MVEL.eval("0x0A")); } public void testOctalEscapes() { assertEquals("\344", MVEL.eval("'\\344'")); } public void testOctalEscapes2() { assertEquals("\7", MVEL.eval("'\\7'")); } public void testOctalEscapes3() { assertEquals("\777", MVEL.eval("'\\777'")); } public void testUniHex1() { assertEquals("\uFFFF::", MVEL.eval("'\\uFFFF::'")); } public void testNumLiterals() { assertEquals(1e1f, MVEL.eval("1e1f")); } public void testNumLiterals2() { assertEquals(2.f, MVEL.eval("2.f")); } public void testNumLiterals3() { assertEquals(.3f, MVEL.eval(".3f")); } public void testNumLiterals4() { assertEquals(3.14f, MVEL.eval("3.14f")); } public void testNumLiterals5() { Object o = MVEL.eval("1e1"); assertEquals(1e1, MVEL.eval("1e1")); } public void testNumLiterals6() { assertEquals(2., MVEL.eval("2.")); } public void testNumLiterals7() { assertEquals(.3, MVEL.eval(".3")); } public void testNumLiterals8() { assertEquals(1e-9d, MVEL.eval("1e-9d")); } public void testNumLiterals9() { assertEquals(0x400921FB54442D18L, MVEL.eval("0x400921FB54442D18L")); } public void testArrayCreation2() { String[][] s = (String[][]) test("new String[][] {{\"2008-04-01\", \"2008-05-10\"}," + " {\"2007-03-01\", \"2007-02-12\"}}"); assertEquals("2007-03-01", s[1][0]); } public void testArrayCreation3() { OptimizerFactory.setDefaultOptimizer("ASM"); Serializable ce = compileExpression("new String[][] {{\"2008-04-01\", \"2008-05-10\"}," + " {\"2007-03-01\", \"2007-02-12\"}}"); String[][] s = (String[][]) executeExpression(ce); assertEquals("2007-03-01", s[1][0]); } public void testArrayCreation4() { String[][] s = (String[][]) test("new String[][]{{\"2008-04-01\", \"2008-05-10\"}," + " {\"2007-03-01\", \"2007-02-12\"}}"); assertEquals("2007-03-01", s[1][0]); } public void testNakedMethodCall() { MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true; OptimizerFactory.setDefaultOptimizer("ASM"); Serializable c = compileExpression("tm = System.currentTimeMillis"); assertTrue(((Long) executeExpression(c, new HashMap())) > 0); OptimizerFactory.setDefaultOptimizer("reflective"); assertTrue(((Long) executeExpression(c, new HashMap())) > 0); Map map = new HashMap(); map.put("foo", new Foo()); c = compileExpression("foo.happy"); assertEquals("happyBar", executeExpression(c, map)); OptimizerFactory.setDefaultOptimizer("ASM"); c = compileExpression("foo.happy"); assertEquals("happyBar", executeExpression(c, map)); MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = false; } public void testDecl() { assertEquals((char) 100, test("char chr; chr = 100; chr")); } public void testInlineUnion() { assertEquals("test", test("{'foo', 'test'}[1]")); } public static double minim(double[] tab) { double min = Float.MAX_VALUE; for (int i = 0; i < tab.length; i++) { if (min > tab[i]) { min = tab[i]; } } return min; } public void testJIRA113() { assertEquals(true, test("org.mvel2.tests.core.CoreConfidenceTests.minim( new double[] {456.2, 2.3} ) == 2.3")); } public void testSetCoercion() { Serializable s = compileSetExpression("name"); Foo foo = new Foo(); executeSetExpression(s, foo, 12); assertEquals("12", foo.getName()); foo = new Foo(); setProperty(foo, "name", 12); assertEquals("12", foo.getName()); } public void testSetCoercion2() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("sampleBean", SampleBean.class); Serializable s = compileSetExpression("sampleBean.map2['bleh']", ctx); Foo foo = new Foo(); executeSetExpression(s, foo, "12"); assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue()); foo = new Foo(); executeSetExpression(s, foo, "13"); assertEquals(13, foo.getSampleBean().getMap2().get("bleh").intValue()); OptimizerFactory.setDefaultOptimizer("ASM"); ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("sampleBean", SampleBean.class); s = compileSetExpression("sampleBean.map2['bleh']", ctx); foo = new Foo(); executeSetExpression(s, foo, "12"); assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue()); executeSetExpression(s, foo, new Integer(12)); assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue()); } public void testListCoercion() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("bar", Bar.class); Serializable s = compileSetExpression("bar.testList[0]", ctx); Foo foo = new Foo(); foo.getBar().getTestList().add(new Integer(-1)); executeSetExpression(s, foo, "12"); assertEquals(12, foo.getBar().getTestList().get(0).intValue()); foo = new Foo(); foo.getBar().getTestList().add(new Integer(-1)); executeSetExpression(s, foo, "13"); assertEquals(13, foo.getBar().getTestList().get(0).intValue()); OptimizerFactory.setDefaultOptimizer("ASM"); ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("bar", Bar.class); s = compileSetExpression("bar.testList[0]", ctx); foo = new Foo(); foo.getBar().getTestList().add(new Integer(-1)); executeSetExpression(s, foo, "12"); assertEquals(12, foo.getBar().getTestList().get(0).intValue()); executeSetExpression(s, foo, "13"); assertEquals(13, foo.getBar().getTestList().get(0).intValue()); } public void testArrayCoercion1() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("bar", Bar.class); Serializable s = compileSetExpression("bar.intarray[0]", ctx); Foo foo = new Foo(); executeSetExpression(s, foo, "12"); assertEquals(12, foo.getBar().getIntarray()[0].intValue()); foo = new Foo(); executeSetExpression(s, foo, "13"); assertEquals(13, foo.getBar().getIntarray()[0].intValue()); OptimizerFactory.setDefaultOptimizer("ASM"); ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("bar", Bar.class); s = compileSetExpression("bar.intarray[0]", ctx); foo = new Foo(); executeSetExpression(s, foo, "12"); assertEquals(12, foo.getBar().getIntarray()[0].intValue()); executeSetExpression(s, foo, "13"); assertEquals(13, foo.getBar().getIntarray()[0].intValue()); } public void testFieldCoercion1() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("bar", Bar.class); Serializable s = compileSetExpression("bar.assignTest", ctx); Foo foo = new Foo(); executeSetExpression(s, foo, 12); assertEquals("12", foo.getBar().getAssignTest()); foo = new Foo(); executeSetExpression(s, foo, 13); assertEquals("13", foo.getBar().getAssignTest()); OptimizerFactory.setDefaultOptimizer("ASM"); ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("bar", Bar.class); s = compileSetExpression("bar.assignTest", ctx); foo = new Foo(); executeSetExpression(s, foo, 12); assertEquals("12", foo.getBar().getAssignTest()); executeSetExpression(s, foo, 13); assertEquals("13", foo.getBar().getAssignTest()); } public void testJIRA115() { String exp = "results = new java.util.ArrayList(); foreach (element : elements) { " + "if( {1,32769,32767} contains element ) { results.add(element); } }; results"; Map map = new HashMap(); map.put("elements", new int[]{1, 32769, 32767}); ArrayList result = (ArrayList) MVEL.eval(exp, map); assertEquals(3, result.size()); } public void testStaticTyping2() { String exp = "int x = 5; int y = 2; new int[] { x, y }"; Integer[] res = (Integer[]) MVEL.eval(exp, new HashMap()); assertEquals(5, res[0].intValue()); assertEquals(2, res[1].intValue()); } public void testFunctions5() { String exp = "def foo(a,b) { a + b }; foo(1.5,5.25)"; System.out.println(MVEL.eval(exp, new HashMap())); } public void testChainedMethodCallsWithParams() { assertEquals(true, test("foo.toUC(\"abcd\").equals(\"ABCD\")")); } public void testIsUsedInIf() { assertEquals(true, test("c = 'str'; if (c is String) { true; } else { false; } ")); } public void testJIRA122() { Serializable s = compileExpression("System.out.println('>'+java.lang.Character.toLowerCase(name.charAt(0))); java.lang.Character.toLowerCase(name.charAt(0)) == 'a'"); OptimizerFactory.setDefaultOptimizer("ASM"); Map map = new HashMap(); map.put("name", "Adam"); assertEquals(true, executeExpression(s, map)); assertEquals(true, executeExpression(s, map)); } public void testJIRA122b() { Serializable s = compileExpression("System.out.println('>'+java.lang.Character.toLowerCase(name.charAt(0))); java.lang.Character.toLowerCase(name.charAt(0)) == 'a'"); OptimizerFactory.setDefaultOptimizer("reflective"); Map map = new HashMap(); map.put("name", "Adam"); assertEquals(true, executeExpression(s, map)); assertEquals(true, executeExpression(s, map)); } public void testJIRA103() { MvelContext mvelContext = new MvelContext(); MVEL.setProperty(mvelContext, "regkeys", "s"); } public void testJIRA103b() { MvelContext mvelContext = new MvelContext(); Map map = new HashMap(); map.put("ctx", mvelContext); Serializable c = compileExpression("ctx.regkeys = 'foo'"); executeExpression(c, map); executeExpression(c, map); } public void testNewUsingWith() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addImport(Foo.class); ctx.addImport(Bar.class); Serializable s = compileExpression("[ 'foo' : (with ( new Foo() )" + " { bar = with ( new Bar() ) { name = 'ziggy' } }) ]", ctx); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals("ziggy", (((Foo) ((Map) executeExpression(s)).get("foo")).getBar().getName())); } private static Map JIRA124_CTX = Collections.singletonMap("testValue", true); public void testJIRA124() throws Exception { assertEquals("A", testTernary(1, "testValue == true ? 'A' : 'B' + 'C'")); assertEquals("AB", testTernary(2, "testValue ? 'A' + 'B' : 'C'")); assertEquals("A", testTernary(3, "(testValue ? 'A' : 'B' + 'C')")); assertEquals("AB", testTernary(4, "(testValue ? 'A' + 'B' : 'C')")); assertEquals("A", testTernary(5, "(testValue ? 'A' : ('B' + 'C'))")); assertEquals("AB", testTernary(6, "(testValue ? ('A' + 'B') : 'C')")); JIRA124_CTX = Collections.singletonMap("testValue", false); assertEquals("BC", testTernary(1, "testValue ? 'A' : 'B' + 'C'")); assertEquals("C", testTernary(2, "testValue ? 'A' + 'B' : 'C'")); assertEquals("BC", testTernary(3, "(testValue ? 'A' : 'B' + 'C')")); assertEquals("C", testTernary(4, "(testValue ? 'A' + 'B' : 'C')")); assertEquals("BC", testTernary(5, "(testValue ? 'A' : ('B' + 'C'))")); assertEquals("C", testTernary(6, "(testValue ? ('A' + 'B') : 'C')")); } private static Object testTernary(int i, String expression) throws Exception { Object val; Object val2; try { val = executeExpression(compileExpression(expression), JIRA124_CTX); } catch (Exception e) { System.out.println("FailedCompiled[" + i + "]:" + expression); throw e; } try { val2 = MVEL.eval(expression, JIRA124_CTX); } catch (Exception e) { System.out.println("FailedEval[" + i + "]:" + expression); throw e; } if (((val == null || val2 == null) && val != val2) || (val != null && !val.equals(val2))) { throw new AssertionError("results do not match (" + String.valueOf(val) + " != " + String.valueOf(val2) + ")"); } return val; } public void testMethodCaching() { MVEL.eval("for (pet: getPets()) pet.run();", new PetStore()); } public static class PetStore { public List getPets() { List pets = new ArrayList(); pets.add(new Dog()); pets.add(new Cat()); return pets; } } public static class Pet { public void run() { } } public static class Dog extends Pet { @Override public void run() { System.out.println("dog is running"); } } public static class Cat extends Pet { @Override public void run() { System.out.println("cat is running"); } } public void testSetExpressions2() { Foo foo = new Foo(); Collection col = new ArrayList(); final Serializable fooExpr = compileSetExpression("collectionTest"); executeSetExpression(fooExpr, foo, col); assertEquals(col, foo.getCollectionTest()); } public class Fruit { public class Apple { } } public void testInnerClassReference() { assertEquals(Fruit.Apple.class, test("import " + CoreConfidenceTests.class.getName() + "; CoreConfidenceTests.Fruit.Apple")); } public void testEdson() { assertEquals("foo", test("list = new java.util.ArrayList(); list.add(new String('foo')); list[0]")); } public void testEnumSupport() { MyInterface myInterface = new MyClass(); myInterface.setType(MyInterface.MY_ENUM.TWO, true); boolean isType = MVEL.eval("isType(org.mvel2.tests.core.res.MyInterface$MY_ENUM.ONE)", myInterface, Boolean.class); System.out.println(isType); } public void testOperatorPrecedenceOrder() { Serializable compiled = compileExpression("bean1.successful && bean2.failed || bean1.failed && bean2.successful"); Map context = new HashMap(); BeanB bean1 = new BeanB(true); BeanB bean2 = new BeanB(false); context.put("bean1", bean1); context.put("bean2", bean2); System.out.println("interpreted: " + MVEL.eval("bean1.successful && bean2.failed || bean1.failed && bean2.successful", context)); assertEquals(bean1.isSuccessful() && bean2.isFailed() || bean1.isFailed() && bean2.isSuccessful(), (boolean) executeExpression(compiled, context, Boolean.class)); } public static class BeanB { private boolean successful; public BeanB(boolean successful) { this.successful = successful; } public boolean isSuccessful() { return successful; } public boolean isFailed() { return !successful; } } public void testJIRA139() { ParserContext ctx = new ParserContext(); ctx.addImport("ReflectionUtil", ReflectionUtil.class); Serializable s = compileExpression("ReflectionUtil.getGetter('foo')", ctx); assertEquals(ReflectionUtil.getGetter("foo"), executeExpression(s)); } public void testJIRA140() { ParserContext ctx = new ParserContext(); Serializable s = compileExpression("import org.mvel2.tests.core.res.*;" + "cols = new Column[] { new Column('name', 20), new Column('age', 2) };" + "grid = new Grid(new Model(cols));", ctx); Grid g = (Grid) executeExpression(s, new HashMap()); assertEquals(g.getModel().getColumns()[0].getName(), "name"); assertEquals(g.getModel().getColumns()[0].getLength(), 20); assertEquals(g.getModel().getColumns()[1].getName(), "age"); assertEquals(g.getModel().getColumns()[1].getLength(), 2); } public void testVerifierWithIndexedProperties() { ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.addInput("base", Base.class); Serializable s = compileExpression("base.fooMap['foo'].setName('coffee')", ctx); Map vars = new HashMap(); vars.put("base", new Base()); executeExpression(s, vars); assertEquals("coffee", ((Base) vars.get("base")).fooMap.get("foo").getName()); } public void testPrimitiveTypes() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("base", Base.class); Serializable s = compileExpression("int x = 5; x = x + base.intValue; x", ctx); Map vars = new HashMap(); vars.put("base", new Base()); Number x = (Number) executeExpression(s, vars); assertEquals(15, x.intValue()); } public void testAutoBoxing() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); //ctx.addInput("base", Base.class); Serializable s = compileExpression("(list = new java.util.ArrayList()).add( 5 ); list", ctx); Map vars = new HashMap(); //vars.put("base", new Base()); List list = (List) executeExpression(s, vars); assertEquals(1, list.size()); } public void testAutoBoxing2() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("base", Base.class); Serializable s = compileExpression("java.util.List list = new java.util.ArrayList(); " + "list.add( base.intValue ); list", ctx); Map vars = new HashMap(); vars.put("base", new Base()); List list = (List) executeExpression(s, vars); assertEquals(1, list.size()); } public void testTypeCoercion() { OptimizerFactory.setDefaultOptimizer("ASM"); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("base", Base.class); Serializable s = compileExpression("java.math.BigInteger x = new java.math.BigInteger( \"5\" );" + " x + base.intValue;", ctx); Map vars = new HashMap(); vars.put("base", new Base()); Number x = (Number) executeExpression(s, vars); assertEquals(15, x.intValue()); } public void testTypeCoercion2() { OptimizerFactory.setDefaultOptimizer("reflective"); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("base", Base.class); Serializable s = compileExpression("java.math.BigInteger x = new java.math.BigInteger( \"5\" );" + " x + base.intValue;", ctx); Map vars = new HashMap(); vars.put("base", new Base()); Number x = (Number) executeExpression(s, vars); assertEquals(15, x.intValue()); } public void testEmpty() { ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); Serializable s = compileExpression("list = new java.util.ArrayList(); list == empty", ctx); Map vars = new HashMap(); Boolean x = (Boolean) executeExpression(s, vars); assertNotNull(x); assertTrue(x.booleanValue()); } public void testMapsAndLists() { OptimizerFactory.setDefaultOptimizer("ASM"); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addImport(HashMap.class); ctx.addImport(ArrayList.class); ctx.addInput("list", List.class); String expression = "m = new HashMap();\n" + "l = new ArrayList();\n" + "l.add(\"first\");\n" + "m.put(\"content\", l);\n" + "list.add(((ArrayList)m[\"content\"])[0]);"; Serializable s = compileExpression(expression, ctx); Map vars = new HashMap(); List list = new ArrayList(); vars.put("list", list); Boolean result = (Boolean) executeExpression(s, vars); assertNotNull(result); assertTrue(result); assertEquals(1, list.size()); assertEquals("first", list.get(0)); } public void testMapsAndLists2() { OptimizerFactory.setDefaultOptimizer("reflective"); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addImport(HashMap.class); ctx.addImport(ArrayList.class); ctx.addInput("list", List.class); String expression = "m = new HashMap();\n" + "l = new ArrayList();\n" + "l.add(\"first\");\n" + "m.put(\"content\", l);\n" + "list.add(((ArrayList)m[\"content\"])[0]);"; Serializable s = compileExpression(expression, ctx); Map vars = new HashMap(); List list = new ArrayList(); vars.put("list", list); Boolean result = (Boolean) executeExpression(s, vars); assertNotNull(result); assertTrue(result); assertEquals(1, list.size()); assertEquals("first", list.get(0)); } public void testReturnBoolean() { String ex = "list = new java.util.ArrayList(); return list != null"; ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); Serializable s = compileExpression(ex, ctx); assertEquals(true, executeExpression(s, new HashMap())); } public void testInlineListSensitivenessToSpaces() { String ex = "([\"a\",\"b\", \"c\"])"; ParserContext ctx = new ParserContext(); Serializable s = compileExpression(ex, ctx); List result = (List) executeExpression(s, new HashMap()); assertNotNull(result); assertEquals("a", result.get(0)); assertEquals("b", result.get(1)); assertEquals("c", result.get(2)); } public void testComaProblemStrikesBack() { String ex = "a.explanation = \"There is a coma, in here\""; ParserContext ctx = new ParserContext(); ExpressionCompiler compiler = new ExpressionCompiler(ex); Serializable s = compiler.compile(ctx); Base a = new Base(); Map variables = new HashMap(); variables.put("a", a); executeExpression(s, variables); assertEquals("There is a coma, in here", a.data); } public void testMultiVarDeclr() { String ex = "var a, b, c"; ParserContext ctx = new ParserContext(); ExpressionCompiler compiler = new ExpressionCompiler(ex); compiler.setVerifyOnly(true); compiler.compile(ctx); assertEquals(3, ctx.getVariables().size()); } public void testVarDeclr() { String ex = "var a"; ParserContext ctx = new ParserContext(); ExpressionCompiler compiler = new ExpressionCompiler(ex); compiler.setVerifyOnly(true); compiler.compile(ctx); assertEquals(1, ctx.getVariables().size()); } public void testMultiTypeVarDeclr() { String ex = "String a, b, c"; ParserContext ctx = new ParserContext(); ExpressionCompiler compiler = new ExpressionCompiler(ex); compiler.compile(ctx); assertNotNull(ctx.getVariables()); assertEquals(3, ctx.getVariables().entrySet().size()); for (Map.Entry entry : ctx.getVariables().entrySet()) { assertEquals(String.class, entry.getValue()); } } public void testMultiTypeVarDeclr2() { String ex = "String a = 'foo', b = 'baz', c = 'bar'"; ParserContext ctx = new ParserContext(); ExpressionCompiler compiler = new ExpressionCompiler(ex); compiler.compile(ctx); assertNotNull(ctx.getVariables()); assertEquals(3, ctx.getVariables().entrySet().size()); for (Map.Entry entry : ctx.getVariables().entrySet()) { assertEquals(String.class, entry.getValue()); } } public void testMultiTypeVarDeclr3() { String ex = "int a = 52 * 3, b = 8, c = 16;"; ParserContext ctx = new ParserContext(); ExpressionCompiler compiler = new ExpressionCompiler(ex); Serializable s = compiler.compile(ctx); assertNotNull(ctx.getVariables()); assertEquals(3, ctx.getVariables().entrySet().size()); for (Map.Entry entry : ctx.getVariables().entrySet()) { assertEquals(Integer.class, entry.getValue()); } Map vars = new HashMap(); executeExpression(s, vars); assertEquals(52 * 3, vars.get("a")); assertEquals(8, vars.get("b")); assertEquals(16, vars.get("c")); } public void testTypeVarDeclr() { String ex = "String a;"; ParserContext ctx = new ParserContext(); ExpressionCompiler compiler = new ExpressionCompiler(ex); compiler.compile(ctx); assertNotNull(ctx.getVariables()); assertEquals(1, ctx.getVariables().entrySet().size()); for (Map.Entry entry : ctx.getVariables().entrySet()) { assertEquals(String.class, entry.getValue()); } } public static interface Services { public final static String A_CONST = "Hello World"; public void log(String text); } public void testStringConcatenation() { // debugging MVEL code, it seems that MVEL 'thinks' that the result of the expression: // "Drop +5%: "+$sb+" avg: $"+$av+" price: $"+$pr // is a double, and as so, he looks for a method: // Services.log( double ); // but finds only: // Services.log( String ); // raising the error. String ex = "services.log( \"Drop +5%: \"+$sb+\" avg: $\"+$av+\" price: $\"+$pr );"; ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("$sb", String.class); ctx.addInput("$av", double.class); ctx.addInput("$pr", double.class); ctx.addInput("services", Services.class); try { ExpressionCompiler compiler = new ExpressionCompiler(ex); compiler.compile(ctx); } catch (Throwable e) { e.printStackTrace(); fail("Should not raise exception: " + e.getMessage()); } } public void testStringConcatenation2() { String ex = "services.log( $cheese + \" some string \" );"; ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("$cheese", Cheese.class); ctx.addInput("services", Services.class); try { ExpressionCompiler compiler = new ExpressionCompiler(ex); compiler.compile(ctx); } catch (Throwable e) { e.printStackTrace(); fail("Should not raise exception: " + e.getMessage()); } } public void testMapsWithVariableAsKey() { String ex = "aMap[aKey] == 'aValue'"; ParserContext ctx = new ParserContext(); ctx.setStrongTyping(false); ExpressionCompiler compiler = new ExpressionCompiler(ex); compiler.setVerifyOnly(true); compiler.compile(ctx); Set requiredInputs = compiler.getParserContextState().getInputs().keySet(); assertTrue(requiredInputs.contains("aMap")); assertTrue(requiredInputs.contains("aKey")); } public static void testProjectionUsingThis() { Set records = new HashSet(); for (int i = 0; i < 53; i++) { Bean2 record = new Bean2(i); records.add(record); } Object result = MVEL.eval("(_prop in this)", records); System.out.println("result: " + result); } public static final class Bean2 { public final int _prop; public Bean2(int prop_) { _prop = prop_; } public int getProp() { return _prop; } public String toString() { return Integer.toString(_prop); } } public void testUnaryOpNegation1() { assertEquals(false, test("!new Boolean(true)")); } public void testUnaryOpNegation2() { assertEquals(true, test("!isdef _foozy_")); } public class Az { public void foo(String s) { } } public class Bz extends Az { } public void testJIRA151() { OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE); Bz b = new Bz(); ParserContext context = new ParserContext(); Object expression = MVEL.compileExpression("a.foo(value)", context); Map variables = new HashMap(); variables.put("a", b); variables.put("value", 123); for (int i = 0; i < 100; i++) { System.out.println("i: " + i); System.out.flush(); executeExpression(expression, variables); } } public void testJIRA151b() { OptimizerFactory.setDefaultOptimizer("ASM"); Bz b = new Bz(); ParserContext context = new ParserContext(); Object expression = MVEL.compileExpression("a.foo(value)", context); Map variables = new HashMap(); variables.put("a", b); variables.put("value", 123); for (int i = 0; i < 100; i++) { System.out.println("i: " + i); System.out.flush(); executeExpression(expression, variables); } } public void testJIRA151c() { OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE); A b = new B(); A c = new C(); ParserContext context = new ParserContext(); Object expression = MVEL.compileExpression("a.foo(value)", context); for (int i = 0; i < 100; i++) { System.out.println("i: " + i); System.out.flush(); { Map variables = new HashMap(); variables.put("a", b); variables.put("value", 123); executeExpression(expression, variables); } { Map variables = new HashMap(); variables.put("a", c); variables.put("value", 123); executeExpression(expression, variables); } } } public void testJIRA151d() { OptimizerFactory.setDefaultOptimizer("ASM"); A b = new B(); A c = new C(); ParserContext context = new ParserContext(); Object expression = MVEL.compileExpression("a.foo(value)", context); for (int i = 0; i < 100; i++) { System.out.println("i: " + i); System.out.flush(); { Map variables = new HashMap(); variables.put("a", b); variables.put("value", 123); executeExpression(expression, variables); } { Map variables = new HashMap(); variables.put("a", c); variables.put("value", 123); executeExpression(expression, variables); } } } public void testJIRA153() { assertEquals(false, MVEL.eval("!(true)")); assertEquals(false, executeExpression(MVEL.compileExpression("!(true)"))); } public void testJIRA154() { Map m = createTestMap(); m.put("returnTrue", MVEL.getStaticMethod(CoreConfidenceTests.class, "returnTrue", new Class[0])); assertEquals(false, MVEL.eval("!returnTrue()", m)); } public void testJIRA154b() { ParserContext pctx = new ParserContext(); pctx.addImport("returnTrue", MVEL.getStaticMethod(CoreConfidenceTests.class, "returnTrue", new Class[0])); assertEquals(false, executeExpression(MVEL.compileExpression("!(returnTrue())", pctx))); } public void testJIRA155() { ParserContext pctx = new ParserContext(); pctx.addImport("returnTrue", MVEL.getStaticMethod(CoreConfidenceTests.class, "returnTrue", new Class[0])); assertEquals(true, executeExpression(MVEL.compileExpression("!true || returnTrue()", pctx))); } public void testJIRA155b() { ParserContext pctx = new ParserContext(); pctx.addImport("returnTrue", MVEL.getStaticMethod(CoreConfidenceTests.class, "returnTrue", new Class[0])); assertEquals(true, executeExpression(MVEL.compileExpression("!(!true || !returnTrue())", pctx))); } public void testJIRA156() throws Throwable { ClassProvider provider = new ClassProvider(); provider.getPrivate().foo(); PublicClass.class.getMethod("foo").invoke(provider.getPrivate()); String script = "provider.getPrivate().foo()"; HashMap vars = new HashMap(); vars.put("provider", provider); MVEL.eval(script, vars); } public void testJIRA156b() throws Throwable { ClassProvider provider = new ClassProvider(); provider.getPrivate().foo(); PublicClass.class.getMethod("foo").invoke(provider.getPrivate()); String script = "provider.getPrivate().foo()"; Serializable s = MVEL.compileExpression(script); HashMap vars = new HashMap(); vars.put("provider", provider); OptimizerFactory.setDefaultOptimizer("reflective"); executeExpression(s, vars); OptimizerFactory.setDefaultOptimizer("ASM"); executeExpression(s, vars); } public void testJIRA156c() throws Throwable { ClassProvider provider = new ClassProvider(); provider.getPublic().foo(); PublicClass.class.getMethod("foo").invoke(provider.getPublic()); String script = "provider.getPublic().foo()"; Serializable s = MVEL.compileExpression(script); HashMap vars = new HashMap(); vars.put("provider", provider); MVEL.eval(script, vars); OptimizerFactory.setDefaultOptimizer("reflective"); executeExpression(s, vars); OptimizerFactory.setDefaultOptimizer("ASM"); executeExpression(s, vars); } public static boolean returnTrue() { return true; } public static class TestHelper { public static void method(int id, Object[] arr) { System.out.println(id + " -> " + arr.length); } public static void method(Object obj1, Object obj2) { System.out.println(obj1 + "-> " + obj2); } public static Calendar minDate() { return Calendar.getInstance(); } public static Calendar maxDate() { return Calendar.getInstance(); } } public static class Fooz { public Fooz(String id) { } } public void testArray() { String ex = " TestHelper.method(1, new String[]{\"a\", \"b\"});\n" + " TestHelper.method(2, new String[]{new String(\"a\"), new String(\"b\")});\n" + " TestHelper.method(3, new Fooz[]{new Fooz(\"a\"), new Fooz(\"b\")});"; ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addImport(TestHelper.class); ctx.addImport(Fooz.class); ExpressionCompiler compiler = new ExpressionCompiler(ex); OptimizerFactory.setDefaultOptimizer("ASM"); CompiledExpression expr = compiler.compile(ctx); executeExpression(expr); OptimizerFactory.setDefaultOptimizer("reflective"); expr = compiler.compile(ctx); executeExpression(expr); } public void testArray2() { String ex = " TestHelper.method(1, {\"a\", \"b\"});\n" + " TestHelper.method(2, {new String(\"a\"), new String(\"b\")});\n" + " TestHelper.method(3, {new Fooz(\"a\"), new Fooz(\"b\")});"; ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addImport(TestHelper.class); ctx.addImport(Fooz.class); ExpressionCompiler compiler = new ExpressionCompiler(ex); OptimizerFactory.setDefaultOptimizer("ASM"); CompiledExpression expr = compiler.compile(ctx); executeExpression(expr); OptimizerFactory.setDefaultOptimizer("reflective"); expr = compiler.compile(ctx); executeExpression(expr); } public void testJIRA165() { OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE); A b = new B(); A a = new A(); ParserContext context = new ParserContext(); Object expression = MVEL.compileExpression("a.bar(value)", context); for (int i = 0; i < 100; i++) { System.out.println("i: " + i); System.out.flush(); { Map variables = new HashMap(); variables.put("a", b); variables.put("value", 123); executeExpression(expression, variables); } { Map variables = new HashMap(); variables.put("a", a); variables.put("value", 123); executeExpression(expression, variables); } } } public void testJIRA165b() { OptimizerFactory.setDefaultOptimizer("ASM"); A b = new B(); A a = new A(); ParserContext context = new ParserContext(); Object expression = MVEL.compileExpression("a.bar(value)", context); for (int i = 0; i < 100; i++) { System.out.println("i: " + i); System.out.flush(); { Map variables = new HashMap(); variables.put("a", b); variables.put("value", 123); executeExpression(expression, variables); } { Map variables = new HashMap(); variables.put("a", a); variables.put("value", 123); executeExpression(expression, variables); } } } public void testJIRA166() { Object v = MVEL.eval("import java.util.regex.Matcher; import java.util.regex.Pattern;" + " if (Pattern.compile(\"hoge\").matcher(\"hogehogehoge\").find()) { 'foo' } else { 'bar' }", new HashMap()); assertEquals("foo", v); } public static class Beano { public String getProperty1() { return null; } public boolean isProperty2() { return true; } public boolean isProperty3() { return false; } } public void testJIRA167() { Map context = new HashMap(); context.put("bean", new Beano()); MVEL.eval("bean.property1==null?bean.isProperty2():bean.isProperty3()", context); } public void testJIRA168() { boolean before = MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL; try { Map st = new HashMap(); st.put("__fact__", new ArrayList()); st.put("__expected__", 0); String expressionNaked = "__fact__.size == __expected__"; String expressionNonNaked = "__fact__.size() == __expected__"; MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true; // the following works fine ParserContext ctx = new ParserContext(); for (Map.Entry entry : st.entrySet()) { ctx.addInput(entry.getKey(), entry.getValue().getClass()); } CompiledExpression expr = new ExpressionCompiler(expressionNaked).compile(ctx); Boolean result = (Boolean) executeExpression(expr, st); assertTrue(result); // the following works fine result = (Boolean) MVEL.eval(expressionNonNaked, st); assertTrue(result); // the following fails result = (Boolean) MVEL.eval(expressionNaked, st); assertTrue(result); } finally { MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = before; } } public void testJIRA170() { OptimizerFactory.setDefaultOptimizer("reflective"); List staticDispatch = Arrays.asList(2, 1, 0); List multimethodDispatch = Arrays.asList(3, 2, 1); // invokeJIRA170("Dynamic", ctxJIRA170(false, false), varsJIRA170(), multimethodDispatch); // invokeJIRA170("Strict", ctxJIRA170(true, false), varsJIRA170(), multimethodDispatch); invokeJIRA170("Strong", ctxJIRA170(false, true), varsJIRA170(), staticDispatch); } public void testJIRA170b() { OptimizerFactory.setDefaultOptimizer("ASM"); List staticDispatch = Arrays.asList(2, 1, 0); List multimethodDispatch = Arrays.asList(3, 2, 1); // invokeJIRA170("Dynamic", ctxJIRA170(false, false), varsJIRA170(), multimethodDispatch); // invokeJIRA170("Strict", ctxJIRA170(true, false), varsJIRA170(), multimethodDispatch); invokeJIRA170("Strong", ctxJIRA170(false, true), varsJIRA170(), staticDispatch); } public void invokeJIRA170(String name, ParserContext pctx, Map vars, Collection expected) { Serializable expression = MVEL.compileExpression("x.remove((Object) y); x ", pctx); Object result = executeExpression(expression, vars); assertTrue(String.format("%s Expected %s, Got %s", name, expected, result), expected.equals(result)); result = executeExpression(expression, vars); assertTrue(String.format("%s Expected %s, Got %s", name, expected, result), expected.equals(result)); } private Map varsJIRA170() { Map vars = new HashMap(); vars.put("x", new ArrayList(Arrays.asList(3, 2, 1, 0))); vars.put("y", 3); return vars; } private ParserContext ctxJIRA170(boolean strictTypeEnforcement, boolean strongTyping) { ParserContext ctx = new ParserContext(); // ctx.setStrictTypeEnforcement(strictTypeEnforcement); ctx.setStrongTyping(strongTyping); ctx.addInput("x", Collection.class, new Class[]{Integer.class}); ctx.addInput("y", Integer.class); return ctx; } public static class JIRA167Step { public String getParent() { return null; } } public static class JIRA167Node { public boolean isServer() { return true; } } public void testJIRA167b() { Map context = new HashMap(); context.put("current", new JIRA167Step()); context.put("node", new JIRA167Node()); MVEL.eval("current.parent==null?node.isServer():(node==current.parent.node)", context); } public void testJIRA167c() { MVEL.eval("true?true:(false)"); } public void testJIRA174() { Serializable s = MVEL.compileExpression("def test(a1) { java.util.Collection a = a1; a.clear(); a.add(1); a.add(2); a.add(3); a.remove(2); a; }\n" + "a = test(new java.util.ArrayList());\n" + "b = test(new java.util.HashSet());"); Map vars = new HashMap(); executeExpression(s, vars); assertEquals(false, ((Collection) vars.get("a")).contains(2)); assertEquals(2, ((Collection) vars.get("a")).size()); assertEquals(false, ((Collection) vars.get("b")).contains(2)); assertEquals(2, ((Collection) vars.get("b")).size()); } public void testJIRA176() { Map innerMap = new HashMap(); innerMap.put("testKey[MyValue=newValue]", "test"); Map vars = new HashMap(); vars.put("mappo", innerMap); assertEquals("test", MVEL.eval("mappo['testKey[MyValue=newValue]']", vars)); } public void testJIRA176b() { Map innerMap = new HashMap(); innerMap.put("testKey[MyValue=newValue]", "test"); Map vars = new HashMap(); vars.put("mappo", innerMap); Serializable s = MVEL.compileExpression("mappo['testKey[MyValue=newValue]']"); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals("test", executeExpression(s, vars)); s = MVEL.compileExpression("mappo['testKey[MyValue=newValue]']"); OptimizerFactory.setDefaultOptimizer("ASM"); assertEquals("test", executeExpression(s, vars)); } public void testRandomSomething() { Foo foo = new Foo(); foo.setName("foo1"); Foo foo2 = new Foo(); foo2.setName("foo2"); MVEL.setProperty(foo, "name", 5); Serializable s = MVEL.compileExpression("name.toUpperCase()", ParserContext.create().stronglyTyped().withInput("name", String.class)); Object _return = executeExpression(s, foo); System.out.println("returned value: " + String.valueOf(_return)); _return = executeExpression(s, foo2); System.out.println("returned value: " + String.valueOf(_return)); } public static class ProcessManager { public void startProcess(String name, Map variables) { System.out.println("Process started"); } } public static class KnowledgeRuntimeHelper { public ProcessManager getProcessManager() { return new ProcessManager(); } } public void testDeepMethodNameResolution() { String expression = "variables = [ \"symbol\" : \"RHT\" ]; \n" + "drools.getProcessManager().startProcess(\"id\", variables );"; // third pass ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("drools", KnowledgeRuntimeHelper.class); Map vars = new HashMap(); vars.put("drools", new KnowledgeRuntimeHelper()); Serializable expr = MVEL.compileExpression(expression, ctx); executeExpression(expr, vars); } public void testJIRA183() { String exp1 = "int end = 'attribute'.indexOf('@'); if(end == -1)" + " { end = 'attribute'.length()} 'attribute'.substring(0, end);"; Object val1 = MVEL.eval(exp1, new HashMap()); String exp2 = "int end = 'attribute'.indexOf('@'); if(end == -1)" + " { end = 'attribute'.length() } 'attribute'.substring(0, end);"; Object val2 = MVEL.eval(exp2, new HashMap()); } public void testContextAssignments() { Foo foo = new Foo(); MVEL.eval("this.name = 'bar'", foo); assertEquals("bar", foo.getName()); } public void testMVEL187() { ParserContext context = new ParserContext(); context.addPackageImport("test"); context.addInput("outer", Outer.class); Object compiled = MVEL.compileExpression( "outer.getInner().getValue()", context); Map vars = new HashMap(); vars.put("outer", new Outer()); VariableResolverFactory varsResolver = new MapVariableResolverFactory(vars); assertEquals(2, executeExpression(compiled, varsResolver)); } public void testMVEL190() { ParserContext context = new ParserContext(); context.addImport(Ship.class); context.addImport(MapObject.class); context.addInput("obj", MapObject.class); Object compiled = MVEL.compileExpression( "((Ship) obj).getName()", context); Map vars = new HashMap(); vars.put("obj", new Ship()); VariableResolverFactory varsResolver = new MapVariableResolverFactory(vars); System.out.println( executeExpression(compiled, varsResolver)); } public void testMVEL190a() { Serializable compiled = MVEL.compileExpression("a.toString()", ParserContext.create().stronglyTyped().withInput("a", String.class)); } public void testGenericInference() { String expression = "$result = person.footributes[0].name"; ParserContext ctx; MVEL.analysisCompile(expression, ctx = ParserContext.create().stronglyTyped().withInput("person", Person.class)); assertEquals(String.class, ctx.getVarOrInputTypeOrNull("$result")); Serializable s = MVEL.compileExpression(expression, ParserContext.create().stronglyTyped().withInput("person", Person.class)); Map vars = new HashMap(); Person p = new Person(); p.setFootributes(new ArrayList()); p.getFootributes().add(new Foo()); vars.put("person", p); assertEquals("dog", executeExpression(s, vars)); } public void testGenericInference2() { ParserContext ctx; MVEL.analysisCompile("$result = person.maptributes['fooey'].name", ctx = ParserContext.create().stronglyTyped().withInput("person", Person.class)); assertEquals(String.class, ctx.getVarOrInputTypeOrNull("$result")); } public void testRegExSurroundedByBrackets() { Map map = new HashMap(); map.put("x", "foobie"); assertEquals(Boolean.TRUE, MVEL.eval("x ~= ('f.*')", map)); } public void testMethodScoring() { OptimizerFactory.setDefaultOptimizer("ASM"); ParserConfiguration pconf = new ParserConfiguration(); for (Method m : StaticMethods.class.getMethods()) { if (Modifier.isStatic(m.getModifiers())) { pconf.addImport(m.getName(), m); } } pconf.addImport("TestCase", TestCase.class); ParserContext pctx = new ParserContext(pconf); Map vars = new HashMap(); // this is successful TestCase.assertTrue(StaticMethods.is(StaticMethods.getList(java.util.Formatter.class))); // this also should be fine Serializable expr = MVEL.compileExpression("TestCase.assertTrue( is( getList( java.util.Formatter ) ) )", pctx); executeExpression(expr, vars); } public static class StaticMethods { public static boolean is(List arg) { return true; } public static boolean is(Collection arg) { throw new RuntimeException("Wrong method called"); } public static List getList(Class arg) { ArrayList result = new ArrayList(); result.add(arg); return result; } } public void testStrictTypingCompilationWithVarInsideConstructor() { ParserContext ctx = new ParserContext(); ctx.addInput("$likes", String.class); ctx.addInput("results", List.class); ctx.addImport(Cheese.class); ctx.setStrongTyping(true); Serializable expr = null; try { expr = MVEL.compileExpression("Cheese c = new Cheese( $likes, 15 );\nresults.add( c ); ", ctx); } catch (CompileException e) { e.printStackTrace(); fail("This should not fail:\n" + e.getMessage()); } List results = new ArrayList(); Map vars = new HashMap(); vars.put("$likes", "stilton"); vars.put("results", results); executeExpression(expr, vars); assertEquals(new Cheese("stilton", 15), results.get(0)); } public void testSetterViaDotNotation() { TestClass tc = new TestClass(); tc.getExtra().put("test", "value"); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); String expression = "extra.test"; Serializable compiled = MVEL.compileSetExpression(expression, ctx); MVEL.executeSetExpression(compiled, tc, "value2"); assertEquals("value2", tc.getExtra().get("test")); } public void testSetterViaMapNotation() { TestClass tc = new TestClass(); tc.getExtra().put("test", "value"); ParserContext ctx = new ParserContext(); ctx.withInput("this", TestClass.class); ctx.setStrongTyping(true); String expression = "extra[\"test\"]"; Serializable compiled = MVEL.compileSetExpression(expression, tc.getClass(), ctx); MVEL.executeSetExpression(compiled, tc, "value3"); assertEquals("value3", tc.getExtra().get("test")); } public void testGetterViaDotNotation() { TestClass tc = new TestClass(); tc.getExtra().put("test", "value"); Map vars = new HashMap(); vars.put("tc", tc); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("tc", tc.getClass()); String expression = "tc.extra.test"; Serializable compiled = MVEL.compileExpression(expression, ctx); String val = (String) executeExpression(compiled, vars); assertEquals("value", val); } public void testGetterViaMapNotation() { TestClass tc = new TestClass(); tc.getExtra().put("test", "value"); Map vars = new HashMap(); vars.put("tc", tc); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("tc", tc.getClass()); String expression = "tc.extra[\"test\"]"; Serializable compiled = MVEL.compileExpression(expression, ctx); String val = (String) executeExpression(compiled, vars); assertEquals("value", val); } public void testGetterViaMapGetter() { TestClass tc = new TestClass(); tc.getExtra().put("test", "value"); Map vars = new HashMap(); vars.put("tc", tc); ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addInput("tc", tc.getClass()); String expression = "tc.extra.get(\"test\")"; Serializable compiled = MVEL.compileExpression(expression, ctx); String val = (String) executeExpression(compiled, vars); assertEquals("value", val); } public void testJIRA209() { Map vars = new LinkedHashMap(); vars.put("bal", new BigDecimal("999.99")); String[] testCases = { // "bal < 100 or bal > 200", // "bal < 100 || bal > 200", "bal > 200 or bal < 100", "bal > 200 || bal < 100", "bal < 100 and bal > 200", "bal < 100 && bal > 200", "bal > 200 and bal < 100", "bal > 200 && bal < 100" }; Object val1, val2; for (String expr : testCases) { System.out.println("Evaluating '" + expr + "': ......"); val1 = MVEL.eval(expr, vars); // System.out.println("'" + expr + " ' = " + ret.toString()); assertNotNull(val1); Serializable compiled = MVEL.compileExpression(expr); val2 = executeExpression(compiled, vars); // System.out.println("'" + expr + " ' = " + ret.toString()); assertNotNull(val2); assertEquals("expression did not evaluate correctly: " + expr, val1, val2); } } public void testConstructor() { String ex = " TestHelper.method(new Person('bob', 30), new Person('mark', 40, 999, 55, 10));\n"; ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addImport(TestHelper.class); ctx.addImport(Person.class); // un-comment the following line to see how MVEL is converting the int argument 40 into a // string and then executing the wrong constructor on the Person class try { MVEL.compileExpression(ex, ctx); fail("Constructor should not have been found."); } catch (CompileException e) { // yay. } // fail( "The Person constructor used in the expression does not exist, so an error should have been raised during compilation." ); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/DebuggerTests.java0000644000175000017500000004403211173714542025417 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import static org.mvel2.MVEL.parseMacros; import org.mvel2.MVELRuntime; import org.mvel2.Macro; import org.mvel2.ParserContext; import org.mvel2.ast.ASTNode; import org.mvel2.ast.WithNode; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.debug.DebugTools; import static org.mvel2.debug.DebugTools.decompile; import org.mvel2.debug.Debugger; import org.mvel2.debug.Frame; import org.mvel2.integration.Interceptor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.tests.core.res.Cheese; import org.mvel2.tests.core.res.Foo; import java.util.HashMap; import java.util.Map; public class DebuggerTests extends AbstractTest { private static int count; private static int a1 = 0; private static int a4 = 0; public void testDebuggerInvoke() { count = 0; MVELRuntime.resetDebugger(); MVELRuntime.setThreadDebugger(new Debugger() { public int onBreak(Frame frame) { if (frame.getFactory().isResolveable("a1")) { a1++; } if (frame.getFactory().isResolveable("a4")) { a4++; System.out.println("HEI " + frame.getLineNumber()); } count++; return 0; } }); String src = "a1=7;\na2=8;\na3=9;\na4=10;\na5=11;\na6=12;\na7=13;\na8=14;"; ExpressionCompiler c = new ExpressionCompiler(src); ParserContext ctx = new ParserContext(); ctx.setSourceFile("mysource"); ctx.setDebugSymbols(true); CompiledExpression compexpr = c.compile(ctx); System.out.println(decompile(compexpr)); MVELRuntime.registerBreakpoint(ctx.getSourceFile(), 1); MVELRuntime.registerBreakpoint(ctx.getSourceFile(), 3); MVELRuntime.registerBreakpoint(ctx.getSourceFile(), 7); VariableResolverFactory factory = new DefaultLocalVariableResolverFactory(); MVEL.executeDebugger(compexpr, null, factory); System.out.println(a1); System.out.println(a4); System.out.println(count); assertEquals(2, a1); assertEquals(1, a4); // test passes but the breakpoint should be received by line 7, not by line 3 assertEquals(3, count); // three breakpoints FAILS } public void testDebuggerInvoke2() { count = 0; MVELRuntime.resetDebugger(); MVELRuntime.setThreadDebugger(new Debugger() { public int onBreak(Frame frame) { count++; return 0; } }); String src = "a1=7;\na2=8;\nSystem.out.println(\"h\");\nac=23;\nde=23;\nge=23;\ngef=34;"; ExpressionCompiler c = new ExpressionCompiler(src); ParserContext ctx = new ParserContext(); ctx.setSourceFile("mysource"); ctx.setDebugSymbols(true); CompiledExpression compexpr = c.compile(ctx); System.out.println(decompile(compexpr)); MVELRuntime.registerBreakpoint(ctx.getSourceFile(), 1); MVELRuntime.registerBreakpoint(ctx.getSourceFile(), 2); MVELRuntime.registerBreakpoint(ctx.getSourceFile(), 3); MVELRuntime.registerBreakpoint(ctx.getSourceFile(), 4); MVELRuntime.registerBreakpoint(ctx.getSourceFile(), 5); VariableResolverFactory factory = new DefaultLocalVariableResolverFactory(); MVEL.executeDebugger(compexpr, null, factory); System.out.println(count); assertEquals(5, count); } public void testBreakpoints() { ExpressionCompiler compiler = new ExpressionCompiler("a = 5;\nb = 5;\n\nif (a == b) {\n\nSystem.out.println('Good');\nreturn a + b;\n}\n"); System.out.println("-------\n" + compiler.getExpression() + "\n-------\n"); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test.mv"); ctx.setDebugSymbols(true); CompiledExpression compiled = compiler.compile(ctx); MVELRuntime.registerBreakpoint("test.mv", 7); Debugger testDebugger = new Debugger() { public int onBreak(Frame frame) { System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]"); return 0; } }; MVELRuntime.setThreadDebugger(testDebugger); assertEquals(10, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap()))); } public void testBreakpoints2() { ExpressionCompiler compiler = new ExpressionCompiler("System.out.println('test the debugger');\n a = 0;"); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test.mv"); ctx.setDebugSymbols(true); CompiledExpression compiled = compiler.compile(ctx); } public void testBreakpoints3() { String expr = "System.out.println( \"a1\" );\n" + "System.out.println( \"a2\" );\n" + "System.out.println( \"a3\" );\n" + "System.out.println( \"a4\" );\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.addImport("System", System.class); context.setStrictTypeEnforcement(true); context.setDebugSymbols(true); context.setSourceFile("mysource"); String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(context)); System.out.println("output: " + s); int fromIndex = 0; int count = 0; while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) { count++; } assertEquals(4, count); } public void testBreakpointsAcrossWith() { String line1 = "System.out.println( \"a1\" );\n"; String line2 = "c = new Cheese();\n"; String line3 = "with ( c ) { type = 'cheddar',\n" + " price = 10 };\n"; String line4 = "System.out.println( \"a1\" );\n"; String expr = line1 + line2 + line3 + line4; System.out.println(expr); ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.addImport("System", System.class); context.addImport("Cheese", Cheese.class); context.setStrictTypeEnforcement(true); context.setDebugSymbols(true); context.setSourceFile("mysource"); String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(context)); System.out.println("output: " + s); int fromIndex = 0; int count = 0; while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) { count++; } assertEquals(5, count); } public void testBreakpointsAcrossComments() { String expression = "/** This is a comment\n" + // 1 " * Second comment line\n" + // 2 " * Third Comment Line\n" + // 3 " */\n" + // 4 "System.out.println('4');\n" + // 5 "System.out.println('5');\n" + // 6 "a = 0;\n" + // 7 "b = 1;\n" + // 8 "a + b"; // 9 ExpressionCompiler compiler = new ExpressionCompiler(expression); System.out.println("Expression:\n------------"); System.out.println(expression); System.out.println("------------"); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test2.mv"); ctx.setDebugSymbols(true); CompiledExpression compiled = compiler.compile(ctx); MVELRuntime.registerBreakpoint("test2.mv", 9); Debugger testDebugger = new Debugger() { public int onBreak(Frame frame) { System.out.println("Breakpoint Encountered [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]"); System.out.println("vars:" + frame.getFactory().getKnownVariables()); System.out.println("Resume Execution"); return 0; } }; MVELRuntime.setThreadDebugger(testDebugger); assertEquals(1, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap()))); } public void testBreakpointsAcrossComments2() { ExpressionCompiler compiler = new ExpressionCompiler( "// This is a comment\n" + // 1 "//Second comment line\n" + // 2 "//Third Comment Line\n" + // 3 "\n" + // 4 "//Test\n" + // 5 "System.out.println('4');\n" + // 6 "//System.out.println('5'); \n" + // 7 "a = 0;\n" + // 8 "b = 1;\n" + // 9 " a + b"); // 10 ParserContext ctx = new ParserContext(); ctx.setSourceFile("test2.mv"); ctx.setDebugSymbols(true); CompiledExpression compiled = compiler.compile(ctx); MVELRuntime.registerBreakpoint("test2.mv", 6); MVELRuntime.registerBreakpoint("test2.mv", 8); MVELRuntime.registerBreakpoint("test2.mv", 9); MVELRuntime.registerBreakpoint("test2.mv", 10); Debugger testDebugger = new Debugger() { public int onBreak(Frame frame) { System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]"); return 0; } }; MVELRuntime.setThreadDebugger(testDebugger); assertEquals(1, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap()))); } public void testBreakpoints4() { String expression = "System.out.println('foo');\n" + "a = new Foo();\n" + "update (a) { name = 'bar' };\n" + "System.out.println('name:' + a.name);\n" + "return a.name;"; Map interceptors = new HashMap(); Map macros = new HashMap(); interceptors.put("Update", new Interceptor() { public int doBefore(ASTNode node, VariableResolverFactory factory) { ((WithNode) node).getNestedStatement().getValue(null, factory); System.out.println("fired update interceptor -- before"); return 0; } public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) { System.out.println("fired update interceptor -- after"); return 0; } }); macros.put("update", new Macro() { public String doMacro() { return "@Update with"; } }); expression = parseMacros(expression, macros); ExpressionCompiler compiler = new ExpressionCompiler(expression); ParserContext ctx = new ParserContext(); ctx.setDebugSymbols(true); ctx.setSourceFile("test2.mv"); ctx.addImport("Foo", Foo.class); ctx.setInterceptors(interceptors); CompiledExpression compiled = compiler.compile(ctx); System.out.println("\nExpression:------------"); System.out.println(expression); System.out.println("------------"); MVELRuntime.registerBreakpoint("test2.mv", 3); MVELRuntime.registerBreakpoint("test2.mv", 4); MVELRuntime.registerBreakpoint("test2.mv", 5); Debugger testDebugger = new Debugger() { public int onBreak(Frame frame) { System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]"); return 0; } }; MVELRuntime.setThreadDebugger(testDebugger); assertEquals("bar", MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap()))); } public void testBreakpoints5() { OptimizerFactory.setDefaultOptimizer("ASM"); String expression = "System.out.println('foo');\r\n" + "a = new Foo();\r\n" + "a.name = 'bar';\r\n" + "foo.happy();\r\n" + "System.out.println( 'name:' + a.name ); \r\n" + "System.out.println( 'name:' + a.name ); \r\n" + "System.out.println( 'name:' + a.name ); \r\n" + "return a.name;"; Map interceptors = new HashMap(); Map macros = new HashMap(); interceptors.put("Update", new Interceptor() { public int doBefore(ASTNode node, VariableResolverFactory factory) { ((WithNode) node).getNestedStatement().getValue(null, factory); System.out.println("fired update interceptor -- before"); return 0; } public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) { System.out.println("fired update interceptor -- after"); return 0; } }); macros.put("update", new Macro() { public String doMacro() { return "@Update with"; } }); expression = parseMacros(expression, macros); ExpressionCompiler compiler = new ExpressionCompiler(expression); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test2.mv"); ctx.setDebugSymbols(true); ctx.addImport("Foo", Foo.class); ctx.setInterceptors(interceptors); CompiledExpression compiled = compiler.compile(ctx); System.out.println("\nExpression:------------"); System.out.println(expression); System.out.println("------------"); System.out.println(DebugTools.decompile(compiled)); MVELRuntime.registerBreakpoint("test2.mv", 1); Debugger testDebugger = new Debugger() { public int onBreak(Frame frame) { System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]"); return Debugger.STEP_OVER; } }; MVELRuntime.setThreadDebugger(testDebugger); System.out.println("\n==RUN==\n"); assertEquals("bar", MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(createTestMap()))); } public void testDebugSymbolsWithWindowsLinedEndings() throws Exception { String expr = " System.out.println( \"a1\" );\r\n" + " System.out.println( \"a2\" );\r\n" + " System.out.println( \"a3\" );\r\n" + " System.out.println( \"a4\" );\r\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setDebugSymbols(true); ctx.setSourceFile("mysource"); String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(ctx)); System.out.println(s); int fromIndex = 0; int count = 0; while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) { count++; } assertEquals(4, count); } public void testDebugSymbolsWithUnixLinedEndings() throws Exception { String expr = " System.out.println( \"a1\" );\n" + " System.out.println( \"a2\" );\n" + " System.out.println( \"a3\" );\n" + " System.out.println( \"a4\" );\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setDebugSymbols(true); ctx.setSourceFile("mysource"); String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(ctx)); int fromIndex = 0; int count = 0; while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) { count++; } assertEquals(4, count); } public void testDebugSymbolsWithMixedLinedEndings() throws Exception { String expr = " System.out.println( \"a1\" );\n" + " System.out.println( \"a2\" );\r\n" + " System.out.println( \"a3\" );\n" + " System.out.println( \"a4\" );\r\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setDebugSymbols(true); ctx.setSourceFile("mysource"); String s = org.mvel2.debug.DebugTools.decompile(compiler.compile(ctx)); System.out.println(s); int fromIndex = 0; int count = 0; while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) { count++; } assertEquals(4, count); } public void testDebugSymbolsSingleStatement() { String ex = "System.out.println( Cheese.STILTON );"; ParserContext ctx = new ParserContext(); ctx.setStrongTyping(true); ctx.addImport( Cheese.class ); try { ExpressionCompiler compiler = new ExpressionCompiler(ex); CompiledExpression expr = compiler.compile(ctx); // executing the following line with a MVEL.executeExpression() works fine // but executeDebugger() fails MVEL.executeDebugger( expr, null, (VariableResolverFactory)null ); } catch (Throwable e) { e.printStackTrace(); fail("Should not raise exception: " + e.getMessage()); } } }mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/UtilsTests.java0000644000175000017500000000714211174146707024777 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import junit.framework.TestCase; import org.mvel2.MVEL; import org.mvel2.util.FastList; import org.mvel2.util.StringAppender; import java.util.HashMap; import java.util.List; import java.util.Map; public class UtilsTests extends TestCase { public void testMain() { assertEquals("foobarfoobar", new StringAppender().append("foo").append('b').append('a').append('r').append("foobar").toString()); } public void testMain2() { assertEquals("foo bar test 1 2 3foo bar test 1 2 3", new StringAppender(0).append("foo bar ").append("test").append(" 1 2 3") .append("foo bar").append(" ").append("test").append(" 1 2 3").toString()); } public void testMain3() { assertEquals("C:/projects/webcat/exploded/resources/productimages/", new StringAppender(10).append("C:/projects/webcat/exploded/") .append("resources/productimages/").toString()); } public void testFastList1() { FastList list = new FastList(3); list.add("One"); list.add("Two"); list.add("Three"); list.add("Five"); list.add(1, "Four"); String[] zz1 = {"One", "Four", "Two", "Three", "Five"}; int i = 0; for (Object o : list) { if (!zz1[i++].equals(o)) throw new AssertionError("problem with list!"); } list.remove(2); String[] zz2 = {"One", "Four", "Three", "Five"}; i = 0; for (Object o : list) { if (!zz2[i++].equals(o)) throw new AssertionError("problem with list!"); } } public void testAddToFastList() throws Exception { FastList fl = new FastList(0); assertEquals(0, fl.size()); // this throws an ArrayIndexOutOfBoundsException:0 fl.add("value"); assertEquals(1, fl.size()); } public void testAddAllFastList() throws Exception { FastList fl1 = new FastList(1); fl1.add("value1"); fl1.add("value2"); assertEquals(2, fl1.size()); FastList fl2 = new FastList(1); fl2.add("value3"); fl2.add("value4"); // the addAll results in a list of 2 instead of 4 that was expected fl1.addAll(fl2); assertEquals(4, fl1.size()); } public void testAddAllFastList2() throws Exception { FastList fl1 = new FastList(); fl1.add("value1"); fl1.add("value2"); FastList fl2 = new FastList(); fl2.add("value3"); fl2.add("value4"); fl1.addAll(fl2); assertEquals("value1", fl1.get(0)); assertEquals("value2", fl1.get(1)); assertEquals("value3", fl1.get(2)); // this results in null assertEquals("value4", fl1.get(3)); // this results in null } public void testAddAll2() { FastList flSource = new FastList(); flSource.add("value"); FastList flDest = new FastList(flSource.size()); flDest.addAll(flSource); // throws ArrayIndexOutOfBoundsException: 2 assertEquals("value", flDest.get(0)); } public void testFastListEval() throws Exception { Map map = new HashMap(); // The following throws a PropertyAccessException: // unable to resolve property: could not access property MVEL.eval("list = []; list.add('value')", map); assertEquals(1, ((List) map.get("list")).size()); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/MacroProcessorTest.java0000755000175000017500000002271211172704121026444 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import junit.framework.Assert; import junit.framework.TestCase; import org.mvel2.*; import static org.mvel2.MVEL.executeExpression; import static org.mvel2.MVEL.parseMacros; import org.mvel2.ast.ASTNode; import org.mvel2.ast.WithNode; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.debug.DebugTools; import org.mvel2.debug.Debugger; import org.mvel2.debug.Frame; import org.mvel2.integration.Interceptor; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.tests.core.res.Foo; import java.util.HashMap; import java.util.Map; public class MacroProcessorTest extends TestCase { private MacroProcessor macroProcessor; protected void setUp() throws Exception { super.setUp(); Map macros = new HashMap(); macros.put("insert", new Macro() { public String doMacro() { return "drools.insert"; } }); macroProcessor = new MacroProcessor(); macroProcessor.setMacros(macros); } public void testParseString() { String raw = " l.add( \"rule 2 executed \" + str);"; try { String result = macroProcessor.parse(raw); assertEquals(raw, result); } catch (Exception ex) { ex.printStackTrace(); fail("there shouldn't be any exception: " + ex.getMessage()); } } public void testParseConsequenceWithComments() { String raw = " // str is null, we are just testing we don't get a null pointer \n " + " list.add( p );"; try { String result = macroProcessor.parse(raw); assertEquals(raw, result); } catch (Exception ex) { ex.printStackTrace(); fail("there shouldn't be any exception: " + ex.getMessage()); } } public void testInfiniteLoop() { String str = ""; str += "int insuranceAmt = caseRate + (charges * pctDiscount / 100);\n"; str += "update (estimate); \n"; Map macros = new HashMap(); macros.put("update", new Macro() { public String doMacro() { return "drools.update"; } }); String result = parseMacros(str, macros); str = ""; str += "int insuranceAmt = caseRate + (charges * pctDiscount / 100);\n"; str += "drools.update (estimate);"; assertEquals(str, result); } public void testMacroSupport() { Map vars = new HashMap(); vars.put("foo", new Foo()); Map interceptors = new HashMap(); Map macros = new HashMap(); interceptors.put("Modify", new Interceptor() { public int doBefore(ASTNode node, VariableResolverFactory factory) { ((WithNode) node).getNestedStatement().getValue(null, factory); factory.createVariable("mod", "FOOBAR!"); return 0; } public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) { return 0; } }); macros.put("modify", new Macro() { public String doMacro() { return "@Modify with"; } }); ExpressionCompiler compiler = new ExpressionCompiler(parseMacros("modify (foo) { aValue = 'poo' }; mod", macros)); ParserContext ctx = new ParserContext(null, interceptors, null); ctx.setSourceFile("test.mv"); ctx.setDebugSymbols(true); assertEquals("FOOBAR!", executeExpression(compiler.compile(ctx), null, vars)); } public void testMacroSupportWithStrings() { Map vars = new HashMap(); Foo foo = new Foo(); vars.put("foo", foo); Map macros = new HashMap(); macros.put("modify", new Macro() { public String doMacro() { return "drools.modify"; } }); assertEquals("", foo.aValue); ExpressionCompiler compiler = new ExpressionCompiler(parseMacros("\"This is an modify()\"", macros)); ParserContext ctx = new ParserContext(null, null, null); ctx.setSourceFile("test.mv"); ctx.setDebugSymbols(true); assertEquals("This is an modify()", executeExpression(compiler.compile(ctx), null, vars)); } public void testMacroSupportWithDebugging() { Map vars = new HashMap(); vars.put("foo", new Foo()); Map interceptors = new HashMap(); Map macros = new HashMap(); interceptors.put("Modify", new Interceptor() { public int doBefore(ASTNode node, VariableResolverFactory factory) { ((WithNode) node).getNestedStatement().getValue(null, factory); factory.createVariable("mod", "FOOBAR!"); return 0; } public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) { return 0; } }); macros.put("modify", new Macro() { public String doMacro() { return "@Modify with"; } }); ExpressionCompiler compiler = new ExpressionCompiler( parseMacros( "System.out.println('hello');\n" + "System.out.println('bye');\n" + "modify (foo) { aValue = 'poo', \n" + " aValue = 'poo' };\n mod", macros) ); // compiler.setDebugSymbols(true); ParserContext ctx = new ParserContext(null, interceptors, null); ctx.setSourceFile("test.mv"); ctx.setDebugSymbols(true); CompiledExpression compiled = compiler.compile(ctx); MVELRuntime.setThreadDebugger(new Debugger() { public int onBreak(Frame frame) { System.out.println(frame.getSourceName() + ":" + frame.getLineNumber()); return Debugger.STEP; } }); MVELRuntime.registerBreakpoint("test.mv", 3); System.out.println(DebugTools.decompile(compiled )); Assert.assertEquals("FOOBAR!", MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(vars))); } public void testParseStringUnmatchedChars() { String raw = "result.add( \"\\\"\\\' there are } [ unmatched characters in this string (\" );"; try { String result = macroProcessor.parse(raw); assertEquals(raw, result); } catch (Exception ex) { ex.printStackTrace(); fail("there shouldn't be any exception: " + ex.getMessage()); } } public void testParseConsequenceWithFlowControlBlocks() { String raw = " // str is null, we are just testing we don't get a null pointer \n " + " if (l.x < 1) {\n" + " insert( new RuleLink(\"FIRST.INLET\" , comp, comp) );\n" + " } else {\n" + " insert( new RuleLink(\"FIRST.INLET.NOT\" , comp, comp) );\n" + " }\n" + " if( 1 < 2 ) { \n" + " insert( p ); \n" + " } else { \n" + " while( true ) {insert(x);}\n" + " }"; String expected = " // str is null, we are just testing we don't get a null pointer \n " + " if (l.x < 1) {\n" + " drools.insert( new RuleLink(\"FIRST.INLET\" , comp, comp) );\n" + " } else {\n" + " drools.insert( new RuleLink(\"FIRST.INLET.NOT\" , comp, comp) );\n" + " }\n" + " if( 1 < 2 ) { \n" + " drools.insert( p ); \n" + " } else { \n" + " while( true ) {drools.insert(x);}\n" + " }"; try { String result = macroProcessor.parse(raw); assertEquals(expected, result); } catch (Exception ex) { ex.printStackTrace(); fail("there shouldn't be any exception: " + ex.getMessage()); } } public void testCommentParsingWithMacro() { String raw = "/** This is a block comment **/ insert /** This is a second \n\nblock comment insert **/"; String expected = "/** This is a block comment **/ drools.insert /** This is a second \n\nblock comment insert **/"; try { String result = macroProcessor.parse(raw); assertEquals(expected, result); } catch (Exception ex) { ex.printStackTrace(); fail("there shouldn't be any exception: " + ex.getMessage()); } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/0000755000175000017500000000000011412747037022574 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Bar.java0000644000175000017500000000274311274117371024147 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.ArrayList; import java.util.List; public class Bar { private String name = "dog"; private boolean woof = true; private int age = 14; private String assignTest = ""; private List testList = new ArrayList(); private Integer[] intarray = new Integer[1]; public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isWoof() { return woof; } public void setWoof(boolean woof) { this.woof = woof; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isFoo(Object obj) { return obj instanceof Foo; } public String getAssignTest() { return assignTest; } public void setAssignTest(String assignTest) { this.assignTest = assignTest; } public List getTestList() { return testList; } public void setTestList(List testList) { this.testList = testList; } public String happy() { return "happyBar"; } public static int staticMethod() { return 1; } public Integer[] getIntarray() { return intarray; } public void setIntarray(Integer[] intarray) { this.intarray = intarray; } public boolean equals(Object o) { return o instanceof Bar; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/TestMVEL197.java0000644000175000017500000000074411323476635025314 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.HashMap; import java.util.Map; import org.mvel2.templates.TemplateRuntime; public class TestMVEL197 { private String name1; private String name2; public String getName1() { return name1; } public void setName1(String name1) { this.name1 = name1; } public String getName2() { return name2; } public void setName2(String name2) { this.name2 = name2; } }mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/AStatic.java0000644000175000017500000000020511073524603024757 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class AStatic { public static String Process(String arg) { return arg; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/User.java0000644000175000017500000000303511073524603024351 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.io.Serializable; public class User implements Serializable { private String firstName; private String lastName; public User() { } public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof User)) return false; User other = (User) obj; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; return true; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/PDFFieldUtil.java0000644000175000017500000000062211073524603025645 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.Calendar; import java.util.Date; public class PDFFieldUtil { public int calculateAge(Date gebDat) { long milliAge = System.currentTimeMillis() - gebDat.getTime(); Calendar geburtsTag = Calendar.getInstance(); geburtsTag.setTimeInMillis(milliAge); return geburtsTag.get(Calendar.YEAR) - 1970; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/MyClass.java0000644000175000017500000000076611172704121025011 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.EnumSet; import java.util.Set; public class MyClass implements MyInterface { private Set m_myEnumSet = EnumSet.noneOf(MY_ENUM.class); public boolean isType(MY_ENUM myenum) { return m_myEnumSet.contains(myenum); } public void setType(MY_ENUM myenum, boolean flag) { if (flag == true) { m_myEnumSet.add(myenum); } else { m_myEnumSet.remove(myenum); } } }mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/DefaultKnowledgeHelper.java0000644000175000017500000000134111073524603030015 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.ArrayList; import java.util.List; public class DefaultKnowledgeHelper implements KnowledgeHelper { private WorkingMemory workingMemory; public DefaultKnowledgeHelper() { } public DefaultKnowledgeHelper(WorkingMemory workingMemory) { this.workingMemory = workingMemory; } public WorkingMemory getWorkingMemory() { return this.workingMemory; } public List retracted = new ArrayList(); public void insert(Object object) { } public void retract(Object object) { retracted.add(object); } public void retract(FactHandle handle) { retracted.add(handle); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/PojoStatic.java0000644000175000017500000000051511073524603025512 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class PojoStatic { private String value; public PojoStatic(String value) { this.value = value; } public PojoStatic() { } public String getValue() { return value; } public void setValue(String string) { this.value = string; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Users.java0000644000175000017500000000157411073524603024542 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.List; public class Users { private List users; public List getUsers() { return users; } public void setUsers(List users) { this.users = users; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((users == null) ? 0 : users.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Users)) return false; Users other = (Users) obj; if (users == null) { if (other.users != null) return false; } else if (!users.equals(other.users)) return false; return true; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Foo.java0000644000175000017500000000266611073524603024167 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.Collection; public class Foo { private Bar bar = new Bar(); public String register; public String aValue = ""; public String bValue = ""; private String name = "dog"; private int countTest = 0; private Collection collectionTest; private SampleBean sampleBean = new SampleBean(); public void abc() { } public Bar getBar() { return bar; } public void setBar(Bar bar) { this.bar = bar; } public String happy() { return "happyBar"; } public String toUC(String s) { register = s; return s.toUpperCase(); } public int getNumber() { return 4; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection getCollectionTest() { return collectionTest; } public void setCollectionTest(Collection collectionTest) { this.collectionTest = collectionTest; } public SampleBean getSampleBean() { return sampleBean; } public void setSampleBean(SampleBean sampleBean) { this.sampleBean = sampleBean; } public int getCountTest() { return countTest; } public void setCountTest(int countTest) { this.countTest = countTest; } public boolean equals(Object o) { return o instanceof Foo; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/RuleBase.java0000644000175000017500000000020311073524603025127 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public interface RuleBase { public void removeRule(String pkgName, String ruleName); } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/DerivedClass.java0000644000175000017500000000012211073524603025775 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class DerivedClass extends Base { } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Model.java0000644000175000017500000000047411147332451024477 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class Model { private Column[] columns; public Model(Column[] columns) { this.columns = columns; } public Column[] getColumns() { return columns; } public void setColumns(Column[] columns) { this.columns = columns; } }mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/PresentationElements.java0000644000175000017500000000167611073524603027614 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.List; public class PresentationElements { private List names; public List getNames() { return names; } public void setNames(List names) { this.names = names; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((names == null) ? 0 : names.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof PresentationElements)) return false; PresentationElements other = (PresentationElements) obj; if (names == null) { if (other.names != null) return false; } else if (!names.equals(other.names)) return false; return true; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Cake.java0000644000175000017500000000042511272124620024272 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.Set; public class Cake { private Set ingredients; public Set getIngredients() { return ingredients; } public void setIngredients(Set ingredients) { this.ingredients = ingredients; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/TestClass.java0000644000175000017500000000047611332105653025344 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.HashMap; import java.util.Map; public class TestClass { private Map extra = new HashMap(); public Map getExtra() { return extra; } public void setExtra(Map extra) { this.extra = extra; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/MapObject.java0000644000175000017500000000013111274117371025274 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public interface MapObject { public int getId(); }mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Base.java0000644000175000017500000000472311172704121024305 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Base { public String data = "cat"; public String number = "101"; public List list; public String[] array; public List things; public Boolean fun = false; public String sentence = "The quick brown fox jumps over the lazy dog!"; public Foo foo = new Foo(); public boolean ackbar = false; public Map funMap = new HashMap(); public Map fooMap = new HashMap(); public String barfoo; public String defnull = null; public int sarahl; public Object[] testArray = new Object[]{new Foo(), new Bar()}; public String[] stringArray = new String[]{"hello", "there", "how", "are", "you"}; public int[] intArray = new int[]{5, 3, 2, 1, 0}; public Base() { this.list = new ArrayList(); list.add("Happy"); list.add("Happy!"); list.add("Joy"); list.add("Joy!"); this.array = (String[]) this.list.toArray(new String[this.list.size()]); things = new ArrayList(); things.add(new Thing("Bob")); things.add(new Thing("Smith")); things.add(new Thing("Cow")); funMap.put("foo", new Foo()); funMap.put("foo_bar", new Foo()); fooMap.put("foo", foo); } public Foo getFoo() { return foo; } public boolean equalityCheck(Object a, Object b) { return a.equals(b); } public void populate() { barfoo = "sarah"; } public String funMethod(String[] array) { return array[0]; } public int sum(int[] nums) { int sum = 0; for (int i : nums) sum += i; return sum; } public String readBack(String test) { return test; } public String appendTwoStrings(String a, String b) { return a + b; } public String getDATA() { return data; } public boolean ord(boolean val, int num) { System.out.println("num: " + num); return val; } public boolean equals(Object o) { return o instanceof Base; } public Map getFooMap() { return fooMap; } public int getIntValue() { return 10; } public void setExplanation(String data) { this.data = data; } public String getExplanation() { return this.data; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/RuleBaseImpl.java0000644000175000017500000000027711073524603025764 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class RuleBaseImpl implements RuleBase { public void removeRule(String pkgName, String ruleName) { } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Cheesery.java0000644000175000017500000000274211073524603025206 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class Cheesery { private String name; private Cheese cheese; public Cheesery(String name) { this(name, null); } public Cheesery(String name, Cheese cheese) { super(); this.name = name; this.cheese = cheese; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Cheese getCheese() { return cheese; } public void setCheese(Cheese cheese) { this.cheese = cheese; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cheese == null) ? 0 : cheese.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Cheesery other = (Cheesery) obj; if (cheese == null) { if (other.cheese != null) return false; } else if (!cheese.equals(other.cheese)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/SampleBean.java0000644000175000017500000000124711075175560025453 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.HashMap; import java.util.Map; public class SampleBean { private Map map = new HashMap(); private Map map2 = new HashMap(); public SampleBean() { map.put("bar", new Bar()); } public Object getProperty(String name) { return map.get(name); } public Object setProperty(String name, Object value) { map.put(name, value); return value; } public Map getMap2() { return map2; } public void setMap2(Map map2) { this.map2 = map2; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/KnowledgeHelperFixer.java0000644000175000017500000000434111073524603027511 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; /* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static org.mvel2.MVEL.parseMacros; import org.mvel2.Macro; import java.util.HashMap; import java.util.Map; public class KnowledgeHelperFixer { public String fix(final String raw) { if (raw == null) { return raw; } Map macros = new HashMap(5); macros.put("insert", new Macro() { public String doMacro() { return "drools.insert"; } }); macros.put("insertLogical", new Macro() { public String doMacro() { return "drools.insertLogical"; } }); macros.put("modifyRetract", new Macro() { public String doMacro() { return "drools.modifyRetract"; } }); macros.put("modifyInsert", new Macro() { public String doMacro() { return "drools.modifyInsert"; } }); macros.put("update", new Macro() { public String doMacro() { return "drools.update"; } }); macros.put("retract", new Macro() { public String doMacro() { return "drools.retract"; } }); return parseMacros(raw, macros); } }mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/KnowledgeHelper.java0000644000175000017500000000034211073524603026510 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public interface KnowledgeHelper { void insert(Object object); void retract(Object object); void retract(FactHandle handle); WorkingMemory getWorkingMemory(); } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Grid.java0000644000175000017500000000070411172704121024313 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; /** * Created by IntelliJ IDEA. * User: christopherbrock * Date: 19-Feb-2009 * Time: 12:39:15 PM * To change this template use File | Settings | File Templates. */ public class Grid { private Model model; public Grid(Model model) { this.model = model; } public Model getModel() { return model; } public void setModel(Model model) { this.model = model; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/MyEnum.java0000644000175000017500000000102411073524603024641 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public enum MyEnum { ALTERNATIVE("Alternative"), FULL_DOCUMENTATION("FullDocumentation"); private final String value; MyEnum(String v) { value = v; } public String value() { return value; } public static MyEnum fromValue(String v) { for (MyEnum c : MyEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/WorkingMemoryImpl.java0000644000175000017500000000050311073524603027063 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class WorkingMemoryImpl implements WorkingMemory { private RuleBase ruleBasae; public WorkingMemoryImpl(RuleBase ruleBasae) { super(); this.ruleBasae = ruleBasae; } public RuleBase getRuleBase() { return ruleBasae; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/TestInterface.java0000644000175000017500000000044011073524603026170 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; /** * Created by IntelliJ IDEA. * User: brockm * Date: Jun 22, 2007 * Time: 6:31:04 PM * To change this template use File | Settings | File Templates. */ public interface TestInterface { public String getName(); public boolean isFoo(); } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/res2/0000755000175000017500000000000011412747036023446 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/res2/PublicClass.java0000644000175000017500000000026411220461406026506 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res.res2; import java.io.Serializable; public class PublicClass implements Serializable { public void foo() { System.out.println("public!"); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/res2/Outer.java0000644000175000017500000000036011260412347025401 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res.res2; public class Outer { public Inner getInner() { return new Inner(); } public class Inner extends Object { public int getValue() { return 2; } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/res2/PrivateClass.java0000644000175000017500000000023311217724430026703 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res.res2; class PrivateClass extends PublicClass { @Override public void foo() { System.out.println("private!"); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/res2/ClassProvider.java0000644000175000017500000000034411220461406027061 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res.res2; public class ClassProvider { public PublicClass getPrivate() { return new PrivateClass(); } public PublicClass getPublic() { return new PublicClass(); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Cheese.java0000644000175000017500000000461511073524603024634 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.io.Serializable; import java.util.Date; /* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Cheese implements Serializable { public static final String STILTON = "stilton"; /** * */ private static final long serialVersionUID = -1187540653710115339L; private String type; private int price; private Date useBy; public Cheese() { } public Cheese(final String type, final int price) { super(); this.type = type; this.price = price; } public int getPrice() { return this.price; } public String getType() { return this.type; } public void setType(final String type) { this.type = type; } public void setPrice(final int price) { this.price = price; } public Date getUseBy() { return useBy; } public void setUseBy(Date useBy) { this.useBy = useBy; } public String toString() { return "Cheese( type='" + this.type + "', price=" + this.price + " )"; } public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + price; result = PRIME * result + ((type == null) ? 0 : type.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Cheese other = (Cheese) obj; if (price != other.price) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/MyInterface.java0000644000175000017500000000035711172704121025640 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public interface MyInterface { public enum MY_ENUM { ONE, TWO, THREE, FOUR } ; public boolean isType(MY_ENUM myenum); public void setType(MY_ENUM myenum, boolean flag); } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Column.java0000644000175000017500000000121411172704121024660 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; /** * Created by IntelliJ IDEA. * User: christopherbrock * Date: 19-Feb-2009 * Time: 12:32:25 PM * To change this template use File | Settings | File Templates. */ public class Column { private String name; private int length; public Column(String name, int length) { this.name = name; this.length = length; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/WorkingMemory.java0000644000175000017500000000015611073524603026245 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public interface WorkingMemory { public RuleBase getRuleBase(); } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Thing.java0000644000175000017500000000042711073524603024506 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class Thing { private String name; public Thing(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Ship.java0000644000175000017500000000031411274117371024336 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public class Ship extends Object implements MapObject { public int getId() { return 1; } public String getName() { return "Name"; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/SampleBeanAccessor.java0000644000175000017500000000260411073524603027126 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import org.mvel2.asm.MethodVisitor; import static org.mvel2.asm.Opcodes.CHECKCAST; import static org.mvel2.asm.Opcodes.INVOKEVIRTUAL; import org.mvel2.integration.PropertyHandler; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.optimizers.impl.asm.ProducesBytecode; public class SampleBeanAccessor implements PropertyHandler, ProducesBytecode { public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory) { return ((SampleBean) contextObj).getProperty(name); } public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value) { return ((SampleBean) contextObj).setProperty(name, value); } // implement the bytecode generation stubs to work with the JIT. public void produceBytecodeGet(MethodVisitor mv, String propertyName, VariableResolverFactory variableResolverFactory) { mv.visitTypeInsn(CHECKCAST, "org/mvel2/tests/core/res/SampleBean"); mv.visitLdcInsn(propertyName); mv.visitMethodInsn(INVOKEVIRTUAL, "org/mvel2/tests/core/res/SampleBean", "getProperty", "(Ljava/lang/String;)Ljava/lang/Object;"); } public void produceBytecodePut(MethodVisitor mv, String propertyName, VariableResolverFactory variableResolverFactory) { throw new RuntimeException("not implemented"); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/FactHandle.java0000644000175000017500000000016411073524603025424 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; public interface FactHandle { int getId(); Object getObject(); } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/res/Task.java0000644000175000017500000000307411073524603024340 0ustar drazzibdrazzibpackage org.mvel2.tests.core.res; import java.util.List; public class Task { private int priority; private List users; private List names; public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public List getUsers() { return users; } public void setUsers(List users) { this.users = users; } public List getNames() { return names; } public void setNames(List names) { this.names = names; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((names == null) ? 0 : names.hashCode()); result = prime * result + priority; result = prime * result + ((users == null) ? 0 : users.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Task)) return false; Task other = (Task) obj; if (names == null) { if (other.names != null) return false; } else if (!names.equals(other.names)) return false; if (priority != other.priority) return false; if (users == null) { if (other.users != null) return false; } else if (!users.equals(other.users)) return false; return true; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/FailureTests.java0000644000175000017500000000502011172704121025243 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import org.mvel2.ParserContext; import java.util.HashMap; /** * Tests to ensure MVEL fails when it should. */ public class FailureTests extends AbstractTest { public void testBadParserConstruct() { try { MVEL.eval("a = 0; a =+++ 5;"); } catch (RuntimeException e) { return; } assertTrue(false); } public void testShouldFail() { try { MVEL.eval("i = 0; i < 99 dksadlka", new HashMap()); } catch (Exception e) { return; } assertTrue(false); } public void testShouldFail2() { try { MVEL.compileExpression("i = 0; i < 99 dksadlka"); } catch (Exception e) { return; } assertTrue(false); } public void testShouldFail3() { try { MVEL.compileExpression("def foo() { 'bar' }; foo(123);"); } catch (Exception e) { e.printStackTrace(); return; } assertTrue(false); } public void testShouldFail4() { try { MVEL.eval("hour zzz", createTestMap()); } catch (Exception e) { return; } assertTrue(false); } public void testShouldFail5() { try { MVEL.eval("["); } catch (Exception e) { return; } assertTrue(false); } public void testShouldFail6() { try { ParserContext pctx = new ParserContext(); pctx.setStrongTyping(true); MVEL.compileExpression("new int[] {1.5}", pctx); } catch (Exception e) { return; } assertTrue(false); } public void testShouldFail7() { try { ParserContext pctx = new ParserContext(); pctx.setStrongTyping(true); MVEL.compileExpression("String x = 'foo'; int y = 2; new int[] { x, y }", pctx); } catch (Exception e) { // e.printStackTrace(); return; } assertTrue(false); } public void testShouldFail8() { try { ParserContext pCtx = new ParserContext(); pCtx.setStrongTyping(true); MVEL.compileExpression("for (String s : new java.util.HashMap()) { }", pCtx); } catch (Exception e) { // e.printStackTrace(); return; } assertTrue(false); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/MVELTest.java0000644000175000017500000000124611172704121024242 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import junit.framework.TestCase; import org.mvel2.MVEL; import java.io.File; import java.io.IOException; /** * @author yone098 */ public class MVELTest extends TestCase { private File file; public void setUp() { file = new File("samples/scripts/multibyte.mvel"); } /** * evalFile with encoding(workspace encoding utf-8) * * @throws IOException */ public void testEvalFile1() throws IOException { Object obj = MVEL.evalFile(file, "UTF-8"); assertEquals("?????", obj); // use default encoding obj = MVEL.evalFile(file); assertEquals("?????", obj); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/AbstractTest.java0000644000175000017500000006125711360202735025255 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.mvel2.DataConversion; import org.mvel2.MVEL; import static org.mvel2.MVEL.compileExpression; import static org.mvel2.MVEL.executeExpression; import org.mvel2.ParserContext; import org.mvel2.compiler.AbstractParser; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.debug.DebugTools; import static org.mvel2.debug.DebugTools.decompile; import org.mvel2.integration.impl.MapVariableResolverFactory; import static org.mvel2.optimizers.OptimizerFactory.setDefaultOptimizer; import org.mvel2.optimizers.dynamic.DynamicOptimizer; import org.mvel2.tests.core.res.Base; import org.mvel2.tests.core.res.DerivedClass; import org.mvel2.tests.core.res.Foo; import org.mvel2.tests.core.res.TestInterface; import org.mvel2.util.StringAppender; import java.io.*; import static java.lang.Integer.parseInt; import static java.lang.String.valueOf; import static java.lang.System.currentTimeMillis; import static java.lang.System.getProperty; import java.math.BigDecimal; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.*; public abstract class AbstractTest extends TestCase { static { // Modify the dynamic optimizer to ensure it always engages the JIT DynamicOptimizer.tenuringThreshold = 1; } private boolean silentTests = Boolean.getBoolean("mvel.tests.silent"); public void testNothing() { // to satify Eclipse and Surefire. } protected void setUp() throws Exception { } protected static Map createTestMap() { Map map = new HashMap(); map.put("foo", new Foo()); map.put("a", null); map.put("b", null); map.put("c", "cat"); map.put("BWAH", ""); map.put("misc", new MiscTestClass()); map.put("pi", "3.14"); map.put("hour", 60); map.put("zero", 0); map.put("array", new String[]{"", "blip"}); map.put("order", new Order()); map.put("$id", 20); map.put("five", 5); map.put("testImpl", new TestInterface() { public String getName() { return "FOOBAR!"; } public boolean isFoo() { return true; } }); map.put("derived", new DerivedClass()); map.put("ipaddr", "10.1.1.2"); map.put("dt1", new Date(currentTimeMillis() - 100000)); map.put("dt2", new Date(currentTimeMillis())); return map; } protected void tearDown() throws Exception { } protected Object test(final String ex) { Thread[] threads; if (Boolean.getBoolean("mvel.tests.quick")) { threads = new Thread[1]; } else if (getProperty("mvel.tests.threadcount") != null) { threads = new Thread[parseInt(getProperty("mvel.tests.threadcount"))]; } else { threads = new Thread[5]; } final Collection results = Collections.synchronizedCollection(new LinkedList()); long time = currentTimeMillis(); for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(new TestRunner(results, ex)); } if (!silentTests) { System.out.println("\n[test] begin test for:\n----------------------"); System.out.println(ex); System.out.println("----------------------"); } for (Thread thread1 : threads) { if (threads.length > 1) { System.out.println("Start Thread."); thread1.setPriority(Thread.MIN_PRIORITY); thread1.start(); } else { thread1.run(); } } if (threads.length > 1) { boolean threadsRunning = true; while (threadsRunning) { threadsRunning = false; for (Thread thread : threads) { if (thread.isAlive()) { System.out.println("Thread Alive."); threadsRunning = true; break; } } try { Thread.sleep(250); } catch (InterruptedException e) { break; } } } System.out.println("All threads have stopped."); System.out.println("Result Count: " + results.size()); // analyze results if (!silentTests) { System.out.println("[test] finished in: " + (currentTimeMillis() - time) + "ms (execution count: " + (threads.length * 8) + " [mixed modes])"); System.out.print("[test] analyzing results ... "); } Object last = null; if (!results.isEmpty()) { last = results.iterator().next(); if (last != null) { for (Object o : results) { if (o == null) { throw new AssertionError("differing result in multi-thread test (first array has: " + valueOf(last) + "; second has: " + valueOf(o) + ")"); } else if (!o.equals(last)) { if (o.getClass().isArray()) { // Object[] a1 = (Object[]) o; // Object[] a2 = (Object[]) last; // // if (a1.length == a2.length) { // for (int i = 0; i < a1.length; i++) { // if (a1[i] == null && a2[i] == null) { // continue; // } // else if (!a1[i].equals(a2[i])) { // throw new AssertionError("differing result in multi-thread test (first array has: " + valueOf(last) + "; second has: " + valueOf(o) + ")"); // } // } // } // else { // throw new AssertionError("differing result in multi-thread test: array sizes differ."); // } } else { throw new AssertionError("differing result in multi-thread test (last was: " + valueOf(last) + "; current is: " + valueOf(o) + ")"); } } last = o; } } } if (!silentTests) { System.out.println("good!"); } return last; } protected static class TestRunner implements Runnable { private Collection results; private String expression; public TestRunner(Collection results, String expression) { this.results = results; this.expression = expression; } public void run() { try { Object result = runSingleTest(expression); results.add(result); } catch (Throwable e) { System.out.println("thread terminating due to exception"); e.printStackTrace(); return; } } } protected static Object runSingleTest(final String ex) { return _test(ex); } protected static Object testCompiledSimple(String ex) { return MVEL.executeExpression(MVEL.compileExpression(ex)); } protected static Object testCompiledSimple(String ex, Map map) { return MVEL.executeExpression(MVEL.compileExpression(ex), map); } protected static Object testCompiledSimple(String ex, Object base, Map map) { return MVEL.executeExpression(MVEL.compileExpression(ex), base, map); } protected static Object _test(String ex) { ExpressionCompiler compiler = new ExpressionCompiler(ex); StringAppender failErrors = new StringAppender(); CompiledExpression compiled = compiler.compile(); Object first = null, second = null, third = null, fourth = null, fifth = null, sixth = null, seventh = null, eighth = null; System.out.println(DebugTools.decompile((Serializable) compiled)); if (!Boolean.getBoolean("mvel2.disable.jit")) { setDefaultOptimizer("ASM"); try { first = executeExpression(compiled, new Base(), createTestMap()); } catch (Exception e) { failErrors.append("\nFIRST TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } try { second = executeExpression(compiled, new Base(), createTestMap()); } catch (Exception e) { failErrors.append("\nSECOND TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } } try { third = MVEL.eval(ex, new Base(), createTestMap()); } catch (Exception e) { failErrors.append("\nTHIRD TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (first != null && !first.getClass().isArray()) { if (!first.equals(second)) { System.out.println(failErrors.toString()); throw new AssertionError("Different result from test 1 and 2 (Compiled Re-Run / JIT) [first: " + valueOf(first) + "; second: " + valueOf(second) + "]"); } if (!first.equals(third)) { if (failErrors != null) System.out.println(failErrors.toString()); throw new AssertionError("Different result from test 1 and 3 (Compiled to Interpreted) [first: " + valueOf(first) + " (" + (first != null ? first.getClass().getName() : null) + "); third: " + valueOf(third) + " (" + (third != null ? third.getClass().getName() : "null") + ")]"); } } setDefaultOptimizer("reflective"); Serializable compiled2 = compileExpression(ex); try { fourth = executeExpression(compiled2, new Base(), createTestMap()); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nFOURTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } try { fifth = executeExpression(compiled2, new Base(), createTestMap()); } catch (Exception e) { e.printStackTrace(); if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nFIFTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (fourth != null && !fourth.getClass().isArray()) { if (!fourth.equals(fifth)) { throw new AssertionError("Different result from test 4 and 5 (Compiled Re-Run X2) [fourth: " + valueOf(fourth) + "; fifth: " + valueOf(fifth) + "]"); } } ParserContext ctx = new ParserContext(); ctx.setSourceFile("unittest"); ctx.setDebugSymbols(true); ExpressionCompiler debuggingCompiler = new ExpressionCompiler(ex); // debuggingCompiler.setDebugSymbols(true); CompiledExpression compiledD = debuggingCompiler.compile(ctx); try { sixth = executeExpression(compiledD, new Base(), createTestMap()); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nSIXTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (sixth != null && !sixth.getClass().isArray()) { if (!fifth.equals(sixth)) { System.out.println("Payload 1 -- No Symbols: "); System.out.println(decompile(compiled)); System.out.println(); System.out.println("Payload 2 -- With Symbols: "); System.out.println(decompile(compiledD)); System.out.println(); throw new AssertionError("Different result from test 5 and 6 (Compiled to Compiled+DebuggingSymbols) [first: " + valueOf(fifth) + "; second: " + valueOf(sixth) + "]"); } } try { seventh = executeExpression(compiledD, new Base(), createTestMap()); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nSEVENTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (seventh != null && !seventh.getClass().isArray()) { if (!seventh.equals(sixth)) { throw new AssertionError("Different result from test 4 and 5 (Compiled Re-Run / Reflective) [first: " + valueOf(first) + "; second: " + valueOf(second) + "]"); } } try { Serializable xx = serializationTest(compiledD); AbstractParser.resetParserContext(); eighth = executeExpression(xx, new Base(), new MapVariableResolverFactory(createTestMap())); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nEIGHTH TEST (Serializability): { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (eighth != null && !eighth.getClass().isArray()) { if (!eighth.equals(seventh)) { throw new AssertionError("Different result from test 4 and 5 (Compiled Re-Run / Reflective) [first: " + valueOf(first) + "; second: " + valueOf(second) + "]"); } } if (failErrors.length() > 0) { System.out.println(decompile(compiledD)); throw new AssertionError("Detailed Failure Report:\n" + failErrors.toString()); } return fourth; } protected static Serializable serializationTest(Serializable s) throws Exception { File file = new File("./mvel_ser_test" + currentTimeMillis() + Math.round(Math.random() * 1000) + ".tmp"); InputStream inputStream = null; ObjectInputStream objectIn = null; try { file.createNewFile(); file.deleteOnExit(); FileOutputStream fileStream = new FileOutputStream(file); ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(fileStream)); objectOut.writeObject(s); objectOut.flush(); fileStream.flush(); fileStream.close(); inputStream = new BufferedInputStream(new FileInputStream(file)); objectIn = new ObjectInputStream(inputStream); return (Serializable) objectIn.readObject(); } finally { if (inputStream != null) inputStream.close(); if (objectIn != null) objectIn.close(); // file.delete(); } } public static class MiscTestClass { int exec = 0; @SuppressWarnings({"unchecked", "UnnecessaryBoxing"}) public List toList(Object object1, String string, int integer, Map map, List list) { exec++; List l = new ArrayList(); l.add(object1); l.add(string); l.add(new Integer(integer)); l.add(map); l.add(list); return l; } public int getExec() { return exec; } } public static class Bean { private Date myDate = new Date(); public Date getToday() { return new Date(); } public Date getNullDate() { return null; } public String getNullString() { return null; } public Date getMyDate() { return myDate; } public void setMyDate(Date myDate) { this.myDate = myDate; } } public static class Context { private final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy"); private Bean bean; public Bean getBean() { return bean; } public void setBean(Bean bean) { this.bean = bean; } public String formatDate(Date date) { return date == null ? null : dateFormat.format(date); } public String formatString(String str) { return str == null ? "" : str; } } public static class Person { private String name; private int age; private String likes; private List footributes; private Map maptributes; public Person() { } public Person(String name) { this.name = name; } public Person( String name, int age ) { this.name=name; this.age = age; } public Person( String name, String likes, int age) { this.name = name; this.likes = likes; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List getFootributes() { return footributes; } public void setFootributes(List footributes) { this.footributes = footributes; } public Map getMaptributes() { return maptributes; } public void setMaptributes(Map maptributes) { this.maptributes = maptributes; } public String toString() { return "Person( name=="+name+" age=="+age+" likes=="+likes+" )"; } } public static class Address { private String street; public Address(String street) { super(); this.street = street; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } public static class Drools { public void insert(Object obj) { } } public static class Model { private List latestHeadlines; public List getLatestHeadlines() { return latestHeadlines; } public void setLatestHeadlines(List latestHeadlines) { this.latestHeadlines = latestHeadlines; } } public static class Message { public static final int HELLO = 0; public static final int GOODBYE = 1; private List items = new ArrayList(); private String message; private int status; public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } public void addItem(Item item) { this.items.add(item); } public List getItems() { return items; } } public static class Item { private String name; public Item(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class ClassA { private Integer i; private double d; private String s; public Date date; private BigDecimal bigdec; private BigInteger bigint; public Integer getI() { return i; } public void setI(Integer i) { this.i = i; } public double getD() { return d; } public void setD(double d) { this.d = d; } public String getS() { return s; } public void setS(String s) { this.s = s; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public BigDecimal getBigdec() { return bigdec; } public void setBigdec(BigDecimal bigdec) { this.bigdec = bigdec; } public BigInteger getBigint() { return bigint; } public void setBigint(BigInteger bigint) { this.bigint = bigint; } } public class ClassB { private Integer i; private double d; private String s; public String date; private BigDecimal bigdec; private BigInteger bigint; public Integer getI() { return i; } public void setI(Integer i) { this.i = i; } public double getD() { return d; } public void setD(double d) { this.d = d; } public String getS() { return s; } public void setS(String s) { this.s = s; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public BigDecimal getBigdec() { return bigdec; } public void setBigdec(BigDecimal bigdec) { this.bigdec = bigdec; } public BigInteger getBigint() { return bigint; } public void setBigint(BigInteger bigint) { this.bigint = bigint; } } public static class Order { private int number = 20; public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } } public static void assertNumEquals(Object obj, Object obj2) { assertNumEquals(obj, obj2, true); } public static void assertNumEquals(Object obj, Object obj2, boolean permitRoundingVariance) { if (obj == null || obj2 == null) throw new AssertionError("null value"); if (obj.getClass().equals(obj2.getClass())) { if (obj instanceof Number) { double compare = ((Number) obj).doubleValue() - ((Number) obj2).doubleValue(); if (!(compare <= 0.0001d && compare >= -0.0001d)) { throw new AssertionFailedError("expected <" + String.valueOf(obj) + "> but was <" + String.valueOf(obj) + ">"); } } else { assertEquals(obj, obj2); } } else { obj = DataConversion.convert(obj, obj2.getClass()); if (!obj.equals(obj2)) { if (permitRoundingVariance) { obj = DataConversion.convert(obj, Integer.class); obj2 = DataConversion.convert(obj2, Integer.class); assertEquals(obj, obj2); } else { throw new AssertionFailedError("expected <" + String.valueOf(obj) + "> but was <" + String.valueOf(obj) + ">"); } } } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/core/FunctionsTest.java0000644000175000017500000000653211351236755025466 0ustar drazzibdrazzibpackage org.mvel2.tests.core; import org.mvel2.MVEL; import static org.mvel2.MVEL.executeExpression; import org.mvel2.ast.Function; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExpressionCompiler; import org.mvel2.optimizers.OptimizerFactory; import org.mvel2.util.CompilerTools; import static org.mvel2.util.CompilerTools.extractAllDeclaredFunctions; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Dhanji R. Prasanna (dhanji@gmail com) */ public class FunctionsTest extends AbstractTest { public final void testThatFunctionsCloseOverArguments() { final Object o = MVEL.eval( "def fun(x) { ($ in [1, 2, 3] if $ > x) }" + "" + "fun(0)", new HashMap() ); assertTrue(o instanceof List); assertEquals(Arrays.asList(1, 2, 3), o); } public void testFunctionDefAndCall() { assertEquals("FoobarFoobar", test("function heyFoo() { return 'Foobar'; };\n" + "return heyFoo() + heyFoo();")); } public void testFunctionDefAndCall2() { ExpressionCompiler compiler = new ExpressionCompiler("function heyFoo() { return 'Foobar'; };\n" + "return heyFoo() + heyFoo();"); Serializable s = compiler.compile(); Map m = extractAllDeclaredFunctions((CompiledExpression) s); assertTrue(m.containsKey("heyFoo")); OptimizerFactory.setDefaultOptimizer("reflective"); assertEquals("FoobarFoobar", executeExpression(s, new HashMap())); assertEquals("FoobarFoobar", executeExpression(s, new HashMap())); OptimizerFactory.setDefaultOptimizer("dynamic"); } public void testFunctionDefAndCall3() { assertEquals("FOOBAR", test("function testFunction() { a = 'foo'; b = 'bar'; a + b; }; testFunction().toUpperCase(); ")); } public void testFunctionDefAndCall4() { assertEquals("barfoo", test("function testFunction(input) { return input; }; testFunction('barfoo');")); } public void testFunctionDefAndCall5() { assertEquals(10, test("function testFunction(x, y) { return x + y; }; testFunction(7, 3);")); } public void testFunctionDefAndCall6() { assertEquals("foo", MVEL.eval("def fooFunction(x) x; fooFunction('foo')", new HashMap())); } public void testAnonymousFunction() { assertEquals("foobar", test("a = function { 'foobar' }; a();")); } public void testJIRA207() { String ex = "x = 0; y = 0;" + "def foo() { x = 1; System.out.println('Word up'); }\n" + "def bar() { y = 1; System.out.println('Peace out'); }\n" + "def doMany(fps) {\n" + "foreach(f : fps) { System.out.println(f); f(); }\n" + "}\n" + "doMany([foo,bar]);" + "x == 1 && y == 1;"; Boolean bool = (Boolean) MVEL.eval(ex, new HashMap()); assertTrue(bool); OptimizerFactory.setDefaultOptimizer("ASM"); Serializable s = MVEL.compileExpression(ex); bool = (Boolean) MVEL.executeExpression(s, new HashMap()); assertTrue(bool); OptimizerFactory.setDefaultOptimizer("dynamic"); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/perftests/0000755000175000017500000000000011412747035023070 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/perftests/NullOutputStream.java0000644000175000017500000000031611073524603027237 0ustar drazzibdrazzibpackage org.mvel2.tests.perftests; import java.io.IOException; import java.io.OutputStream; public class NullOutputStream extends OutputStream { public void write(int i) throws IOException { } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/perftests/CompiledPerformanceTests.java0000644000175000017500000000466111164070104030671 0ustar drazzibdrazzibpackage org.mvel2.tests.perftests; import org.mvel2.MVEL; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.tests.core.CoreConfidenceTests; import org.mvel2.tests.core.res.Bar; import org.mvel2.tests.core.res.Base; import org.mvel2.tests.core.res.Foo; import org.mvel2.util.ParseTools; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; public class CompiledPerformanceTests { protected Foo foo = new Foo(); protected Map map = new HashMap(); protected Base base = new Base(); public CompiledPerformanceTests() { foo.setBar(new Bar()); map.put("foo", foo); map.put("a", null); map.put("b", null); map.put("c", "cat"); map.put("BWAH", ""); map.put("misc", new CoreConfidenceTests.MiscTestClass()); map.put("pi", "3.14"); map.put("hour", "60"); map.put("zero", 0); } public void testQuickSort() throws IOException { Serializable s = MVEL.compileExpression(new String(ParseTools.loadFromFile(new File("samples/scripts/fquicksort.mvel")))); HashMap map = new HashMap(); MapVariableResolverFactory mvrf = new MapVariableResolverFactory(map); for (int i = 0; i < 1000000; i++) { MVEL.executeExpression(s, mvrf); mvrf.clear(); } // for (int x = 0; x < 4; x++) { // Serializable s = MVEL.compileSetExpression("tak.bar.name"); // long time = System.currentTimeMillis(); // // for (int i = 0; i < ITERATIONS; i++) { // MVEL.executeSetExpression(s, map, "foobie"); // } // // System.out.println("SET PERFORMANCE: " + (System.currentTimeMillis() - time)); // // time = System.currentTimeMillis(); // // s = MVEL.compileExpression("tak.bar.name"); // // for (int i = 0; i < ITERATIONS; i++) { // MVEL.executeExpression(s, map); // } // // System.out.println("GET PERFORMANCE: " + (System.currentTimeMillis() - time)); // // } } public void testQuickSort2() throws IOException { testQuickSort(); } public void testQuickSort3() throws IOException { testQuickSort(); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/perftests/SimpleTests.java0000644000175000017500000000430411326620474026211 0ustar drazzibdrazzibpackage org.mvel2.tests.perftests; import org.mvel2.MVEL; import org.mvel2.optimizers.dynamic.DynamicOptimizer; import org.mvel2.util.ParseTools; import org.mvel2.util.QuickSort; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.io.Serializable; import static java.lang.Runtime.getRuntime; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; public class SimpleTests { private static final double COUNT = 30000; public static void main(String[] args) throws IOException { PrintStream ps = System.out; try { for (int i = 0; i < 10000; i++) { testQuickSortMVEL(ps); } } catch (Throwable t) { t.printStackTrace(); } System.setOut(ps); } private static int tg = 0; private static void testQuickSortMVEL(PrintStream ps) throws IOException { double time; time = System.currentTimeMillis(); char[] sourceFile = ParseTools.loadFromFile(new File("samples/scripts/quicksort.mvel")); Serializable c = MVEL.compileExpression(sourceFile); Map vars = new HashMap(); DecimalFormat dc = new DecimalFormat("#.##"); for (int a = 0; a < 10000; a++) { vars.clear(); MVEL.executeExpression(c, vars); } ps.println("Result: " + (time = System.currentTimeMillis() - time)); ps.println("Rate : " + (COUNT / (time / 1000)) + " per second."); ps.println("FreeMem: " + dc.format((double) getRuntime().freeMemory() / (1024d * 1024d)) + "MB / TotalMem: " + dc.format((double) getRuntime().totalMemory() / (1024d * 1024d)) + "MB"); ps.println("TotalGarbaged: " + DynamicOptimizer.totalRecycled); } private static void testQuickSortNative(PrintStream ps) { double time; time = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { QuickSort.quickSort(new int[]{50, 20, 21, 209, 10, 77, 8, 9, 55, 73, 41, 99}); } ps.println("Result: " + (time = System.currentTimeMillis() - time)); ps.println("Rate : " + (COUNT / (time / 1000)) + " per second."); } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/perftests/InlineCollectionsPerformance.java0000644000175000017500000000674011073524603031536 0ustar drazzibdrazzibpackage org.mvel2.tests.perftests; import org.mvel2.MVEL; import org.mvel2.compiler.ExecutableAccessor; import org.mvel2.util.FastList; import java.util.List; public class InlineCollectionsPerformance { private static final int COUNT = 200000; public static void main(String[] args) { long time; for (int i = 0; i < 5; i++) { // time = System.currentTimeMillis(); // testJavaList(); // System.out.println("Java : " + (System.currentTimeMillis() - time)); // time = System.currentTimeMillis(); testOGNLList(); System.out.println("OGNL2.7 : " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); testMVELList(); System.out.println("MVEL : " + (System.currentTimeMillis() - time)); System.out.println(); } } // public static void testMVELList() { // // ExecutableAccessor s = (ExecutableAccessor) MVEL.compileExpression("['Foo':'Bar','Foo':'Bar','Foo':'Bar','Foo':'Bar','Foo':'Bar']"); // Map list; // s.getNode().getReducedValueAccelerated(null, null, null); // for (int i = 0; i < COUNT; i++) { // list = (Map) s.getNode().getAccessor().getValue(null, null, null); // // } // } // public static void testMVELList() { // // ExecutableAccessor s = (ExecutableAccessor) MVEL.compileExpression("{'Foo','Bar','Foo','Bar','Foo','Bar','Foo','Bar','Foo','Bar'}"); // Object[] list; // s.getNode().getReducedValueAccelerated(null, null, null); // for (int i = 0; i < COUNT; i++) { // list = (Object[]) s.getNode().getAccessor().getValue(null, null, null); // // // assert "Foo".equals(list.get(0)) && "Foo".equals(list.get(2)) && list.size() == 10; // } // } public static void testMVELList() { ExecutableAccessor s = (ExecutableAccessor) MVEL.compileExpression("['Foo','Bar','Foo','Bar','Foo','Bar','Foo','Bar','Foo','Bar']"); List list; s.getNode().getReducedValueAccelerated(null, null, null); for (int i = 0; i < COUNT; i++) { list = (List) s.getNode().getAccessor().getValue(null, null, null); assert "Foo".equals(list.get(0)) && "Foo".equals(list.get(2)) && list.size() == 10; } } public static void testOGNLList() { // OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null); // Node node; // try { // node = Ognl.compileExpression(context, null, "{'Foo','Bar','Foo','Bar','Foo','Bar','Foo','Bar','Foo','Bar'}"); // } // catch (Exception e) { // throw new RuntimeException(e); // } // // List list; // for (int i = 0; i < COUNT; i++) { // list = (List) node.getAccessor().get(null, null); // // assert "Foo".equals(list.get(0)) && "Foo".equals(list.get(2)) && list.size() == 10; // } } public static void testJavaList() { FastList list; for (int i = 0; i < COUNT; i++) { list = new FastList(10); list.add("Foo"); list.add("Bar"); list.add("Foo"); list.add("Bar"); list.add("Foo"); list.add("Bar"); list.add("Foo"); list.add("Bar"); list.add("Foo"); list.add("Bar"); assert "Foo".equals(list.get(0)) && "Bar".equals(list.get(1)) && list.size() == 10; } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/0000755000175000017500000000000011412747040023043 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/perfTest1.mv0000644000175000017500000000000011326620474025257 0ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/TemplateTests.java0000644000175000017500000005103711323476635026524 0ustar drazzibdrazzibpackage org.mvel2.tests.templates; import junit.framework.TestCase; import org.mvel2.CompileException; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.templates.CompiledTemplate; import org.mvel2.templates.SimpleTemplateRegistry; import org.mvel2.templates.TemplateCompiler; import static org.mvel2.templates.TemplateCompiler.compileTemplate; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.res.Node; import org.mvel2.tests.core.res.Bar; import org.mvel2.tests.core.res.Base; import org.mvel2.tests.core.res.Foo; import org.mvel2.tests.core.res.TestMVEL197; import org.mvel2.tests.templates.tests.res.TestPluginNode; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings({"AssertEqualsBetweenInconvertibleTypes"}) public class TemplateTests extends TestCase { private Map map = new HashMap(); private VariableResolverFactory vrf = new MapVariableResolverFactory(map); private Foo foo = new Foo(); private Base base = new Base(); public TemplateTests() { map.put("_foo_", "Foo"); map.put("_bar_", "Bar"); ArrayList list = new ArrayList(3); list.add("Jane"); list.add("John"); list.add("Foo"); map.put("arrayList", list); foo.setBar(new Bar()); map.put("foo", foo); map.put("a", null); map.put("b", null); map.put("c", "cat"); map.put("BWAH", ""); map.put("pi", "3.14"); map.put("hour", "60"); map.put("zero", 0); //noinspection UnnecessaryBoxing map.put("doubleTen", new Double(10)); map.put("variable_with_underscore", "HELLO"); map.put("testImpl", new TestInterface() { public String getName() { return "FOOBAR!"; } public boolean isFoo() { return true; } }); } public Object test(String template) { CompiledTemplate compiled = compileTemplate(template); return TemplateRuntime.execute(compiled, base, vrf); } public void testPassThru() { String s = "foobar!"; assertEquals("foobar!", test(s)); } public void testBasicParsing() { String s = "foo: @{_foo_}--@{_bar_}!"; assertEquals("foo: Foo--Bar!", test(s)); } public void testIfStatement() { String s = "@if{_foo_=='Foo'}Hello@end{}"; assertEquals("Hello", test(s)); } public void testIfStatement2() { String s = "@if{_foo_=='Bar'}Hello@else{_foo_=='Foo'}Goodbye@end{}"; assertEquals("Goodbye", test(s)); } public void testIfStatement3() { String s = "@if{_foo_=='Bar'}Hello@else{_foo_=='foo'}Goodbye@else{}Nope@end{}"; assertEquals("Nope", test(s)); } public void testIfStatement4() { String s = "@if{_foo_=='Foo'}Hello@else{_foo_=='foo'}Goodbye@else{}Nope@end{}End"; assertEquals("HelloEnd", test(s)); } public void testIfStatement5() { String s = "@if{_foo_=='foo'}Hello@end{}Goodbye"; assertEquals("Goodbye", test(s)); } public void testIfNesting() { String s = "@if{_foo_=='Foo'}Hello@if{_bar_=='Bar'}Bar@end{}@else{_foo_=='foo'}Goodbye@else{}Nope@end{}"; assertEquals("HelloBar", test(s)); } public void testForEach() { String s = "List:@foreach{item : arrayList}@{item}@end{}"; assertEquals("List:JaneJohnFoo", test(s)); } public void testForEachMulti() { String s = "Multi:@foreach{item : arrayList, item2 : arrayList}@{item}-@{item2}@end{','}:Multi"; assertEquals("Multi:Jane-Jane,John-John,Foo-Foo:Multi", test(s)); } public void testComplexTemplate() { String s = "@foreach{item : arrayList}@if{item[0] == 'J'}@{item}@end{}@end{}"; assertEquals("JaneJohn", test(s)); } public void testFileBasedEval() { assertEquals("Foo::Bar", TemplateRuntime.eval(new File("src/test/java/org/mvel2/tests/templates/templateTest.mv"), base, new MapVariableResolverFactory(map), null)); } public void testInclusionOfTemplateFile() { String s = "<<@include{'src/test/java/org/mvel2/tests/templates/templateTest.mv'}>>"; assertEquals("<>", test(s)); } public void testInclusionOfTemplateFile2() { String s = "<<@include{'src/test/java/org/mvel2/tests/templates/templateError.mv'}>>"; try { test(s); } catch (CompileException e) { System.out.println(e.toString() ); return; } assertTrue(false); } public void testForEachException1() { String s = "<<@foreach{arrayList}@{item}@end{}>>"; try { test(s); } catch (Exception e) { System.out.println(e.toString()); return; } assertTrue(false); } public void testForEachException2() { String s = "<<@foreach{item:arrayList}@{item}>>"; try { test(s); } catch (Exception e) { System.out.println(e.toString()); return; } assertTrue(false); } public void testTemplateFile() { String s = (String) TemplateRuntime.eval(new File("src/test/java/org/mvel2/tests/templates/templateIfTest.mv"), base, new MapVariableResolverFactory(map), null); System.out.println(s); } // public void testTemplateFile2() { // String s = (String) TemplateRuntime.eval(new File("src/test/java/org/mvel2/tests/templates/templateDeclareTest.mv"), // base, new MapVariableResolverFactory(map), null); // // System.out.println(s); // // } public void testInclusionOfNamedTemplate() { SimpleTemplateRegistry registry = new SimpleTemplateRegistry(); registry.addNamedTemplate("footemplate", compileTemplate("@{_foo_}@{_bar_}")); registry.addNamedTemplate("bartemplate", compileTemplate("@{_bar_}@{_foo_}")); String s = "@includeNamed{'footemplate'} :: @includeNamed{'bartemplate'}"; assertEquals("FooBar :: BarFoo", TemplateRuntime.eval(s, map, registry)); } @SuppressWarnings({"AssertEqualsBetweenInconvertibleTypes"}) public void testExpressions() { String s = "@{_foo_.length()}"; Object r = test(s); assertEquals(3, r); } public void testCode() { String s = "@code{a = 'foo'; b = 'bar'}@{a}@{b}"; assertEquals("foobar", test(s)); } public void testInlineDeclarations() { String s = "@declare{'fudge'}Hello @{name}!@end{}@includeNamed{'fudge'; name='John'} -- @includeNamed{'fudge'; name='Mary'}"; assertEquals("Hello John! -- Hello Mary!", test(s)); } public void testPluginNode() { Map> plugins = new HashMap>(); plugins.put("testNode", TestPluginNode.class); TemplateCompiler compiler = new TemplateCompiler("Foo:@testNode{}!!", plugins); CompiledTemplate compiled = compiler.compile(); assertEquals("Foo:THIS_IS_A_TEST!!", TemplateRuntime.execute(compiled)); } public void testComments() { assertEquals("Foo", test("@comment{ This section is commented }@{_foo_}")); } /** * Integration of old tests */ public void testPassThru2() { assertEquals("foo@bar.com", TemplateRuntime.eval("foo@bar.com", map)); } public void testMethodOnValue() { assertEquals("DOG", test("@{foo.bar.name.toUpperCase()}")); } public void testSimpleProperty() { assertEquals("dog", test("@{foo.bar.name}")); } public void testBooleanOperator() { assertEquals(true, test("@{foo.bar.woof == true}")); } public void testBooleanOperator2() { assertEquals(false, test("@{foo.bar.woof == false}")); } public void testTextComparison() { assertEquals(true, test("@{foo.bar.name == 'dog'}")); } public void testNETextComparison() { assertEquals(true, test("@{foo.bar.name != 'foo'}")); } public void testChor() { assertEquals("cat", test("@{a or b or c}")); } public void testChorWithLiteral() { assertEquals("fubar", test("@{a or 'fubar'}")); } public void testNullCompare() { assertEquals(true, test("@{c != null}")); } public void testAnd() { assertEquals(true, test("@{c != null && foo.bar.name == 'dog' && foo.bar.woof}")); } public void testMath() { assertEquals(188.4, test("@{pi * hour}")); } public void testTemplating() { assertEquals("dogDOGGIE133.5", test("@{foo.bar.name}DOGGIE@{hour*2.225+1-1}")); } public void testComplexAnd() { assertEquals(true, test("@{(pi * hour) > 0 && foo.happy() == 'happyBar'}")); } public void testModulus() { assertEquals(38392 % 2, test("@{38392 % 2}")); } public void testLessThan() { assertEquals(true, test("@{pi < 3.15}")); assertEquals(true, test("@{pi <= 3.14}")); assertEquals(false, test("@{pi > 3.14}")); assertEquals(true, test("@{pi >= 3.14}")); } public void testMethodAccess() { assertEquals("happyBar", test("@{foo.happy()}")); } public void testMethodAccess2() { assertEquals("FUBAR", test("@{foo.toUC('fubar')}")); } public void testMethodAccess3() { assertEquals(true, test("@{equalityCheck(c, 'cat')}")); } public void testMethodAccess4() { assertEquals(null, test("@{readBack(null)}")); } public void testMethodAccess5() { assertEquals("nulltest", test("@{appendTwoStrings(null, 'test')}")); } public void testMethodAccess6() { assertEquals(false, test("@{!foo.bar.isWoof()}")); } public void testNegation() { assertEquals(true, test("@{!fun && !fun}")); } public void testNegation2() { assertEquals(false, test("@{fun && !fun}")); } public void testNegation3() { assertEquals(true, test("@{!(fun && fun)}")); } public void testNegation4() { assertEquals(false, test("@{(fun && fun)}")); } public void testMultiStatement() { assertEquals(true, test("@{populate(); barfoo == 'sarah'}")); } public void testAssignment2() { assertEquals("sarah", test("@{populate(); blahfoo = barfoo}")); } public void testOr() { assertEquals(true, test("@{fun || true}")); } public void testLiteralPassThrough() { assertEquals(true, test("@{true}")); } public void testLiteralPassThrough2() { assertEquals(false, test("@{false}")); } public void testLiteralPassThrough3() { assertEquals(null, test("@{null}")); } public void testControlLoopList() { assertEquals("HappyHappy!JoyJoy!", test( "@foreach{item : list}" + "@{item}" + "@end{}" )); } public void testControlLoopArray() { assertEquals("Happy0Happy!1Joy2Joy!3", test( "@code{i=0}@foreach{item : array}" + "@{item}@{i++}" + "@end{}" )); } public void testMultiCollectionControlLoop() { assertEquals("0=Happy:Happy,1=Happy!:Happy!,2=Joy:Joy,3=Joy!:Joy!", test( "@code{i=0}@foreach{item : list, listItem : array}" + "@{i++}=@{item}:@{listItem}" + "@end{','}" )); } public void testControlLoopListMultiple() { for (int i = 0; i < 100; i++) { testControlLoopList(); } } public void testControlLoopArrayMultiple() { for (int i = 0; i < 100; i++) { testControlLoopArray(); } } public static interface TestInterface { public String getName(); public boolean isFoo(); } public void testControlLoop2() { assertEquals("HappyHappy!JoyJoy!", test( "@foreach{item : list}" + "@{item}" + "@end{}" )); } public void testControlLoop3() { assertEquals("HappyHappy!JoyJoy!", test( "@foreach{item : list }" + "@{item}" + "@end{}" )); } public void testIfStatement6() { assertEquals("sarah", test("@if{'fun' == 'fun'}sarah@end{}")); } public void testIfStatement7() { assertEquals("poo", test("@if{'fun' == 'bar'}sarah@else{}poo@end{}")); } public void testRegEx() { assertEquals(true, test("@{foo.bar.name ~= '[a-z].+'}")); } public void testRegExNegate() { assertEquals(false, test("@{!(foo.bar.name ~= '[a-z].+')}")); } public void testRegEx2() { assertEquals(true, test("@{foo.bar.name ~= '[a-z].+' && foo.bar.name != null}")); } public void testBlank() { assertEquals(true, test("@{'' == empty}")); } public void testBlank2() { assertEquals(true, test("@{BWAH == empty}")); } public void testTernary() { assertEquals("foobie", test("@{zero==0?'foobie':zero}")); } public void testTernary2() { assertEquals("blimpie", test("@{zero==1?'foobie':'blimpie'}")); } public void testTernary3() { assertEquals("foobiebarbie", test("@{zero==1?'foobie':'foobie'+'barbie'}")); } public void testTernary4() { assertEquals("no", test("@{ackbar ? 'yes' : 'no'}")); } public void testStrAppend() { assertEquals("foobarcar", test("@{'foo' + 'bar' + 'car'}")); } public void testStrAppend2() { assertEquals("foobarcar1", test("@{'foobar' + 'car' + 1}")); } public void testInstanceCheck1() { assertEquals(true, test("@{c is java.lang.String}")); } public void testInstanceCheck2() { assertEquals(false, test("@{pi is java.lang.Integer}")); } public void testBitwiseOr1() { assertEquals(6, test("@{2 | 4}")); } public void testBitwiseOr2() { assertEquals(true, test("@{(2 | 1) > 0}")); } public void testBitwiseOr3() { assertEquals(true, test("@{(2 | 1) == 3}")); } public void testBitwiseAnd1() { assertEquals(2, test("@{2 & 3}")); } public void testShiftLeft() { assertEquals(4, test("@{2 << 1}")); } public void testUnsignedShiftLeft() { assertEquals(2, test("@{-2 <<< 0}")); } public void testShiftRight() { assertEquals(128, test("@{256 >> 1}")); } public void testXOR() { assertEquals(3, test("@{1 ^ 2}")); } public void testContains1() { assertEquals(true, test("@{list contains 'Happy!'}")); } public void testContains2() { assertEquals(false, test("@{list contains 'Foobie'}")); } public void testContains3() { assertEquals(true, test("@{sentence contains 'fox'}")); } public void testContains4() { assertEquals(false, test("@{sentence contains 'mike'}")); } public void testContains5() { assertEquals(true, test("@{!(sentence contains 'mike')}")); } public void testTokenMethodAccess() { assertEquals(String.class, test("@{a = 'foo'; a.getClass()}")); } public void testArrayCreationWithLength() { assertEquals(2, test("@{Array.getLength({'foo', 'bar'})}")); } public void testMapCreation() { assertEquals("sarah", test("@{map = ['mike':'sarah','tom':'jacquelin']; map['mike']}")); } public void testProjectionSupport() { assertEquals(true, test("@{(name in things) contains 'Bob'}")); } public void testProjectionSupport2() { assertEquals(3, test("@{(name in things).size()}")); } public void testObjectInstantiation() { assertEquals("foobie", test("@{new java.lang.String('foobie')}")); } public void testObjectInstantiationWithMethodCall() { assertEquals("foobie", test("@{new String('foobie').toString()}")); } public void testObjectInstantiation2() { test("@{new String() is String}"); } public void testArrayCoercion() { assertEquals("gonk", test("@{funMethod( {'gonk', 'foo'} )}")); } public void testMapAccess() { assertEquals("dog", test("@{funMap['foo'].bar.name}")); } public void testMapAccess2() { assertEquals("dog", test("@{funMap.foo.bar.name}")); } public void testSoundex() { assertTrue((Boolean) test("@{'foobar' soundslike 'fubar'}")); } public void testSoundex2() { assertFalse((Boolean) test("@{'flexbar' soundslike 'fubar'}")); } public void testThisReference() { assertEquals(true, test("@{this}") instanceof Base); } public void testIfLoopInTemplate() { assertEquals("ONETWOTHREE", test("@foreach{item :things}@if{item.name=='Bob'}ONE@elseif{item.name=='Smith'}TWO@elseif{item.name=='Cow'}THREE@end{}@end{}")); } public void testStringEscaping() { assertEquals("\"Mike Brock\"", test("@{\"\\\"Mike Brock\\\"\"}")); } public void testStringEscaping2() { assertEquals("MVEL's Parser is Fast", test("@{'MVEL\\'s Parser is Fast'}")); } public void testNestedAtSymbol() { assertEquals("email:foo@foo.com", test("email:@{'foo@foo.com'}")); } public void testEscape() { assertEquals("foo@foo.com", test("foo@@@{'foo.com'}")); } public void testEvalNodes() { assertEquals("foo", test("@eval{\"@{'foo'}\"}")); } public void testIteration1() { List list = new ArrayList(); list.add("a1"); list.add("a2"); list.add("a3"); String template = "@foreach{item : list}a@end{}"; Map map = new HashMap(); map.put("list", list); String r = (String) TemplateRuntime.eval(template, map); System.out.println("r: " + r); assertEquals("aaa", r); } public void testIteration2() { Folder f1 = new Folder("f1", null); String template = "@{name} @foreach{item : children}a@end{}"; String r = (String) TemplateRuntime.eval(template, f1); System.out.println("r: " + r); } public void testIteration3() { Folder f = new Folder("a1", null); List list = f.getChildren(); String template = "@foreach{item : list}a@end{}"; Map map = new HashMap(); map.put("list", list); String r = (String) TemplateRuntime.eval(template, map); System.out.println("r: " + r); assertEquals("aaa", r); } public void testIteration4() { Folder f = new Folder("a1", null); String template = "@foreach{item : f.children}a@end{}"; Map map = new HashMap(); map.put("f", f); String r = (String) TemplateRuntime.eval(template, map); System.out.println("r: " + r); assertEquals("aaa", r); } public void testMVEL197() { Map context = new HashMap(); Object[] args = new Object[1]; TestMVEL197 test = new TestMVEL197(); test.setName1("name1"); test.setName2("name2"); args[0] = test; context.put("args", args); String template = "${(args[0].name1=='name1'&&args[0].name2=='name2')?'a':'b'}"; Object value = TemplateRuntime.eval(template, context); assertEquals("a", value); } public class Page { String name; Folder parent; public Page(String name, Folder parent) { this.name = name; this.parent = parent; } public String getName() { return name; } public Folder getParent() { return parent; } } public class Folder extends Page { public Folder(String name, Folder parent) { super(name, parent); } public List getChildren() { List list = new ArrayList(); list.add(new Page("a1", this)); list.add(new Page("a2", this)); list.add(new Page("a3", this)); return list; } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/templateIfTest.mv0000644000175000017500000000013710772721046026350 0ustar drazzibdrazzib@code{__a = 1; __b = 2; __c = 3}@if{__a == 1}@if{__b == 2}@if{__c == 3}Hello!@end{}@end{}@end{}mvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/tests/0000755000175000017500000000000011412747040024205 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/tests/res/0000755000175000017500000000000011412747040024776 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/tests/res/TestPluginNode.java0000644000175000017500000000133411164527565030562 0ustar drazzibdrazzibpackage org.mvel2.tests.templates.tests.res; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.templates.TemplateRuntime; import org.mvel2.templates.util.TemplateOutputStream; import org.mvel2.templates.res.Node; import org.mvel2.util.StringAppender; import java.io.PrintStream; import java.io.PrintWriter; public class TestPluginNode extends Node { public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) { appender.append("THIS_IS_A_TEST"); return next != null ? next.eval(runtime, appender, ctx, factory) : null; } public boolean demarcate(Node terminatingNode, char[] template) { return false; } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/templateTest.mv0000644000175000017500000000010710776262552026074 0ustar drazzibdrazzib@comment{ * * This is a simple template. * }@{_foo_}::@{_bar_}mvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/templateDeclareTest.mv0000644000175000017500000005026210776220614027354 0ustar drazzibdrazzib@declare{"getMethodBytecode"} public java.util.List getMethodBytecode() { org.drools.util.asm.MethodComparator.Tracer visit = new org.drools.util.asm.MethodComparator.Tracer("@{methodName}"); java.io.InputStream is = @{ruleClassName}.class.getClassLoader().getResourceAsStream( "@{package}.@{ruleClassName}".replace( '.', '/' ) + ".class" ); java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); byte[] data = new byte[1024]; int byteCount; try { while ( (byteCount = is.read( data, 0, 1024 )) > -1 ) { bos.write(data, 0, byteCount); } } catch ( java.io.IOException e ) { throw new org.drools.RuntimeDroolsException("Unable getResourceAsStream for Class '@{ruleClassName}' "); } org.drools.asm.ClassReader classReader = new org.drools.asm.ClassReader( bos.toByteArray() ); classReader.accept( visit, true ); org.drools.asm.util.TraceMethodVisitor trace = visit.getTrace(); return trace.getText(); } @end{} @declare{"hashCode"} public int hashCode() { return @{hashCode}; } @end{} @declare{"equals"} public boolean equals(Object object) { if (object == null ) { return false; } else if ( object == this ){ return true; } if ( ! (object instanceof org.drools.spi.CompiledInvoker) ) { return false; } org.drools.spi.CompiledInvoker other = ( org.drools.spi.CompiledInvoker ) object; return org.drools.util.asm.MethodComparator.compareBytecode( getMethodBytecode(), other.getMethodBytecode() ); } @end{} @declare{"returnValueInvoker"} package @{package}; public class @{invokerClassName} implements org.drools.spi.ReturnValueExpression, org.drools.spi.CompiledInvoker, java.io.Externalizable { private static final long serialVersionUID = 400L; public Object createContext() { return null; } public org.drools.spi.FieldValue evaluate(java.lang.Object object, org.drools.spi.Tuple tuple, org.drools.rule.Declaration[] previousDeclarations, org.drools.rule.Declaration[] localDeclarations, org.drools.WorkingMemory workingMemory, Object context ) throws Exception { @code{i0=0}@foreach{type : declarationTypes, declr : declarations} @{type} @{declr.identifier} = ( @{type} ) previousDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) tuple.get( previousDeclarations[@{i0}] ) ).getObject() ); @code{i0++} @end{} @if{readLocalsFromTuple} @code{i0=0}@foreach{type : localDeclarationTypes, declr : localDeclarations} @{type} @{declr.identifier} = ( @{type} ) localDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) tuple.get( localDeclarations[@{i0}] ) ).getObject() ); @code{i0++} @end{} @else{} @code{i0=0}@foreach{type : localDeclarationTypes, declr : localDeclarations} @{type} @{declr.identifier} = ( @{type} ) localDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, object ); @code{i0++} @end{} @end{} @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} return @{ruleClassName}.@{methodName}( @foreach{declr : declarations} @{declr.identifier} @end{","} @if{localDeclarations != empty && declarations != empty},@end{} @foreach{declr :localDeclarations} @{declr.identifier} @end{","}@if{globals != empty && (localDeclarations != empty || declarations != empty)},@end{} @foreach{identifier : globals}@{identifier} @end{","} ); } @includeNamed{"hashCode"} @includeNamed{"getMethodBytecode"} @includeNamed{"equals"} public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException { } } @end{} @declare{"predicateInvoker"} package @{package}; public class @{invokerClassName} implements org.drools.spi.PredicateExpression, org.drools.spi.CompiledInvoker, java.io.Externalizable { private static final long serialVersionUID = 400L; public Object createContext() { return null; } public boolean evaluate(java.lang.Object object, org.drools.spi.Tuple tuple, org.drools.rule.Declaration[] previousDeclarations, org.drools.rule.Declaration[] localDeclarations, org.drools.WorkingMemory workingMemory, Object context ) throws Exception { @code{i0=0}@foreach{type : declarationTypes, declr : declarations} @{type} @{declr.identifier} = ( @{type} ) previousDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) tuple.get( previousDeclarations[@{i0}] ) ).getObject() ); @code{i0++} @end{} @code{i0=0}@foreach{type : localDeclarationTypes, declr : localDeclarations} @{type} @{declr.identifier} = ( @{type} ) localDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, object ); @code{i0++} @end{} @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} return @{ruleClassName}.@{methodName}( @foreach{declr : declarations} @{declr.identifier} @end{","} @if{localDeclarations != empty && declarations != empty},@end{} @foreach{declr : localDeclarations} @{declr.identifier} @end{","}@if{globals != empty && (localDeclarations != empty || declarations != empty)},@end{} @foreach{identifier : globals}@{identifier} @end{","} ); } @includeNamed{"hashCode"} @includeNamed{"getMethodBytecode"} @includeNamed{"equals"} public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException { } } @end{} @declare{"evalInvoker"} package @{package}; public class @{invokerClassName} implements org.drools.spi.EvalExpression, org.drools.spi.CompiledInvoker, java.io.Externalizable { private static final long serialVersionUID = 400L; // no need for context public Object createContext() { return null; } public boolean evaluate(org.drools.spi.Tuple tuple, org.drools.rule.Declaration[] declarations, org.drools.WorkingMemory workingMemory, Object context ) throws Exception { @code{i0=0}@foreach{type : declarationTypes, declr : declarations} @{type} @{declr.identifier} = ( @{type} ) declarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) tuple.get( declarations[@{i0}] ) ).getObject() ); @code{i0++} @end{} @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} return @{ruleClassName}.@{methodName}( @foreach{declr : declarations} @{declr.identifier} @end{","} @if{globals != empty && declarations != empty},@end{} @foreach{identifier : globals}@{identifier} @end{","} ); } @includeNamed{"hashCode"} @includeNamed{"getMethodBytecode"} @includeNamed{"equals"} public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException { } } @end{} @declare{"accumulateInvoker"} package @{package}; import org.drools.asm.ClassReader; import org.drools.asm.util.TraceMethodVisitor; import org.drools.util.asm.MethodComparator.Tracer; import java.util.Collections; public class @{invokerClassName} implements org.drools.spi.Accumulator, org.drools.spi.CompiledInvoker { private static final long serialVersionUID = 400L; public Object createContext() { return new @{ruleClassName}.@{className}(); } public void init(java.lang.Object workingMemoryContext, java.lang.Object context, org.drools.spi.Tuple leftTuple, org.drools.rule.Declaration[] declarations, org.drools.WorkingMemory workingMemory) throws Exception { @code{i0=0}@foreach{type : declarationTypes, declr : declarations} @{type} @{declr.identifier} = ( @{type} ) declarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) leftTuple.get( declarations[@{i0}] ) ).getObject() ); @code{i0++} @end{} @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} ((@{ruleClassName}.@{className})context).init( @foreach{declr : declarations} @{declr.identifier}@end{","}@if{globals != empty && declarations != empty},@end{} @foreach{identifier : globals} @{identifier}@end{","} ); } public void accumulate(java.lang.Object workingMemoryContext, java.lang.Object context, org.drools.spi.Tuple leftTuple, org.drools.common.InternalFactHandle handle, org.drools.rule.Declaration[] declarations, org.drools.rule.Declaration[] innerDeclarations, org.drools.WorkingMemory workingMemory) throws Exception { @code{ i0 = 0 }@foreach{type : declarationTypes, declr : declarations} @{type} @{declr.identifier} = ( @{type} ) declarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) leftTuple.get( declarations[@{i0}] ) ).getObject() ); @code{ i0++ } @end{} @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} @if{isMultiPattern} @code{ i0 = 0 }@foreach{declr : innerDeclarations} @{declr.extractor.extractToClassName} @{declr.identifier} = (@{declr.extractor.extractToClassName}) innerDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) leftTuple.get( innerDeclarations[@{i0}] ) ).getObject() ); @code{ i0++ } @end{} @else{} @code{ i0 = 0 }@foreach{declr : innerDeclarations} @{declr.extractor.extractToClassName} @{declr.identifier} = (@{declr.extractor.extractToClassName}) innerDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, handle.getObject() ); @code{ i0++ } @end{} @end{} ((@{ruleClassName}.@{className})context).accumulate( workingMemory, innerDeclarations, handle.getObject()@if{declarations != empty},@end{} @foreach{declr : declarations} @{declr.identifier}@end{","}@if{globals != empty},@end{} @foreach{identifier: globals} @{identifier}@end{","}@if{innerDeclarations != empty},@end{} @foreach{declr : innerDeclarations} @{declr.identifier}@end{","}); } public void reverse(java.lang.Object workingMemoryContext, java.lang.Object context, org.drools.spi.Tuple leftTuple, org.drools.common.InternalFactHandle handle, org.drools.rule.Declaration[] declarations, org.drools.rule.Declaration[] innerDeclarations, org.drools.WorkingMemory workingMemory) throws Exception { @code{ i0 = 0 }@foreach{type : declarationTypes, declr : declarations} @{type} @{declr.identifier} = ( @{type} ) declarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) leftTuple.get( declarations[@{i0}] ) ).getObject() ); @code{ i0++ } @end{} @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} @if{isMultiPattern} @code{ i0 = 0}@foreach{declr : innerDeclarations} @{declr.extractor.extractToClassName} @{declr.identifier} = (@{declr.extractor.extractToClassName}) innerDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) leftTuple.get( innerDeclarations[@{i0}] ) ).getObject() ); @code{ i0++ } @end{} @else{} @code{ i0 = 0 }@foreach{declr : innerDeclarations} @{declr.extractor.extractToClassName} @{declr.identifier} = (@{declr.extractor.extractToClassName}) innerDeclarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, handle.getObject() ); @code{ i0++ } @end{} @end{} ((@{ruleClassName}.@{className})context).reverse( workingMemory, innerDeclarations, handle.getObject()@if{declarations != empty},@end{} @foreach{declr : declarations} @{declr.identifier}@end{","}@if{globals != empty},@end{} @foreach{identifier : globals} @{identifier}@end{","}@if{innerDeclarations != empty},@end{} @foreach{declr : innerDeclarations} @{declr.identifier}@end{","}); } public Object getResult(java.lang.Object workingMemoryContext, java.lang.Object context, org.drools.spi.Tuple leftTuple, org.drools.rule.Declaration[] declarations, org.drools.WorkingMemory workingMemory) throws Exception { @code{ i0 = 0 }@foreach{type : declarationTypes, declr : declarations} @{type} @{declr.identifier} = ( @{type} ) declarations[@{i0}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, ( (org.drools.common.InternalFactHandle) leftTuple.get( declarations[@{i0}] ) ).getObject() ); @code{ i0++ } @end{} @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} return ((@{ruleClassName}.@{className})context).getResult( @foreach{declr : declarations} @{declr.identifier}@end{","}@if{globals != empty && declarations != empty},@end{} @foreach{identifier : globals} @{identifier}@end{","} ); } public boolean supportsReverse() { return @{supportsReverse}; } public Object createWorkingMemoryContext() { return null; } @includeNamed{"hashCode"} @includeNamed("equals"} public java.util.List getMethodBytecode() { java.io.InputStream is = @{ruleClassName}.class.getClassLoader().getResourceAsStream( "@{package}.@{ruleClassName}".replace( '.', '/' ) + "$@{className}" + ".class" ); java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); byte[] data = new byte[1024]; int byteCount; try { while ( (byteCount = is.read( data, 0, 1024 )) > -1 ) { bos.write(data, 0, byteCount); } } catch ( java.io.IOException e ) { throw new org.drools.RuntimeDroolsException("Unable getResourceAsStream for Class '@{ruleClassName}$@{className}' "); } return Collections.singletonList( bos ); } public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException { } } @end{} @declare{"consequenceInvoker"} package @{package}; public class @{invokerClassName} implements org.drools.spi.Consequence, java.io.Externalizable { private static final long serialVersionUID = 400L; public void evaluate(org.drools.spi.KnowledgeHelper knowledgeHelper, org.drools.WorkingMemory workingMemory) throws Exception { org.drools.spi.Tuple tuple = knowledgeHelper.getTuple(); org.drools.rule.Rule rule = knowledgeHelper.getRule(); org.drools.rule.Declaration[] declarations = rule.getDeclarations(); @foreach{type : declarationTypes, declr : declarations, index : indexes, notPattern : notPatterns} org.drools.common.InternalFactHandle @{declr.identifier}__Handle__ = ( org.drools.common.InternalFactHandle ) tuple.get( knowledgeHelper.getDeclaration( declarations[@{index}].getIdentifier() ) ); @{type} @{declr.identifier} = ( @{type} ) declarations[@{index}].@{declr.nativeReadMethod.name}( (org.drools.common.InternalWorkingMemory) workingMemory, @{declr.identifier}__Handle__.getObject() ); @if{notPattern}@{declr.identifier}__Handle__ = (org.drools.common.InternalFactHandle) knowledgeHelper.getWorkingMemory().getFactHandle( @{declr.identifier} );@end{} @end{} @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} @{ruleClassName}.@{methodName} ( knowledgeHelper@if{declarations != empty},@end{} @foreach{declr : declarations} @{declr.identifier}, @{declr.identifier}__Handle__ @end{","}@if{globals != empty},@end{} @foreach{identifier : globals} @{identifier} @end{","} ); } public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException { } } @end{} @declare{"actionInvoker"} package @{package}; public class @{invokerClassName} implements org.drools.spi.Action, java.io.Externalizable { private static final long serialVersionUID = 400L; public void execute(org.drools.WorkingMemory workingMemory) throws Exception { @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} @{processClassName}.@{methodName} ( @foreach{identifier : globals} @{identifier} @end{","} ); } public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException { } } @end{} @declare{"returnValueEvaluatorInvoker"} package @{package}; public class @{invokerClassName} implements org.drools.spi.ReturnValueEvaluator, java.io.Externalizable { private static final long serialVersionUID = 400L; public Object evaluate(org.drools.WorkingMemory workingMemory) throws Exception { @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" ); @end{} return @{processClassName}.@{methodName} ( @foreach{identifier : globals} @{identifier} @end{","} ); } public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) throws java.io.IOException, java.lang.ClassNotFoundException { } } @end{} @includeNamed{"equals"}mvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/templateError.mv0000644000175000017500000000005010772721046026235 0ustar drazzibdrazzib @foreach{item : arrayList} @{ddo mvel-2.0.18.orig/src/test/java/org/mvel2/tests/templates/templateError2.mv0000644000175000017500000000003411301035750026306 0ustar drazzibdrazzib@{thisDoesntExist()} -- foo!mvel-2.0.18.orig/src/test/java/org/mvel2/tests/fuzz/0000755000175000017500000000000011412747040022043 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/tests/fuzz/Fuzzer.java0000644000175000017500000000624711172177004024204 0ustar drazzibdrazzibpackage org.mvel2.tests.fuzz; import org.mvel2.CompileException; import org.mvel2.MVEL; import org.mvel2.UnresolveablePropertyException; import org.mvel2.util.StringAppender; import java.io.IOException; import static java.lang.Math.random; import static java.lang.System.currentTimeMillis; import java.text.DecimalFormat; import java.util.Random; public class Fuzzer { private static final int MAX = 100000000; private static final int[] SALTS = {83, 301, 320, 102, 105, 993, 203, 102, 4904, 1202, 102, 303, 83, 1, 5, 85, 19, 20, 193, 669, 344, 901, 930, 12, 1, 1, 89, 61, 8392, 2, 2038, 9, 7, 10, 484, 2301}; private static final char[] CHAR_TABLE = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '[', '}', ']', ':', ';', '"', '\'', '<', ',', '>', '.', '?', '/', '`', ' ', '\t', '\n', '\r' }; public static void main(String[] args) throws IOException { DecimalFormat df = new DecimalFormat("###,###.##"); StringAppender append = new StringAppender(); int len; long start = currentTimeMillis(); long time; double rate; int seed; boolean flip = false; Random rand = new Random(System.currentTimeMillis()); Random rand1 = new Random(System.currentTimeMillis() + 1); Random rand2 = new Random(rand1.nextInt()); Random rand3 = new Random(rand.nextInt(SALTS.length - 1)); Random rand4 = new Random(rand3.nextInt()); for (int run = 0; run < MAX; run++) { len = (int) (random() * 500) + 10; append.reset(); for (int i = 0; i < len; i++) { append.append(CHAR_TABLE[((SALTS[ ((rand.nextInt(1000)) + 1) % SALTS.length]) * ((flip = !flip) ? rand1.nextInt(1000) : rand2.nextInt(1000)) + 1) % CHAR_TABLE.length]); SALTS[rand3.nextInt(SALTS.length - 1)] ^= rand4.nextInt(1000) + 1; } try { MVEL.eval(append.toString()); } catch (UnresolveablePropertyException e) { //ignore } catch (CompileException e) { //ignore } catch (ArithmeticException e) { //ignore } catch (Exception e) { System.out.println("untrapped error!\n---\n" + append.toString() + "\n---\n"); System.out.flush(); e.printStackTrace(); System.err.flush(); } if (run % 25000 == 0 && run != 0) { rate = run / (time = (currentTimeMillis() - start) / 1000); System.out.println("Run: " + df.format(run) + " times; " + df.format(time) + "secs; " + df.format(rate) + " avg. per second."); } } } } mvel-2.0.18.orig/src/test/java/org/mvel2/tests/fuzz/IdentifierFuzzer.java0000644000175000017500000000304711253250512026176 0ustar drazzibdrazzibpackage org.mvel2.tests.fuzz; import org.mvel2.MVEL; import org.mvel2.util.ParseTools; import static java.lang.Character.isJavaIdentifierStart; public class IdentifierFuzzer { public static void main(String[] args) { try { for (int i = 0; i < 1000000; i++) { MVEL.compileExpression(getIndentifierSample()); } } catch (Throwable t) { t.printStackTrace(); } System.out.println("**Done**"); } private static char[] getIndentifierSample() { int idLength = (int) (10 * Math.random()) + 2; char[] sample = new char[idLength + 5]; boolean ok = false; char candidate; while (!ok) { if (isJavaIdentifierStart(candidate = (char) (128 * Math.random()))) { sample[0] = candidate; ok = true; } } for (int i = 1; i < idLength; i++) { ok = false; while (!ok) { candidate = (char) (128 * Math.random()); if (Character.isJavaIdentifierPart(candidate)) { sample[i] = candidate; ok = true; } } } if (ParseTools.isReservedWord(new String(sample, 0, idLength).trim())) { return getIndentifierSample(); } sample[idLength] = ' '; sample[idLength + 1] = '='; sample[idLength + 2] = ' '; sample[idLength + 3] = '1'; sample[idLength + 4] = ';'; return sample; } } mvel-2.0.18.orig/src/test/java/org/mvel2/marshalling/0000755000175000017500000000000011412747035022210 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/marshalling/MarshallingTest.java0000644000175000017500000007044611164262300026156 0ustar drazzibdrazzibpackage org.mvel2.marshalling; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import junit.framework.TestCase; import org.mvel2.MVEL; import org.mvel2.integration.impl.MapVariableResolverFactory; import org.mvel2.util.StringAppender; // import com.thoughtworks.xstream.XStream; /** * Generates templates to marshaller classes. * TODO * -Currently uses BeanInfo, needs to handle all MVEL getter/setter types * -Use objenesis or equivalent to always be able to handle no-arg constructor * -handle special immutable classes like BigInteger, BigDecimal(which are already done, but are there others?) * -As well as allowing users to register custom templates, maybe also custom built in marshallers (i.e. how map, collection, array currently works) * -Support optional generated imports, to reduce verbosity * -some issue related to values allowed in a Map * */ public class MarshallingTest extends TestCase { public static enum Type { PRIMITIVE, CHAR, STRING, DATE, CALENDAR, BIG_INTEGER, BIG_DECIMAL, ARRAY, MAP, COLLECTION, OBJECT; } public static class ObjectConverter { private Class type; private ObjectConverterEntry[] fields; public ObjectConverter(Class type, ObjectConverterEntry[] fields) { this.type = type; this.fields = fields; } public Class getType() { return this.type; } public ObjectConverterEntry[] getFields() { return fields; } } public static class ObjectConverterEntry { private String name; private Type type; private Method method; public ObjectConverterEntry(String name, Method method, Type type) { this.name = name; this.type = type; this.method = method; } public String getName() { return name; } public Type getType() { return type; } public Method getMethod() { return this.method; } } public static class MarshallerContext { private Marshaller marshaller; private StringAppender appender = new StringAppender(); public MarshallerContext(Marshaller marshaller) { this.marshaller = marshaller; this.appender = new StringAppender(); } public void marshall(Object object) { marshaller.marshall( object, this ); } public StringAppender getAppender() { return appender; } } public static interface CustomMarshaller { public void marshall(Object object, MarshallerContext ctx); } public static class EpocDateMarshaller implements CustomMarshaller { public void marshall(Object object, MarshallerContext ctx) { ctx.getAppender().append( "new java.util.Date(" + ((Date) object).getTime() + ")" ); } } public static class EpocDefaultCalendarMarshaller implements CustomMarshaller { private CustomMarshaller dateMarshaller; public EpocDefaultCalendarMarshaller() { this( new EpocDateMarshaller() ); } public EpocDefaultCalendarMarshaller(CustomMarshaller dateMarshaller) { this.dateMarshaller = dateMarshaller; } public void marshall(Object object, MarshallerContext ctx) { ctx.getAppender().append( "with ( java.util.Calendar.getInstance() ) { time = " ); this.dateMarshaller.marshall( ((Calendar) object).getTime(), ctx ); ctx.getAppender().append( "} " ); } } public static class Marshaller { private Map converters; private CustomMarshaller dateMarshaller; private CustomMarshaller calendarMarshaller; public Marshaller() { this( new HashMap() ); } public Marshaller(Map custom) { this.converters = new HashMap(); this.dateMarshaller = custom.get( Type.DATE ); if ( this.dateMarshaller == null ) { this.dateMarshaller = new EpocDateMarshaller(); } this.calendarMarshaller = custom.get( Type.CALENDAR ); if ( this.calendarMarshaller == null ) { this.calendarMarshaller = new EpocDefaultCalendarMarshaller(); } } public void marshall(Object object, MarshallerContext ctx) { marshall( object, getType( object.getClass() ), ctx ); } public void marshall(Object object, Type type, MarshallerContext ctx) { if ( object == null ) { ctx.getAppender().append( "null" ); return; } if ( type != Type.OBJECT ) { marshallValue( object, type, ctx ); } else { Class cls = object.getClass(); ObjectConverter converter = this.converters.get( cls ); if ( converter == null ) { converter = generateConverter( cls ); this.converters.put( cls, converter ); } try { int i = 0; ctx.getAppender().append( "new " + cls.getName() + "().{ " ); for ( ObjectConverterEntry entry : converter.getFields() ) { if ( i++ != 0 ) { ctx.getAppender().append( ", " ); } ctx.getAppender().append( entry.getName() ); ctx.getAppender().append( " = " ); marshallValue( entry.getMethod().invoke( object, null ), entry.getType(), ctx ); } } catch ( Exception e ) { throw new IllegalStateException( "Unable to marshall object " + object, e ); } ctx.getAppender().append( " }" ); } } private void marshallValue(Object object, Type type, MarshallerContext ctx) { if ( object == null ) { ctx.getAppender().append( "null" ); return; } switch ( type ) { case PRIMITIVE : { ctx.getAppender().append( object ); break; } case CHAR : { ctx.getAppender().append( "'" ); ctx.getAppender().append( object ); ctx.getAppender().append( "'" ); break; } case STRING : { ctx.getAppender().append( "'" ); ctx.getAppender().append( object ); ctx.getAppender().append( "'" ); break; } case DATE : { dateMarshaller.marshall( object, ctx ); break; } case CALENDAR : { calendarMarshaller.marshall( object, ctx ); break; } case BIG_INTEGER : { ctx.getAppender().append( object ); break; } case BIG_DECIMAL : { ctx.getAppender().append( object ); break; } case ARRAY : { marshallArray( object, ctx ); break; } case MAP : { marshallMap( (Map) object, ctx ); break; } case COLLECTION : { marshallCollection( (Collection) object, ctx ); break; } case OBJECT : { marshall( object, type, ctx ); break; } } } private ObjectConverter generateConverter(Class cls) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo( cls ); } catch ( IntrospectionException e ) { throw new RuntimeException( e ); } PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); List list = new ArrayList(); for ( int i = 0, length = props.length; i < length; i++ ) { PropertyDescriptor prop = props[i]; if ( "class".equals( prop.getName() ) ) { continue; } list.add( new ObjectConverterEntry( prop.getName(), prop.getReadMethod(), getType( prop.getPropertyType() ) ) ); } return new ObjectConverter( cls, list.toArray( new ObjectConverterEntry[list.size()] ) ); } private Type getType(Class cls) { Type type = null; if ( cls.isPrimitive() || Number.class.isAssignableFrom( cls ) ) { type = Type.PRIMITIVE; } else if ( Character.class.isAssignableFrom( cls ) ) { type = Type.CHAR; } else if ( String.class.isAssignableFrom( cls ) ) { type = Type.STRING; } else if ( Date.class.isAssignableFrom( cls ) ) { type = Type.DATE; } else if ( Calendar.class.isAssignableFrom( cls ) ) { type = Type.CALENDAR; } else if ( BigInteger.class.isAssignableFrom( cls ) ) { type = Type.BIG_INTEGER; } else if ( BigDecimal.class.isAssignableFrom( cls ) ) { type = Type.BIG_DECIMAL; } else if ( cls.isArray() ) { type = Type.ARRAY; } else if ( Map.class.isAssignableFrom( cls ) ) { type = Type.MAP; } else if ( Collection.class.isAssignableFrom( cls ) ) { type = Type.COLLECTION; } else { type = Type.OBJECT; } return type; } private void marshallMap(Map map, MarshallerContext ctx) { ctx.getAppender().append( " [ " ); int i = 0; for ( Iterator it = map.entrySet().iterator(); it.hasNext(); i++ ) { if ( i != 0 ) { ctx.getAppender().append( ", " ); } Entry entry = it.next(); marshall( entry.getKey(), ctx ); ctx.getAppender().append( ':' ); marshall( entry.getValue(), ctx ); } ctx.getAppender().append( " ] " ); } private void marshallCollection(Collection collection, MarshallerContext ctx) { ctx.getAppender().append( " [ " ); int i = 0; for ( Iterator it = collection.iterator(); it.hasNext(); i++ ) { if ( i != 0 ) { ctx.getAppender().append( ", " ); } marshall( it.next(), ctx ); } ctx.getAppender().append( " ] " ); } private void marshallArray(Object array, MarshallerContext ctx) { ctx.getAppender().append( " { " ); for ( int i = 0, length = Array.getLength( array ); i < length; i++ ) { if ( i != 0 ) { ctx.getAppender().append( ", " ); } marshall( Array.get( array, i ), ctx ); } ctx.getAppender().append( " } " ); } public String marshallToString(Object object) { MarshallerContext ctx = new MarshallerContext( this ); marshall( object, ctx ); return ctx.getAppender().toString(); } } private Object getData() { Pet pet = new Pet(); pet.setName( "rover" ); pet.setAge( 7 ); List list = new ArrayList(); list.add( "a" ); list.add( 12 ); list.add( new SomeNumers( 10.02f, 22.02, 5, 100l, new BigDecimal( 23.0234d, MathContext.DECIMAL128 ), new BigInteger( "1001" ) ) ); list.add( new Date() ); //list.add( 'b' ); // generates ok but breaks round trip equals list.add( new Cheese( "cheddar", 6 ) ); pet.setList( list ); pet.setArray( new int[]{1, 2, 3} ); Map map = new HashMap(); //map.put( new Date(), new Cheese( "stilton", 11) ); // TODO why doesn't this work map.put( "key1", 13 ); map.put( "key3", "value3" ); map.put( "key2", 15 ); map.put( "key4", new Cheese( "stilton", 11 ) ); Calendar cal = Calendar.getInstance(); // cal.setTime( new Date() ); // map.put( "key5", // cal ); // TODO why doesn't this work. //map.put( "key4", new String[] { "a", "b" } ); // TODO why doesn't this work Person person = new Person(); person.setName( "mark" ); person.setAge( 33 ); person.setPet( pet ); person.setSomeDate( new Date() ); person.setMap( map ); cal = Calendar.getInstance(); cal.setTime( new Date() ); person.setCal( cal ); return person; } private static final int COUNT = 0; // public void testXStream() { // XStream xstream = new XStream(); // // // run once to allow for caching // Object data1 = getData(); // String str = xstream.toXML( data1 ); // System.out.println( str ); // Object data2 = xstream.fromXML( str ); // assertNotSame( data1, // data2 ); // assertEquals( data1, // data2 ); // // long start = System.currentTimeMillis(); // for ( int i = 0; i < COUNT; i++ ) { // data1 = getData(); // str = xstream.toXML( data1 ); // data2 = xstream.fromXML( str ); // assertNotSame( data1, // data2 ); // assertEquals( data1, // data2 ); // } // long end = System.currentTimeMillis(); // // System.out.println( "xstream : " + (end - start) ); // } public void testMVEL() throws Exception { Marshaller marshaller = new Marshaller(); // run once to generate templates Object data1 = getData(); String str = marshaller.marshallToString( data1 ); System.out.println( str ); Object data2 = MVEL.eval( str ); assertNotSame( data1, data2 ); assertEquals( data1, data2 ); long start = System.currentTimeMillis(); for ( int i = 0; i < COUNT; i++ ) { data1 = getData(); str = marshaller.marshallToString( data1 ); data2 = MVEL.eval( str ); assertNotSame( data1, data2 ); assertEquals( data1, data2 ); } long end = System.currentTimeMillis(); System.out.println( "mvel : " + (end - start) ); } public static class SomeNumers { private float aFloat; private double aDouble; private int aInt; private long aLong; private BigDecimal aBigDecimal; private BigInteger aBigInteger; public SomeNumers() { } public SomeNumers(float float1, double double1, int int1, long long1, BigDecimal bigDecimal, BigInteger bigInteger) { super(); aFloat = float1; aDouble = double1; aInt = int1; aLong = long1; aBigDecimal = bigDecimal; aBigInteger = bigInteger; } public float getAFloat() { return aFloat; } public void setAFloat(float float1) { aFloat = float1; } public double getADouble() { return aDouble; } public void setADouble(double double1) { aDouble = double1; } public int getAInt() { return aInt; } public void setAInt(int int1) { aInt = int1; } public long getALong() { return aLong; } public void setALong(long long1) { aLong = long1; } public BigDecimal getABigDecimal() { return aBigDecimal; } public void setABigDecimal(BigDecimal bigDecimal) { aBigDecimal = bigDecimal; } public BigInteger getABigInteger() { return aBigInteger; } public void setABigInteger(BigInteger bigInteger) { aBigInteger = bigInteger; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((aBigDecimal == null) ? 0 : aBigDecimal.hashCode()); result = prime * result + ((aBigInteger == null) ? 0 : aBigInteger.hashCode()); long temp; temp = Double.doubleToLongBits( aDouble ); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Float.floatToIntBits( aFloat ); result = prime * result + aInt; result = prime * result + (int) (aLong ^ (aLong >>> 32)); return result; } @Override public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; SomeNumers other = (SomeNumers) obj; if ( aBigDecimal == null ) { if ( other.aBigDecimal != null ) return false; } else if ( !aBigDecimal.equals( other.aBigDecimal ) ) return false; if ( aBigInteger == null ) { if ( other.aBigInteger != null ) return false; } else if ( !aBigInteger.equals( other.aBigInteger ) ) return false; if ( Double.doubleToLongBits( aDouble ) != Double.doubleToLongBits( other.aDouble ) ) return false; if ( Float.floatToIntBits( aFloat ) != Float.floatToIntBits( other.aFloat ) ) return false; if ( aInt != other.aInt ) return false; if ( aLong != other.aLong ) return false; return true; } } public static class Person { private String name; private int age; private Date someDate; private Pet pet; private Object nullTest; private Map map; private Calendar cal; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Pet getPet() { return this.pet; } public void setPet(Pet pet) { this.pet = pet; } public Date getSomeDate() { return someDate; } public void setSomeDate(Date someDate) { this.someDate = someDate; } public Object getNullTest() { return nullTest; } public void setNullTest(Object nullTest) { this.nullTest = nullTest; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public Calendar getCal() { return cal; } public void setCal(Calendar cal) { this.cal = cal; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((cal == null) ? 0 : cal.hashCode()); result = prime * result + ((map == null) ? 0 : map.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((nullTest == null) ? 0 : nullTest.hashCode()); result = prime * result + ((pet == null) ? 0 : pet.hashCode()); result = prime * result + ((someDate == null) ? 0 : someDate.hashCode()); return result; } @Override public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; Person other = (Person) obj; if ( age != other.age ) return false; if ( cal == null ) { if ( other.cal != null ) return false; } else if ( !cal.equals( other.cal ) ) return false; if ( map == null ) { if ( other.map != null ) return false; } else if ( !map.equals( other.map ) ) return false; if ( name == null ) { if ( other.name != null ) return false; } else if ( !name.equals( other.name ) ) return false; if ( nullTest == null ) { if ( other.nullTest != null ) return false; } else if ( !nullTest.equals( other.nullTest ) ) return false; if ( pet == null ) { if ( other.pet != null ) return false; } else if ( !pet.equals( other.pet ) ) return false; if ( someDate == null ) { if ( other.someDate != null ) return false; } else if ( !someDate.equals( other.someDate ) ) return false; return true; } } public static class Pet { private String name; private Integer age; private List list; private int[] array; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer agr) { this.age = agr; } public List getList() { return list; } public void setList(List list) { this.list = list; } public int[] getArray() { return array; } public void setArray(int[] array) { this.array = array; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + Arrays.hashCode( array ); result = prime * result + ((list == null) ? 0 : list.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; Pet other = (Pet) obj; if ( age == null ) { if ( other.age != null ) return false; } else if ( !age.equals( other.age ) ) return false; if ( !Arrays.equals( array, other.array ) ) return false; if ( list == null ) { if ( other.list != null ) return false; } else if ( !list.equals( other.list ) ) return false; if ( name == null ) { if ( other.name != null ) return false; } else if ( !name.equals( other.name ) ) return false; return true; } } public static class Cheese { private String type; private int age; private boolean edible; public Cheese() { } public Cheese(String type, int age) { this.type = type; this.age = age; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isEdible() { return edible; } public void setEdible(boolean edible) { this.edible = edible; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + (edible ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; Cheese other = (Cheese) obj; if ( age != other.age ) return false; if ( edible != other.edible ) return false; if ( type == null ) { if ( other.type != null ) return false; } else if ( !type.equals( other.type ) ) return false; return true; } } } mvel-2.0.18.orig/src/test/java/org/mvel2/util/0000755000175000017500000000000011412747040020660 5ustar drazzibdrazzibmvel-2.0.18.orig/src/test/java/org/mvel2/util/FastListTest.java0000644000175000017500000000244111345736415024126 0ustar drazzibdrazzibpackage org.mvel2.util; import junit.framework.TestCase; import org.mvel2.MVEL; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FastListTest extends TestCase { protected Map map = new HashMap(); public FastListTest() { map.put("var0", "var0"); } public void testHashCode() { List list = (List) parseDirect("[ 'key1', var0 ]"); System.out.println(list.hashCode()); } public void testEquals() { List list1 = (List) parseDirect("[ 'key1', var0 ]"); List list2 = new ArrayList(); list2.add("key1"); list2.add("var0"); assertEquals(list2, list1); assertEquals(list1, list2); } public Object parseDirect(String ex) { return compiledExecute(ex); } public Object compiledExecute(String ex) { Serializable compiled = MVEL.compileExpression(ex); Object first = MVEL.executeExpression(compiled, null, map); Object second = MVEL.executeExpression(compiled, null, map); if (first != null && !first.getClass().isArray()) assertEquals(first, second); return second; } } mvel-2.0.18.orig/src/test/java/org/mvel2/util/QuickSort.java0000644000175000017500000000330311073524603023447 0ustar drazzibdrazzibpackage org.mvel2.util; /** * This class implements a version of the * quicksort algorithm using a partition * algorithm that does not rely on the * first element of the array being vacant, * nor does it guarantee that the chosen * pivot value is at the split point of * the partition. * * @author Cay Horstmann */ public class QuickSort { public static void main(String[] args) { QuickSort qs = new QuickSort(new int[]{50, 20, 21, 209, 10, 77, 8, 9, 55, 73, 41, 99}); qs.sort(); } public static int[] quickSort(int[] num) { new QuickSort(num).sort(); return num; } public QuickSort(int[] anArray) { a = anArray; } /** * Sorts the array managed by this sorter */ public void sort() { sort(0, a.length - 1); } public void sort(int low, int high) { if (low >= high) return; int p = partition(low, high); sort(low, p); sort(p + 1, high); } private int partition(int low, int high) { // First element int pivot = a[low]; // Middle element //int middle = (low + high) / 2; //int pivot = a[middle]; int i = low - 1; int j = high + 1; while (i < j) { i++; while (a[i] < pivot) i++; j--; while (a[j] > pivot) j--; if (i < j) swap(i, j); } return j; } /** * Swaps two entries of the array. * * @param i the first position to swap * @param j the second position to swap */ private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } private int[] a; }