This is an automated email from the ASF dual-hosted git repository.
henrib pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-jexl.git
The following commit(s) were added to refs/heads/master by this push:
new bbcb06e JEXL: winter cleaning; - switched from clirr to japicmp; -
configured pmd and addressed top issues; - improved test coverage; - various
nitpicks in javadoc and comments;
bbcb06e is described below
commit bbcb06e532404d355fccdefc6e5e6052bd0492cd
Author: henrib <[email protected]>
AuthorDate: Tue Dec 21 17:54:25 2021 +0100
JEXL: winter cleaning;
- switched from clirr to japicmp;
- configured pmd and addressed top issues;
- improved test coverage;
- various nitpicks in javadoc and comments;
---
pom.xml | 135 +++++++++++-----
src/main/config/clirr-ignored.xml | 58 -------
src/main/config/findbugs-exclude-filter.xml | 12 ++
src/main/config/pmd.xml | 31 ++++
.../org/apache/commons/jexl3/JexlArithmetic.java | 49 +++---
.../java/org/apache/commons/jexl3/JexlEngine.java | 6 +-
.../org/apache/commons/jexl3/JexlException.java | 12 +-
.../org/apache/commons/jexl3/JexlFeatures.java | 10 +-
.../java/org/apache/commons/jexl3/JexlOptions.java | 27 ++--
.../apache/commons/jexl3/internal/Debugger.java | 27 ++--
.../org/apache/commons/jexl3/internal/Engine.java | 74 +++++----
.../apache/commons/jexl3/internal/Interpreter.java | 18 +--
.../commons/jexl3/internal/InterpreterBase.java | 34 ++--
.../org/apache/commons/jexl3/internal/Script.java | 4 +-
.../commons/jexl3/internal/TemplateDebugger.java | 1 +
.../commons/jexl3/internal/TemplateEngine.java | 87 ++++++----
.../jexl3/internal/TemplateInterpreter.java | 6 +-
.../commons/jexl3/internal/TemplateScript.java | 16 +-
.../jexl3/internal/introspection/ClassMap.java | 6 +-
.../jexl3/internal/introspection/IndexedType.java | 16 +-
.../jexl3/internal/introspection/Introspector.java | 14 +-
.../internal/introspection/MethodExecutor.java | 5 +-
.../jexl3/internal/introspection/MethodKey.java | 44 +++---
.../jexl3/internal/introspection/Permissions.java | 10 +-
.../introspection/PropertySetExecutor.java | 7 +-
.../jexl3/internal/introspection/Uberspect.java | 2 +-
.../apache/commons/jexl3/parser/ASTJexlScript.java | 6 +-
.../commons/jexl3/parser/ASTNumberLiteral.java | 1 +
.../apache/commons/jexl3/parser/JexlParser.java | 20 +--
.../apache/commons/jexl3/parser/NumberParser.java | 8 +-
.../apache/commons/jexl3/parser/SimpleNode.java | 12 +-
.../apache/commons/jexl3/parser/StringParser.java | 38 +++--
.../commons/jexl3/scripting/JexlScriptEngine.java | 35 ++--
.../org/apache/commons/jexl3/scripting/Main.java | 10 +-
.../org/apache/commons/jexl3/ArithmeticTest.java | 176 ++++++++++++++++++---
.../org/apache/commons/jexl3/FeaturesTest.java | 3 +-
.../java/org/apache/commons/jexl3/JXLTTest.java | 21 ++-
.../jexl3/scripting/JexlScriptEngineTest.java | 106 ++++++++++++-
38 files changed, 751 insertions(+), 396 deletions(-)
diff --git a/pom.xml b/pom.xml
index b4de2ff..2127401 100644
--- a/pom.xml
+++ b/pom.xml
@@ -53,6 +53,9 @@
<commons.jira.pid>12310479</commons.jira.pid>
<checkstyle.plugin.version>3.1.2</checkstyle.plugin.version>
<checksyle.version>9.2</checksyle.version>
+ <japicmp.skip>false</japicmp.skip>
+ <commons.japicmp.version>0.15.3</commons.japicmp.version>
+ <commons.pmd.version>3.15.0</commons.pmd.version>
<!-- override of Jacoco properties defined in CP52 -->
<commons.jacoco.version>0.8.7</commons.jacoco.version>
@@ -119,7 +122,7 @@
</dependencies>
<build>
- <defaultGoal>clean apache-rat:check spotbugs:check package clirr:check
checkstyle:check javadoc:javadoc</defaultGoal>
+ <defaultGoal>clean package apache-rat:check spotbugs:check
japicmp:check checkstyle:check javadoc:javadoc</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -244,17 +247,57 @@
</configuration>
</plugin>
- <!-- Allow Clirr to be run from command-line. Must agree with
config in report section. -->
+ <!-- japicmp -->
<plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>clirr-maven-plugin</artifactId>
+ <groupId>com.github.siom79.japicmp</groupId>
+ <artifactId>japicmp-maven-plugin</artifactId>
+ <version>${commons.japicmp.version}</version>
<configuration>
-
<ignoredDifferencesFile>${basedir}/src/main/config/clirr-ignored.xml</ignoredDifferencesFile>
+ <parameter>
+ <includes>
+ <include>org.apache.commons.jexl3</include>
+
<include>org.apache.commons.jexl3.introspection</include>
+
<include>org.apache.commons.jexl3.scripting</include>
+ </includes>
+ <excludes>
+
<exclude>org.apache.commons.jexl3.internal</exclude>
+
<exclude>org.apache.commons.jexl3.introspection.internal</exclude>
+ <exclude>org.apache.commons.jexl3.parser</exclude>
+ </excludes>
+ <onlyModified>true</onlyModified>
+ <accessModifier>protected</accessModifier>
+ <ignoreMissingClasses>true</ignoreMissingClasses>
+
<breakBuildOnBinaryIncompatibleModifications>false</breakBuildOnBinaryIncompatibleModifications>
+
<breakBuildIfCausedByExclusion>false</breakBuildIfCausedByExclusion>
+ </parameter>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-pmd-plugin</artifactId>
+ <version>${commons.pmd.version}</version>
+ <configuration>
+ <targetJdk>${maven.compiler.target}</targetJdk>
+ <rulesets>
+
<ruleset>${project.basedir}/src/main/config/pmd_jexl.xml</ruleset>
+ </rulesets>
<excludes>
- <exclude>org/apache/commons/jexl3/parser/**</exclude>
- <exclude>org/apache/commons/jexl3/internal/**</exclude>
+
<exclude>org/apache/commons/jexl3/parser/Parser.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/AST*.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/ParserTokenManager.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/*Constants.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/AbstractCharStream.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/*Provider.java</exclude>
</excludes>
</configuration>
+ <dependencies>
+ <dependency>
+ <groupId>org.ow2.asm</groupId>
+ <artifactId>asm</artifactId>
+ <version>9.2</version>
+ </dependency>
+ </dependencies>
</plugin>
<!-- Allow RAT to be run from command-line. Must agree with config
in report section. -->
@@ -327,41 +370,31 @@
</plugin>
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-pmd-plugin</artifactId>
- <version>3.15.0</version>
+ <groupId>com.github.siom79.japicmp</groupId>
+ <artifactId>japicmp-maven-plugin</artifactId>
+ <version>${commons.japicmp.version}</version>
<configuration>
- <targetJdk>${maven.compiler.target}</targetJdk>
- <excludes>
- <excludes>**/generated-sources/**/*</excludes>
- </excludes>
- <rulesets>
- <ruleset>/category/java/bestpractices.xml</ruleset>
- </rulesets>
+ <parameter>
+ <includes>
+ <include>org.apache.commons.jexl3</include>
+
<include>org.apache.commons.jexl3.introspection</include>
+
<include>org.apache.commons.jexl3.scripting</include>
+ </includes>
+ <excludes>
+
<exclude>org.apache.commons.jexl3.internal</exclude>
+
<exclude>org.apache.commons.jexl3.introspection.internal</exclude>
+ <exclude>org.apache.commons.jexl3.parser</exclude>
+ </excludes>
+ <onlyModified>true</onlyModified>
+ <accessModifier>protected</accessModifier>
+ <ignoreMissingClasses>true</ignoreMissingClasses>
+
<breakBuildOnBinaryIncompatibleModifications>false</breakBuildOnBinaryIncompatibleModifications>
+
<breakBuildIfCausedByExclusion>false</breakBuildIfCausedByExclusion>
+ </parameter>
</configuration>
- <reportSets>
- <reportSet>
- <reports>
- <report>pmd</report>
- <report>cpd</report>
- </reports>
- </reportSet>
- </reportSets>
</plugin>
<plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>clirr-maven-plugin</artifactId>
- <version>2.8</version>
- <configuration>
-
<ignoredDifferencesFile>${basedir}/src/main/config/clirr-ignored.xml</ignoredDifferencesFile>
- <excludes>
- <exclude>org/apache/commons/jexl3/parser/**</exclude>
- <exclude>org/apache/commons/jexl3/internal/**</exclude>
- </excludes>
- </configuration>
- </plugin>
- <plugin>
<groupId>org.apache.rat</groupId>
<artifactId>apache-rat-plugin</artifactId>
<configuration>
@@ -384,6 +417,34 @@
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-pmd-plugin</artifactId>
+ <version>${commons.pmd.version}</version>
+ <configuration>
+ <targetJdk>${maven.compiler.target}</targetJdk>
+ <rulesets>
+
<ruleset>${project.basedir}/src/main/config/pmd.xml</ruleset>
+ </rulesets>
+ <excludes>
+
<exclude>org/apache/commons/jexl3/parser/Parser.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/AST*.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/ParserTokenManager.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/*Constants.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/AbstractCharStream.java</exclude>
+
<exclude>org/apache/commons/jexl3/parser/*Provider.java</exclude>
+ </excludes>
+ </configuration>
+ <reportSets>
+ <reportSet>
+ <reports>
+ <report>pmd</report>
+ <report>cpd</report>
+ </reports>
+ </reportSet>
+ </reportSets>
+ </plugin>
+
</plugins>
</reporting>
diff --git a/src/main/config/clirr-ignored.xml
b/src/main/config/clirr-ignored.xml
deleted file mode 100644
index 6f8b1e1..0000000
--- a/src/main/config/clirr-ignored.xml
+++ /dev/null
@@ -1,58 +0,0 @@
-<?xml version="1.0"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-<differences>
- <!-- 3.2 differences: Jexl{Engine, Script, Uberspect} are not used as user
implementation contracts
- but only as JEXL API contracts. Adding new methods or final modifier to
those is very unlikely to have
- any impact on actual binary compatiblity.An equivalent set of changes
occured on 3.1 without complaints. -->
- <difference>
- <className>org/apache/commons/jexl3/JexlEngine</className>
- <differenceType>7014</differenceType> <!-- final method on abstract
class not meant for the user to derive -->
- <method>org.apache.commons.jexl3.JexlScript
createScript(org.apache.commons.jexl3.JexlInfo, java.lang.String,
java.lang.String[])</method>
- <to>org.apache.commons.jexl3.JexlScript
createScript(org.apache.commons.jexl3.JexlInfo, java.lang.String,
java.lang.String[])</to>
- </difference>
-
- <difference>
- <className>org/apache/commons/jexl3/JexlEngine</className>
- <differenceType>7013</differenceType> <!-- added abstract method on
abstract class not meant for the user to derive -->
- <method>org.apache.commons.jexl3.JexlScript
createScript(org.apache.commons.jexl3.JexlFeatures,
org.apache.commons.jexl3.JexlInfo, java.lang.String,
java.lang.String[])</method>
- <to>org.apache.commons.jexl3.JexlScript
createScript(org.apache.commons.jexl3.JexlFeatures,
org.apache.commons.jexl3.JexlInfo, java.lang.String, java.lang.String[])</to>
- </difference>
-
- <difference>
- <className>org/apache/commons/jexl3/JexlScript</className>
- <differenceType>7012</differenceType> <!-- method added to interface
that is not meant for the user to implement -->
- <method>java.lang.String[] getUnboundParameters()</method>
- <to>java.lang.String[] getUnboundParameters()</to>
- </difference>
-
- <difference>
-
<className>org/apache/commons/jexl3/introspection/JexlUberspect</className>
- <differenceType>7012</differenceType> <!-- method added to interface
that is not meant for the user to implement -->
- <method>java.lang.ClassLoader getClassLoader()</method>
- <to>java.lang.ClassLoader getClassLoader()</to>
- </difference>
-
- <!-- The parser now expects/generates TokenMgrException instead of
TokenMgrError -->
- <difference>
-
<className>org/apache/commons/jexl3/JexlException$Tokenization</className>
- <differenceType>7005</differenceType> <!-- parser now constructs this
exception using TokenMgrException -->
- <method>JexlException$Tokenization(org.apache.commons.jexl3.JexlInfo,
org.apache.commons.jexl3.parser.TokenMgrError)</method>
- <to>JexlException$Tokenization(org.apache.commons.jexl3.JexlInfo,
org.apache.commons.jexl3.parser.TokenMgrException)</to>
- </difference>
-</differences>
\ No newline at end of file
diff --git a/src/main/config/findbugs-exclude-filter.xml
b/src/main/config/findbugs-exclude-filter.xml
index 73cb733..2f70690 100644
--- a/src/main/config/findbugs-exclude-filter.xml
+++ b/src/main/config/findbugs-exclude-filter.xml
@@ -22,6 +22,15 @@
-->
<FindBugsFilter>
<Match>
+ <Class name="org.apache.commons.jexl3.parser.AbstractCharStream"/>
+ </Match>
+ <Match>
+ <Class name="org.apache.commons.jexl3.parser.JexlLexicalNode"/>
+ </Match>
+ <Match>
+ <Class name="org.apache.commons.jexl3.parser.JexlParser"/>
+ </Match>
+ <Match>
<Class name="org.apache.commons.jexl3.parser.ParseException"/>
</Match>
<Match>
@@ -39,4 +48,7 @@
<Match>
<Class name="org.apache.commons.jexl3.parser.TokenMgrError"/>
</Match>
+ <Match>
+ <Class name="org.apache.commons.jexl3.parser.SimpleNode"/>
+ </Match>
</FindBugsFilter>
diff --git a/src/main/config/pmd.xml b/src/main/config/pmd.xml
new file mode 100644
index 0000000..d8099ed
--- /dev/null
+++ b/src/main/config/pmd.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<ruleset name="JEXL Rules"
+ xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0
https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
+
+ <description>
+ JEXL custom rules
+ </description>
+
+ <rule ref="category/java/bestpractices.xml">
+ <exclude name="UseVarargs"/>
+ <exclude name="ArrayIsStoredDirectly"/>
+ </rule>
+</ruleset>
diff --git a/src/main/java/org/apache/commons/jexl3/JexlArithmetic.java
b/src/main/java/org/apache/commons/jexl3/JexlArithmetic.java
index ed056bc..4a8e364 100644
--- a/src/main/java/org/apache/commons/jexl3/JexlArithmetic.java
+++ b/src/main/java/org/apache/commons/jexl3/JexlArithmetic.java
@@ -1177,22 +1177,24 @@ public class JexlArithmetic {
* @return the boolean or null if there is no arithmetic solution
*/
public Boolean isEmpty(final Object object, final Boolean def) {
- if (object instanceof Number) {
- final double d = ((Number) object).doubleValue();
- return Double.isNaN(d) || d == 0.d;
- }
- if (object instanceof CharSequence) {
- return ((CharSequence) object).length() == 0;
- }
- if (object.getClass().isArray()) {
- return Array.getLength(object) == 0;
- }
- if (object instanceof Collection<?>) {
- return ((Collection<?>) object).isEmpty();
- }
- // Map isn't a collection
- if (object instanceof Map<?, ?>) {
- return ((Map<?, ?>) object).isEmpty();
+ if (object != null) {
+ if (object instanceof Number) {
+ final double d = ((Number) object).doubleValue();
+ return Double.isNaN(d) || d == 0.d;
+ }
+ if (object instanceof CharSequence) {
+ return ((CharSequence) object).length() == 0;
+ }
+ if (object.getClass().isArray()) {
+ return Array.getLength(object) == 0;
+ }
+ if (object instanceof Collection<?>) {
+ return ((Collection<?>) object).isEmpty();
+ }
+ // Map isn't a collection
+ if (object instanceof Map<?, ?>) {
+ return ((Map<?, ?>) object).isEmpty();
+ }
}
return def;
}
@@ -1354,11 +1356,6 @@ public class JexlArithmetic {
final Comparable<Object> comparable = (Comparable<Object>)
left;
return comparable.compareTo(right);
}
- if (right instanceof Comparable<?>) {
- @SuppressWarnings("unchecked") // OK because of instanceof
check above
- final Comparable<Object> comparable = (Comparable<Object>)
right;
- return comparable.compareTo(left);
- }
}
throw new ArithmeticException("Object comparison:(" + left + " " +
operator + " " + right + ")");
}
@@ -1736,7 +1733,7 @@ public class JexlArithmetic {
* @param rhs right hand side
* @return lhs & rhs
* @see JexlArithmetic#and
- * @deprecated
+ * @deprecated 3.0
*/
@Deprecated
public final Object bitwiseAnd(final Object lhs, final Object rhs) {
@@ -1750,7 +1747,7 @@ public class JexlArithmetic {
* @param rhs right hand side
* @return lhs | rhs
* @see JexlArithmetic#or
- * @deprecated
+ * @deprecated 3.0
*/
@Deprecated
public final Object bitwiseOr(final Object lhs, final Object rhs) {
@@ -1764,7 +1761,7 @@ public class JexlArithmetic {
* @param rhs right hand side
* @return lhs ^ rhs
* @see JexlArithmetic#xor
- * @deprecated
+ * @deprecated 3.0
*/
@Deprecated
public final Object bitwiseXor(final Object lhs, final Object rhs) {
@@ -1777,7 +1774,7 @@ public class JexlArithmetic {
* @param arg argument
* @return !arg
* @see JexlArithmetic#not
- * @deprecated
+ * @deprecated 3.0
*/
@Deprecated
public final Object logicalNot(final Object arg) {
@@ -1791,7 +1788,7 @@ public class JexlArithmetic {
* @param rhs right hand side
* @return contains(rhs, lhs)
* @see JexlArithmetic#contains
- * @deprecated
+ * @deprecated 3.0
*/
@Deprecated
public final Object matches(final Object lhs, final Object rhs) {
diff --git a/src/main/java/org/apache/commons/jexl3/JexlEngine.java
b/src/main/java/org/apache/commons/jexl3/JexlEngine.java
index 9cdb4f2..11e7c2d 100644
--- a/src/main/java/org/apache/commons/jexl3/JexlEngine.java
+++ b/src/main/java/org/apache/commons/jexl3/JexlEngine.java
@@ -54,7 +54,7 @@ public abstract class JexlEngine {
/**
* Default ctor.
*/
- private FailObject() {}
+ FailObject() {}
@Override
public String toString() {
@@ -177,7 +177,7 @@ public abstract class JexlEngine {
/**
* Default ctor.
*/
- private EmptyContext() {}
+ EmptyContext() {}
@Override
public Object get(final String name) {
@@ -207,7 +207,7 @@ public abstract class JexlEngine {
/**
* Default ctor.
*/
- private EmptyNamespaceResolver() {}
+ EmptyNamespaceResolver() {}
@Override
public Object resolveNamespace(final String name) {
diff --git a/src/main/java/org/apache/commons/jexl3/JexlException.java
b/src/main/java/org/apache/commons/jexl3/JexlException.java
index f27bae8..573bc75 100644
--- a/src/main/java/org/apache/commons/jexl3/JexlException.java
+++ b/src/main/java/org/apache/commons/jexl3/JexlException.java
@@ -120,7 +120,7 @@ public class JexlException extends RuntimeException {
* @param node the node
* @return a string builder
*/
- private static StringBuilder errorAt(final JexlNode node) {
+ static StringBuilder errorAt(final JexlNode node) {
final JexlInfo info = node != null? detailedInfo(node,
node.jexlInfo()) : null;
final StringBuilder msg = new StringBuilder();
if (info != null) {
@@ -152,7 +152,7 @@ public class JexlException extends RuntimeException {
* @param info the information
* @return the information or null
*/
- private static JexlInfo detailedInfo(final JexlNode node, final JexlInfo
info) {
+ static JexlInfo detailedInfo(final JexlNode node, final JexlInfo info) {
if (info != null && node != null) {
final Debugger dbg = new Debugger();
if (dbg.debug(node)) {
@@ -183,7 +183,7 @@ public class JexlException extends RuntimeException {
* @param xthrow the thowable
* @return the throwable
*/
- private static <X extends Throwable> X clean(final X xthrow) {
+ static <X extends Throwable> X clean(final X xthrow) {
if (xthrow != null) {
final List<StackTraceElement> stackJexl = new ArrayList<>();
for (final StackTraceElement se : xthrow.getStackTrace()) {
@@ -204,7 +204,7 @@ public class JexlException extends RuntimeException {
* @param xthrow the throwable
* @return the cause
*/
- private static Throwable unwrap(final Throwable xthrow) {
+ static Throwable unwrap(final Throwable xthrow) {
if (xthrow instanceof TryFailed
|| xthrow instanceof InvocationTargetException
|| xthrow instanceof UndeclaredThrowableException) {
@@ -220,7 +220,7 @@ public class JexlException extends RuntimeException {
* @param cause the cause
* @return the info to use
*/
- private static JexlInfo merge(final JexlInfo info, final JavaccError
cause) {
+ static JexlInfo merge(final JexlInfo info, final JavaccError cause) {
if (cause == null || cause.getLine() < 0) {
return info;
}
@@ -812,7 +812,7 @@ public class JexlException extends RuntimeException {
* @param args the method arguments
* @return a suitable signed name
*/
- private static String methodSignature(final String name, final Object[]
args) {
+ static String methodSignature(final String name, final Object[] args) {
if (args != null && args.length > 0) {
final StringBuilder strb = new StringBuilder(name);
strb.append('(');
diff --git a/src/main/java/org/apache/commons/jexl3/JexlFeatures.java
b/src/main/java/org/apache/commons/jexl3/JexlFeatures.java
index 3a91502..15d07e7 100644
--- a/src/main/java/org/apache/commons/jexl3/JexlFeatures.java
+++ b/src/main/java/org/apache/commons/jexl3/JexlFeatures.java
@@ -54,7 +54,7 @@ public final class JexlFeatures {
/** The namespace names. */
private Predicate<String> nameSpaces;
/** The false predicate. */
- public static final Predicate<String> TEST_STR_FALSE = (s)->false;
+ public static final Predicate<String> TEST_STR_FALSE = s->false;
/** Te feature names (for toString()). */
private static final String[] F_NAMES = {
"register", "reserved variable", "local variable", "assign/modify",
@@ -67,7 +67,7 @@ public final class JexlFeatures {
public static final int RESERVED = 1;
/** Locals feature ordinal. */
public static final int LOCAL_VAR = 2;
- /** Side-effects feature ordinal. */
+ /** Side effects feature ordinal. */
public static final int SIDE_EFFECT = 3;
/** Global side-effects feature ordinal. */
public static final int SIDE_EFFECT_GLOBAL = 4;
@@ -171,7 +171,7 @@ public final class JexlFeatures {
if (names == null || names.isEmpty()) {
reservedNames = Collections.emptySet();
} else {
- reservedNames = Collections.unmodifiableSet(new
TreeSet<String>(names));
+ reservedNames = Collections.unmodifiableSet(new TreeSet<>(names));
}
setFeature(RESERVED, !reservedNames.isEmpty());
return this;
@@ -217,7 +217,7 @@ public final class JexlFeatures {
*/
private void setFeature(final int feature, final boolean flag) {
if (flag) {
- flags |= (1 << feature);
+ flags |= (1L << feature);
} else {
flags &= ~(1L << feature);
}
@@ -274,7 +274,7 @@ public final class JexlFeatures {
}
/**
- * Sets whether side effect expressions on global variables (aka non
local) are enabled.
+ * Sets whether side effect expressions on global variables (aka
non-local) are enabled.
* <p>
* When disabled, parsing a script/expression using syntactical constructs
modifying variables
* <em>including all potentially ant-ish variables</em> will throw a
parsing exception.
diff --git a/src/main/java/org/apache/commons/jexl3/JexlOptions.java
b/src/main/java/org/apache/commons/jexl3/JexlOptions.java
index e72b9e7..1c12b1e 100644
--- a/src/main/java/org/apache/commons/jexl3/JexlOptions.java
+++ b/src/main/java/org/apache/commons/jexl3/JexlOptions.java
@@ -56,7 +56,7 @@ public final class JexlOptions {
private static final int STRICT = 1;
/** The cancellable bit. */
private static final int CANCELLABLE = 0;
- /** The flags names ordered. */
+ /** The flag names ordered. */
private static final String[] NAMES = {
"cancellable", "strict", "silent", "safe", "lexical", "antish",
"lexicalShade", "sharedInstance"
};
@@ -97,7 +97,9 @@ public final class JexlOptions {
/**
* Default ctor.
*/
- public JexlOptions() {}
+ public JexlOptions() {
+ // all inits in members declarations
+ }
/**
* Sets the default (static, shared) option flags.
@@ -126,20 +128,23 @@ public final class JexlOptions {
*/
public static int parseFlags(int initial, final String...flags) {
int mask = initial;
- for(String name : flags) {
+ for(String flag : flags) {
boolean b = true;
- if (name.charAt(0) == '+') {
- name = name.substring(1);
- } else if (name.charAt(0) == '-') {
- name = name.substring(1);
+ final String name;
+ if (flag.charAt(0) == '+') {
+ name = flag.substring(1);
+ } else if (flag.charAt(0) == '-') {
+ name = flag.substring(1);
b = false;
+ } else {
+ name = flag;
}
- for(int flag = 0; flag < NAMES.length; ++flag) {
- if (NAMES[flag].equals(name)) {
+ for(int f = 0; f < NAMES.length; ++f) {
+ if (NAMES[f].equals(name)) {
if (b) {
- mask |= (1 << flag);
+ mask |= (1 << f);
} else {
- mask &= ~(1 << flag);
+ mask &= ~(1 << f);
}
break;
}
diff --git a/src/main/java/org/apache/commons/jexl3/internal/Debugger.java
b/src/main/java/org/apache/commons/jexl3/internal/Debugger.java
index fd54f2f..0f5e577 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/Debugger.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/Debugger.java
@@ -129,6 +129,7 @@ public class Debugger extends ParserVisitor implements
JexlInfo.Detail {
* Creates a Debugger.
*/
public Debugger() {
+ // nothing to initialize
}
/**
@@ -364,7 +365,7 @@ public class Debugger extends ParserVisitor implements
JexlInfo.Detail {
* @return visitor pattern value
*/
protected Object infixChildren(final JexlNode node, final String infix,
final boolean paren, final Object data) {
- final int num = node.jjtGetNumChildren(); //child.jjtGetNumChildren()
> 1;
+ final int num = node.jjtGetNumChildren();
if (paren) {
builder.append('(');
}
@@ -619,7 +620,7 @@ public class Debugger extends ParserVisitor implements
JexlInfo.Detail {
* (but underscore, at-sign, sharp-sign and dollar).
*/
protected static final Pattern QUOTED_IDENTIFIER =
- Pattern.compile("[\\s]|[\\p{Punct}&&[^@#\\$_]]");
+ Pattern.compile("[\\s]|[\\p{Punct}&&[^@#$_]]");
/**
* Checks whether an identifier should be quoted or not.
@@ -925,15 +926,21 @@ public class Debugger extends ParserVisitor implements
JexlInfo.Detail {
}
@Override
- protected Object visit(final ASTStringLiteral node, final Object data) {
- final String img = node.getLiteral().replace("'", "\\'");
- return check(node, "'" + img + "'", data);
+ protected Object visit(ASTStringLiteral node, Object data) {
+ String img = StringParser.escapeString(node.getLiteral(), '\'');
+ return this.check(node, img, data);
+ }
+
+ @Override
+ protected Object visit(ASTJxltLiteral node, Object data) {
+ String img = StringParser.escapeString(node.getLiteral(), '`');
+ return this.check(node, img, data);
}
@Override
protected Object visit(final ASTRegexLiteral node, final Object data) {
- final String img = node.toString().replace("/", "\\/");
- return check(node, "~/" + img + "/", data);
+ String img = StringParser.escapeString(node.toString(), '/');
+ return check(node, "~" + img, data);
}
@Override
@@ -1052,12 +1059,6 @@ public class Debugger extends ParserVisitor implements
JexlInfo.Detail {
}
@Override
- protected Object visit(final ASTJxltLiteral node, final Object data) {
- final String img = node.getLiteral().replace("`", "\\`");
- return check(node, "`" + img + "`", data);
- }
-
- @Override
protected Object visit(final ASTAnnotation node, final Object data) {
final int num = node.jjtGetNumChildren();
builder.append('@');
diff --git a/src/main/java/org/apache/commons/jexl3/internal/Engine.java
b/src/main/java/org/apache/commons/jexl3/internal/Engine.java
index b75a7e8..d9ba006 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/Engine.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/Engine.java
@@ -222,7 +222,7 @@ public class Engine extends JexlEngine {
this.scriptFeatures = new
JexlFeatures(features).script(true).namespaceTest(nsTest);
this.charset = conf.charset();
// caching:
- this.cache = conf.cache() <= 0 ? null : new SoftCache<Source,
ASTJexlScript>(conf.cache());
+ this.cache = conf.cache() <= 0 ? null : new SoftCache<>(conf.cache());
this.cacheThreshold = conf.cacheThreshold();
if (uberspect == null) {
throw new IllegalArgumentException("uberspect can not be null");
@@ -283,7 +283,7 @@ public class Engine extends JexlEngine {
jxlt = null;
uberspect.setClassLoader(loader);
if (functions != null) {
- final List<String> names = new
ArrayList<String>(functions.keySet());
+ final Iterable<String> names = new ArrayList<>(functions.keySet());
for(final String name : names) {
final Object functor = functions.get(name);
if (functor instanceof Class<?>) {
@@ -328,7 +328,7 @@ public class Engine extends JexlEngine {
* @param context the context
* @return the options if any
*/
- protected JexlOptions options(final JexlContext context) {
+ protected JexlOptions evalOptions(final JexlContext context) {
// Make a copy of the handled options if any
if (context instanceof JexlContext.OptionsHandle) {
final JexlOptions jexlo = ((JexlContext.OptionsHandle)
context).getEngineOptions();
@@ -336,31 +336,39 @@ public class Engine extends JexlEngine {
return jexlo.isSharedInstance()? jexlo : jexlo.copy();
}
} else if (context instanceof JexlEngine.Options) {
- // This condition and block for compatibility between 3.1 and 3.2
- final JexlOptions jexlo = options.copy();
- final JexlEngine jexl = this;
- final JexlEngine.Options opts = (JexlEngine.Options) context;
- jexlo.setCancellable(option(opts.isCancellable(),
jexl.isCancellable()));
- jexlo.setSilent(option(opts.isSilent(), jexl.isSilent()));
- jexlo.setStrict(option(opts.isStrict(), jexl.isStrict()));
- final JexlArithmetic jexla = jexl.getArithmetic();
- jexlo.setStrictArithmetic(option(opts.isStrictArithmetic(),
jexla.isStrict()));
- jexlo.setMathContext(opts.getArithmeticMathContext());
- jexlo.setMathScale(opts.getArithmeticMathScale());
- return jexlo;
+ return evalOptions((JexlEngine.Options) context);
}
return options;
}
/**
+ * Obsolete version of options evaluation.
+ * @param opts the obsolete instance of options
+ * @return the newer class of options
+ */
+ private JexlOptions evalOptions(final JexlEngine.Options opts) {
+ // This condition and block for compatibility between 3.1 and 3.2
+ final JexlOptions jexlo = options.copy();
+ final JexlEngine jexl = this;
+ jexlo.setCancellable(option(opts.isCancellable(),
jexl.isCancellable()));
+ jexlo.setSilent(option(opts.isSilent(), jexl.isSilent()));
+ jexlo.setStrict(option(opts.isStrict(), jexl.isStrict()));
+ final JexlArithmetic jexla = jexl.getArithmetic();
+ jexlo.setStrictArithmetic(option(opts.isStrictArithmetic(),
jexla.isStrict()));
+ jexlo.setMathContext(opts.getArithmeticMathContext());
+ jexlo.setMathScale(opts.getArithmeticMathScale());
+ return jexlo;
+ }
+
+ /**
* Compute a script options for evaluation.
* <p>This calls processPragma(...).
* @param script the script
* @param context the context
* @return the options
*/
- protected JexlOptions options(final ASTJexlScript script, final
JexlContext context) {
- final JexlOptions opts = options(context);
+ protected JexlOptions evalOptions(final ASTJexlScript script, final
JexlContext context) {
+ final JexlOptions opts = evalOptions(context);
if (opts != options) {
// when feature lexical, try hard to run lexical
if (scriptFeatures.isLexical()) {
@@ -498,9 +506,6 @@ public class Engine extends JexlEngine {
@Override
public Object getProperty(JexlContext context, final Object bean, final
String expr) {
- if (context == null) {
- context = EMPTY_CONTEXT;
- }
// synthesize expr using register
String src = trimSource(expr);
src = "#0" + (src.charAt(0) == '[' ? "" : ".") + src;
@@ -509,11 +514,13 @@ public class Engine extends JexlEngine {
final ASTJexlScript script = parse(null, PROPERTY_FEATURES, src,
scope);
final JexlNode node = script.jjtGetChild(0);
final Frame frame = script.createFrame(bean);
- final Interpreter interpreter = createInterpreter(context, frame,
options);
+ final Interpreter interpreter = createInterpreter(context == null?
EMPTY_CONTEXT : context, frame, options);
return interpreter.visitLexicalNode(node, null);
} catch (final JexlException xjexl) {
if (silent) {
- logger.warn(xjexl.getMessage(), xjexl.getCause());
+ if (logger.isWarnEnabled()) {
+ logger.warn(xjexl.getMessage(), xjexl.getCause());
+ }
return null;
}
throw xjexl.clean();
@@ -539,7 +546,9 @@ public class Engine extends JexlEngine {
interpreter.visitLexicalNode(node, null);
} catch (final JexlException xjexl) {
if (silent) {
- logger.warn(xjexl.getMessage(), xjexl.getCause());
+ if (logger.isWarnEnabled()) {
+ logger.warn(xjexl.getMessage(), xjexl.getCause());
+ }
return;
}
throw xjexl.clean();
@@ -570,8 +579,9 @@ public class Engine extends JexlEngine {
if (!silent) {
throw xjexl.clean();
}
- logger.warn(xjexl.getMessage(), xjexl.getCause());
- result = null;
+ if (logger.isWarnEnabled()) {
+ logger.warn(xjexl.getMessage(), xjexl.getCause());
+ }
}
return result;
}
@@ -614,7 +624,9 @@ public class Engine extends JexlEngine {
}
if (xjexl != null) {
if (silent) {
- logger.warn(xjexl.getMessage(), xjexl.getCause());
+ if (logger.isWarnEnabled()) {
+ logger.warn(xjexl.getMessage(), xjexl.getCause());
+ }
return null;
}
throw xjexl.clean();
@@ -673,11 +685,11 @@ public class Engine extends JexlEngine {
/**
* The collected variables represented as a set of list of strings.
*/
- private final Set<List<String>> refs = new
LinkedHashSet<List<String>>();
+ private final Set<List<String>> refs = new LinkedHashSet<>();
/**
* The current variable being collected.
*/
- private List<String> ref = new ArrayList<String>();
+ private List<String> ref = new ArrayList<>();
/**
* The node that started the collect.
*/
@@ -687,7 +699,7 @@ public class Engine extends JexlEngine {
* if so, > 1 means collect any constant (set,map,...) instead of just
* strings and numbers.
*/
- private int mode = 1;
+ final int mode;
/**
* Constructor.
@@ -704,7 +716,7 @@ public class Engine extends JexlEngine {
public void collect(final JexlNode node) {
if (!ref.isEmpty()) {
refs.add(ref);
- ref = new ArrayList<String>();
+ ref = new ArrayList<>();
}
root = node;
}
@@ -848,7 +860,7 @@ public class Engine extends JexlEngine {
// features = new
JexlFeatures(features).nameSpaces(functions.keySet());
// }
final Source source = cached? new Source(features, src) : null;
- ASTJexlScript script = null;
+ ASTJexlScript script;
if (source != null) {
script = cache.get(source);
if (script != null) {
diff --git a/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java
b/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java
index a1136da..9d262db 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java
@@ -109,7 +109,6 @@ import org.apache.commons.jexl3.parser.ASTUnaryPlusNode;
import org.apache.commons.jexl3.parser.ASTVar;
import org.apache.commons.jexl3.parser.ASTWhileStatement;
import org.apache.commons.jexl3.parser.JexlNode;
-import org.apache.commons.jexl3.parser.Node;
/**
* An interpreter of JEXL syntax.
@@ -128,7 +127,7 @@ public class Interpreter extends InterpreterBase {
* The thread local interpreter.
*/
protected static final java.lang.ThreadLocal<Interpreter> INTER =
- new java.lang.ThreadLocal<Interpreter>();
+ new java.lang.ThreadLocal<>();
/**
* Creates an interpreter.
@@ -743,7 +742,7 @@ public class Interpreter extends InterpreterBase {
protected Object visit(final ASTWhileStatement node, final Object data) {
Object result = null;
/* first objectNode is the condition */
- final Node condition = node.jjtGetChild(0);
+ final JexlNode condition = node.jjtGetChild(0);
while (arithmetic.toBoolean(condition.jjtAccept(this, data))) {
cancelCheck(node);
if (node.jjtGetNumChildren() > 1) {
@@ -765,7 +764,7 @@ public class Interpreter extends InterpreterBase {
Object result = null;
final int nc = node.jjtGetNumChildren();
/* last objectNode is the condition */
- final Node condition = node.jjtGetChild(nc - 1);
+ final JexlNode condition = node.jjtGetChild(nc - 1);
do {
cancelCheck(node);
if (nc > 1) {
@@ -1402,11 +1401,11 @@ public class Interpreter extends InterpreterBase {
}
}
// 2: last objectNode will perform assignement in all cases
- Object property = null;
JexlNode propertyNode = left.jjtGetChild(last);
final ASTIdentifierAccess propertyId = propertyNode instanceof
ASTIdentifierAccess
? (ASTIdentifierAccess) propertyNode
: null;
+ final Object property;
if (propertyId != null) {
// deal with creating/assignining antish variable
if (antish && ant != null && object == null &&
!propertyId.isSafe() && !propertyId.isExpression()) {
@@ -1547,16 +1546,15 @@ public class Interpreter extends InterpreterBase {
cancelCheck(node);
// evaluate the arguments
final Object[] argv = visit(argNode, null);
- // get the method name if identifier
- final int symbol;
final String methodName;
boolean cacheable = cache;
boolean isavar = false;
Object functor = funcNode;
+ // get the method name if identifier
if (functor instanceof ASTIdentifier) {
// function call, target is context or namespace (if there was one)
final ASTIdentifier methodIdentifier = (ASTIdentifier) functor;
- symbol = methodIdentifier.getSymbol();
+ final int symbol = methodIdentifier.getSymbol();
methodName = methodIdentifier.getName();
functor = null;
// is it a global or local variable ?
@@ -1574,12 +1572,10 @@ public class Interpreter extends InterpreterBase {
} else if (functor instanceof ASTIdentifierAccess) {
// a method call on target
methodName = ((ASTIdentifierAccess) functor).getName();
- symbol = -1;
functor = null;
cacheable = true;
} else if (functor != null) {
// ...(x)(y)
- symbol = -1 - 1; // -2;
methodName = null;
cacheable = false;
} else if (!node.isSafeLhs(isSafe())) {
@@ -1872,7 +1868,7 @@ public class Interpreter extends InterpreterBase {
if (jexla == arithmetic) {
return cblock.jjtAccept(Interpreter.this, data);
}
- if (!arithmetic.getClass().equals(jexla.getClass())) {
+ if (!arithmetic.getClass().equals(jexla.getClass()) &&
logger.isWarnEnabled()) {
logger.warn("expected arithmetic to be " +
arithmetic.getClass().getSimpleName()
+ ", got " + jexla.getClass().getSimpleName()
);
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/InterpreterBase.java
b/src/main/java/org/apache/commons/jexl3/internal/InterpreterBase.java
index 6747a11..0e759f3 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/InterpreterBase.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/InterpreterBase.java
@@ -91,9 +91,9 @@ public abstract class InterpreterBase extends ParserVisitor {
this.context = aContext != null ? aContext : Engine.EMPTY_CONTEXT;
this.cache = engine.cache != null;
final JexlArithmetic jexla = jexl.arithmetic;
- this.options = opts == null? engine.options(aContext) : opts;
+ this.options = opts == null? engine.evalOptions(aContext) : opts;
this.arithmetic = jexla.options(options);
- if (arithmetic != jexla &&
!arithmetic.getClass().equals(jexla.getClass())) {
+ if (arithmetic != jexla &&
!arithmetic.getClass().equals(jexla.getClass()) && logger.isWarnEnabled()) {
logger.warn("expected arithmetic to be " +
jexla.getClass().getSimpleName()
+ ", got " + arithmetic.getClass().getSimpleName()
);
@@ -788,33 +788,19 @@ public abstract class InterpreterBase extends
ParserVisitor {
* Helping dispatch function calls.
*/
protected class CallDispatcher {
- /**
- * The syntactic node.
- */
+ /** The syntactic node. */
final JexlNode node;
- /**
- * Whether solution is cacheable.
- */
- boolean cacheable = true;
- /**
- * Whether arguments have been narrowed.
- */
+ /** Whether solution is cacheable. */
+ final boolean cacheable;
+ /** Whether arguments have been narrowed. */
boolean narrow = false;
- /**
- * The method to call.
- */
+ /** The method to call. */
JexlMethod vm = null;
- /**
- * The method invocation target.
- */
+ /** The method invocation target. */
Object target = null;
- /**
- * The actual arguments.
- */
+ /** The actual arguments. */
Object[] argv = null;
- /**
- * The cacheable funcall if any.
- */
+ /** The cacheable funcall if any. */
Funcall funcall = null;
/**
diff --git a/src/main/java/org/apache/commons/jexl3/internal/Script.java
b/src/main/java/org/apache/commons/jexl3/internal/Script.java
index c86b3a7..8e0d1c6 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/Script.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/Script.java
@@ -107,7 +107,7 @@ public class Script implements JexlScript, JexlExpression {
* @return the interpreter
*/
protected Interpreter createInterpreter(final JexlContext context, final
Frame frame) {
- final JexlOptions opts = jexl.options(script, context);
+ final JexlOptions opts = jexl.evalOptions(script, context);
return jexl.createInterpreter(context, frame, opts);
}
@@ -339,4 +339,4 @@ public class Script implements JexlScript, JexlExpression {
return interpreter.isCancellable();
}
}
-}
\ No newline at end of file
+}
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/TemplateDebugger.java
b/src/main/java/org/apache/commons/jexl3/internal/TemplateDebugger.java
index 8934507..2f7fd2d 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/TemplateDebugger.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/TemplateDebugger.java
@@ -45,6 +45,7 @@ public class TemplateDebugger extends Debugger {
* Default ctor.
*/
public TemplateDebugger() {
+ // nothing to initialize
}
@Override
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/TemplateEngine.java
b/src/main/java/org/apache/commons/jexl3/internal/TemplateEngine.java
index 0a54fd4..55c032e 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/TemplateEngine.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/TemplateEngine.java
@@ -24,6 +24,7 @@ import org.apache.commons.jexl3.JxltEngine;
import org.apache.commons.jexl3.parser.ASTJexlScript;
import org.apache.commons.jexl3.parser.JexlNode;
import org.apache.commons.jexl3.parser.StringParser;
+import org.apache.commons.logging.Log;
import java.io.BufferedReader;
import java.io.IOException;
@@ -42,15 +43,17 @@ import java.util.Set;
*/
public final class TemplateEngine extends JxltEngine {
/** The TemplateExpression cache. */
- private final SoftCache<String, TemplateExpression> cache;
+ final SoftCache<String, TemplateExpression> cache;
/** The JEXL engine instance. */
- private final Engine jexl;
+ final Engine jexl;
+ /** The logger. */
+ final Log logger;
/** The first character for immediate expressions. */
- private final char immediateChar;
+ final char immediateChar;
/** The first character for deferred expressions. */
- private final char deferredChar;
+ final char deferredChar;
/** Whether expressions can use JEXL script or only expressions (ie, no
for, var, etc). */
- private boolean noscript = true;
+ final boolean noscript;
/**
* Creates a new instance of {@link JxltEngine} creating a local cache.
@@ -66,6 +69,7 @@ public final class TemplateEngine extends JxltEngine {
final char immediate,
final char deferred) {
this.jexl = aJexl;
+ this.logger = aJexl.logger;
this.cache = new SoftCache<>(cacheSize);
immediateChar = immediate;
deferredChar = deferred;
@@ -113,8 +117,17 @@ public final class TemplateEngine extends JxltEngine {
ExpressionType(final int idx) {
this.index = idx;
}
+
+ /**
+ * @return the index member
+ */
+ int getIndex() {
+ return index;
+ }
}
+
+
/**
* A helper class to build expressions.
* Keeps count of sub-expressions by type.
@@ -123,13 +136,13 @@ public final class TemplateEngine extends JxltEngine {
/** Per TemplateExpression type counters. */
private final int[] counts;
/** The list of expressions. */
- private final ArrayList<TemplateExpression> expressions;
+ private final List<TemplateExpression> expressions;
/**
* Creates a builder.
* @param size the initial TemplateExpression array size
*/
- private ExpressionBuilder(final int size) {
+ ExpressionBuilder(final int size) {
counts = new int[]{0, 0, 0};
expressions = new ArrayList<>(size <= 0 ? 3 : size);
}
@@ -138,8 +151,8 @@ public final class TemplateEngine extends JxltEngine {
* Adds an TemplateExpression to the list of expressions, maintain
per-type counts.
* @param expr the TemplateExpression to add
*/
- private void add(final TemplateExpression expr) {
- counts[expr.getType().index] += 1;
+ void add(final TemplateExpression expr) {
+ counts[expr.getType().getIndex()] += 1;
expressions.add(expr);
}
@@ -153,15 +166,15 @@ public final class TemplateEngine extends JxltEngine {
* @param error the builder to fill
* @return the builder
*/
- private StringBuilder toString(final StringBuilder error) {
+ StringBuilder toString(final StringBuilder error) {
error.append("exprs{");
error.append(expressions.size());
error.append(", constant:");
- error.append(counts[ExpressionType.CONSTANT.index]);
+ error.append(counts[ExpressionType.CONSTANT.getIndex()]);
error.append(", immediate:");
- error.append(counts[ExpressionType.IMMEDIATE.index]);
+ error.append(counts[ExpressionType.IMMEDIATE.getIndex()]);
error.append(", deferred:");
- error.append(counts[ExpressionType.DEFERRED.index]);
+ error.append(counts[ExpressionType.DEFERRED.getIndex()]);
error.append("}");
return error;
}
@@ -172,7 +185,7 @@ public final class TemplateEngine extends JxltEngine {
* @param source the source TemplateExpression
* @return an TemplateExpression
*/
- private TemplateExpression build(final TemplateEngine el, final
TemplateExpression source) {
+ TemplateExpression build(final TemplateEngine el, final
TemplateExpression source) {
int sum = 0;
for (final int count : counts) {
sum += count;
@@ -295,12 +308,14 @@ public final class TemplateEngine extends JxltEngine {
*/
protected final TemplateExpression prepare(final Frame frame, final
JexlContext context) {
try {
- final Interpreter interpreter =
jexl.createInterpreter(context, frame, jexl.options(context));
+ final Interpreter interpreter =
jexl.createInterpreter(context, frame, jexl.evalOptions(context));
return prepare(interpreter);
} catch (final JexlException xjexl) {
final JexlException xuel = createException(xjexl.getInfo(),
"prepare", this, xjexl);
if (jexl.isSilent()) {
- jexl.logger.warn(xuel.getMessage(), xuel.getCause());
+ if (logger.isWarnEnabled()) {
+ logger.warn(xuel.getMessage(), xuel.getCause());
+ }
return null;
}
throw xuel;
@@ -328,7 +343,7 @@ public final class TemplateEngine extends JxltEngine {
* @return the options
*/
protected JexlOptions options(final JexlContext context) {
- return jexl.options(null, context);
+ return jexl.evalOptions(null, context);
}
/**
@@ -351,7 +366,9 @@ public final class TemplateEngine extends JxltEngine {
} catch (final JexlException xjexl) {
final JexlException xuel = createException(xjexl.getInfo(),
"evaluate", this, xjexl);
if (jexl.isSilent()) {
- jexl.logger.warn(xuel.getMessage(), xuel.getCause());
+ if (logger.isWarnEnabled()) {
+ logger.warn(xuel.getMessage(), xuel.getCause());
+ }
return null;
}
throw xuel;
@@ -387,10 +404,9 @@ public final class TemplateEngine extends JxltEngine {
if (val == null) {
throw new NullPointerException("constant can not be null");
}
- if (val instanceof String) {
- val = StringParser.buildTemplate((String) val, false);
- }
- this.value = val;
+ this.value = val instanceof String
+ ? StringParser.buildTemplate((String) val, false)
+ : val;
}
@Override
@@ -442,7 +458,7 @@ public final class TemplateEngine extends JxltEngine {
@Override
protected JexlOptions options(final JexlContext context) {
- return jexl.options(node instanceof ASTJexlScript? (ASTJexlScript)
node : null, context);
+ return jexl.evalOptions(node instanceof ASTJexlScript?
(ASTJexlScript) node : null, context);
}
@Override
@@ -587,11 +603,11 @@ public final class TemplateEngine extends JxltEngine {
* @param list the sub-expressions
* @param src the source for this expression if any
*/
- CompositeExpression(final int[] counters, final
ArrayList<TemplateExpression> list, final TemplateExpression src) {
+ CompositeExpression(final int[] counters, final
List<TemplateExpression> list, final TemplateExpression src) {
super(src);
this.exprs = list.toArray(new TemplateExpression[list.size()]);
- this.meta = (counters[ExpressionType.DEFERRED.index] > 0 ? 2 : 0)
- | (counters[ExpressionType.IMMEDIATE.index] > 0 ? 1 : 0);
+ this.meta = (counters[ExpressionType.DEFERRED.getIndex()] > 0 ? 2
: 0)
+ | (counters[ExpressionType.IMMEDIATE.getIndex()] > 0 ? 1 :
0);
}
@Override
@@ -674,10 +690,8 @@ public final class TemplateEngine extends JxltEngine {
@Override
- public JxltEngine.Expression createExpression(JexlInfo info, final String
expression) {
- if (info == null) {
- info = jexl.createInfo();
- }
+ public JxltEngine.Expression createExpression(JexlInfo jexlInfo, final
String expression) {
+ JexlInfo info = jexlInfo == null? jexl.createInfo() : jexlInfo;
Exception xuel = null;
TemplateExpression stmt = null;
try {
@@ -693,7 +707,9 @@ public final class TemplateEngine extends JxltEngine {
if (!jexl.isSilent()) {
throw xuel;
}
- jexl.logger.warn(xuel.getMessage(), xuel.getCause());
+ if (logger.isWarnEnabled()) {
+ logger.warn(xuel.getMessage(), xuel.getCause());
+ }
stmt = null;
}
return stmt;
@@ -798,8 +814,6 @@ public final class TemplateEngine extends JxltEngine {
for (int column = 0; column < size; ++column) {
final char c = expr.charAt(column);
switch (state) {
- default: // in case we ever add new unified expression type
- throw new UnsupportedOperationException("unexpected
unified expression type");
case CONST:
if (c == immediateChar) {
state = ParseState.IMMEDIATE0;
@@ -931,6 +945,9 @@ public final class TemplateEngine extends JxltEngine {
strb.append(c);
}
state = ParseState.CONST;
+ break;
+ default: // in case we ever add new unified expression type
+ throw new UnsupportedOperationException("unexpected
unified expression type");
}
if (c == '\n') {
lineno += 1;
@@ -1062,8 +1079,8 @@ public final class TemplateEngine extends JxltEngine {
s += 1;
}
if (s < length && pattern.length() <= (length - s)) {
- sequence = sequence.subSequence(s, length);
- if (sequence.subSequence(0, pattern.length()).equals(pattern)) {
+ CharSequence subSequence = sequence.subSequence(s, length);
+ if (subSequence.subSequence(0, pattern.length()).equals(pattern)) {
return s + pattern.length();
}
}
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/TemplateInterpreter.java
b/src/main/java/org/apache/commons/jexl3/internal/TemplateInterpreter.java
index 73d8d5c..f3dffd8 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/TemplateInterpreter.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/TemplateInterpreter.java
@@ -40,9 +40,9 @@ import java.util.Arrays;
*/
public class TemplateInterpreter extends Interpreter {
/** The array of template expressions. */
- private final TemplateExpression[] exprs;
+ final TemplateExpression[] exprs;
/** The writer used to output. */
- private final Writer writer;
+ final Writer writer;
/**
* Helper ctor.
@@ -269,7 +269,7 @@ public class TemplateInterpreter extends Interpreter {
return new Closure(this, (ASTJexlLambda) script) {
@Override
protected Interpreter createInterpreter(final JexlContext
context, final Frame local) {
- final JexlOptions opts = jexl.options(script, context);
+ final JexlOptions opts = jexl.evalOptions(script, context);
final TemplateInterpreter.Arguments targs = new
TemplateInterpreter.Arguments(jexl)
.context(context)
.options(opts)
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/TemplateScript.java
b/src/main/java/org/apache/commons/jexl3/internal/TemplateScript.java
index 337f7de..08d5d43 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/TemplateScript.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/TemplateScript.java
@@ -57,7 +57,7 @@ public final class TemplateScript implements
JxltEngine.Template {
/**
* Creates a new template from an character input.
* @param engine the template engine
- * @param info the source info
+ * @param jexlInfo the source info
* @param directive the prefix for lines of code; can not be "$", "${",
"#" or "#{"
since this would preclude being able to differentiate
directives and jxlt expressions
* @param reader the input reader
@@ -66,7 +66,7 @@ public final class TemplateScript implements
JxltEngine.Template {
* @throws IllegalArgumentException if the directive prefix is invalid
*/
public TemplateScript(final TemplateEngine engine,
- JexlInfo info,
+ JexlInfo jexlInfo,
final String directive,
final Reader reader,
final String... parms) {
@@ -120,9 +120,7 @@ public final class TemplateScript implements
JxltEngine.Template {
}
}
// create the script
- if (info == null) {
- info = jxlt.getEngine().createInfo();
- }
+ final JexlInfo info = jexlInfo == null? jxlt.getEngine().createInfo()
: jexlInfo;
// allow lambda defining params
final Scope scope = parms == null ? null : new Scope(null, parms);
script = jxlt.getEngine().parse(info.at(1, 1), false, strb.toString(),
scope).script();
@@ -259,7 +257,7 @@ public final class TemplateScript implements
JxltEngine.Template {
@Override
public TemplateScript prepare(final JexlContext context) {
final Engine jexl = jxlt.getEngine();
- final JexlOptions options = jexl.options(script, context);
+ final JexlOptions options = jexl.evalOptions(script, context);
final Frame frame = script.createFrame((Object[]) null);
final TemplateInterpreter.Arguments targs = new TemplateInterpreter
.Arguments(jxlt.getEngine())
@@ -274,7 +272,9 @@ public final class TemplateScript implements
JxltEngine.Template {
} catch (final JexlException xjexl) {
final JexlException xuel =
TemplateEngine.createException(xjexl.getInfo(), "prepare", exprs[e], xjexl);
if (jexl.isSilent()) {
- jexl.logger.warn(xuel.getMessage(), xuel.getCause());
+ if (jexl.logger.isWarnEnabled()) {
+ jexl.logger.warn(xuel.getMessage(), xuel.getCause());
+ }
return null;
}
throw xuel;
@@ -291,7 +291,7 @@ public final class TemplateScript implements
JxltEngine.Template {
@Override
public void evaluate(final JexlContext context, final Writer writer, final
Object... args) {
final Engine jexl = jxlt.getEngine();
- final JexlOptions options = jexl.options(script, context);
+ final JexlOptions options = jexl.evalOptions(script, context);
final Frame frame = script.createFrame(args);
final TemplateInterpreter.Arguments targs = new TemplateInterpreter
.Arguments(jexl)
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/introspection/ClassMap.java
b/src/main/java/org/apache/commons/jexl3/internal/introspection/ClassMap.java
index d83a1f2..5f435b8 100644
---
a/src/main/java/org/apache/commons/jexl3/internal/introspection/ClassMap.java
+++
b/src/main/java/org/apache/commons/jexl3/internal/introspection/ClassMap.java
@@ -208,10 +208,10 @@ final class ClassMap {
*
* @param cache the ClassMap instance we create
* @param permissions the permissions to apply during introspection
- * @param classToReflect the class to cache
+ * @param clazz the class to cache
* @param log the Log
*/
- private static void create(final ClassMap cache, final Permissions
permissions, Class<?> classToReflect, final Log log) {
+ private static void create(final ClassMap cache, final Permissions
permissions, Class<?> clazz, final Log log) {
//
// Build a list of all elements in the class hierarchy. This one is
bottom-first (i.e. we start
// with the actual declaring class and its interfaces and then move up
(superclass etc.) until we
@@ -220,7 +220,7 @@ final class ClassMap {
//
// We also ignore all SecurityExceptions that might happen due to
SecurityManager restrictions.
//
- for (; classToReflect != null; classToReflect =
classToReflect.getSuperclass()) {
+ for (Class<?> classToReflect = clazz; classToReflect != null;
classToReflect = classToReflect.getSuperclass()) {
if (Modifier.isPublic(classToReflect.getModifiers())) {
populateWithClass(cache, permissions, classToReflect, log);
}
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/introspection/IndexedType.java
b/src/main/java/org/apache/commons/jexl3/internal/introspection/IndexedType.java
index d851ff2..9cfba39 100644
---
a/src/main/java/org/apache/commons/jexl3/internal/introspection/IndexedType.java
+++
b/src/main/java/org/apache/commons/jexl3/internal/introspection/IndexedType.java
@@ -29,10 +29,10 @@ import java.beans.IntrospectionException;
* It implements JexlPropertyGet since such a container can only be accessed
from its owning instance (not set).
*/
public final class IndexedType implements JexlPropertyGet {
- /** The container name. */
- private final String container;
+ /** The container name. */
+ final String container;
/** The container class. */
- private final Class<?> clazz;
+ final Class<?> clazz;
/** The array of getter methods. */
private final Method[] getters;
/** Last get method used. */
@@ -74,16 +74,16 @@ public final class IndexedType implements JexlPropertyGet {
*/
public static final class IndexedContainer {
/** The container instance. */
- private final Object container;
+ final Object container;
/** The container type instance. */
- private final IndexedType type;
+ final IndexedType type;
/**
* Creates a new duck container.
* @param theType the container type
* @param theContainer the container instance
*/
- private IndexedContainer(final IndexedType theType, final Object
theContainer) {
+ IndexedContainer(final IndexedType theType, final Object theContainer)
{
this.type = theType;
this.container = theContainer;
}
@@ -176,7 +176,7 @@ public final class IndexedType implements JexlPropertyGet {
* @throws Exception if invocation failed;
* IntrospectionException if a property getter could not be found
*/
- private Object invokeGet(final Object object, final Object key) throws
Exception {
+ Object invokeGet(final Object object, final Object key) throws Exception {
if (getters != null && getters.length > 0) {
Method jm = get;
if (jm != null) {
@@ -209,7 +209,7 @@ public final class IndexedType implements JexlPropertyGet {
* @throws Exception if invocation failed;
* IntrospectionException if a property setter could not be found
*/
- private Object invokeSet(final Object object, final Object key, final
Object value) throws Exception {
+ Object invokeSet(final Object object, final Object key, final Object
value) throws Exception {
if (setters != null && setters.length > 0) {
Method jm = set;
if (jm != null) {
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/introspection/Introspector.java
b/src/main/java/org/apache/commons/jexl3/internal/introspection/Introspector.java
index 3cfddba..8054ba5 100644
---
a/src/main/java/org/apache/commons/jexl3/internal/introspection/Introspector.java
+++
b/src/main/java/org/apache/commons/jexl3/internal/introspection/Introspector.java
@@ -326,14 +326,12 @@ public final class Introspector {
/**
* Sets the class loader used to solve constructors.
* <p>Also cleans the constructors and methods caches.</p>
- * @param cloader the class loader; if null, use this instance class loader
+ * @param classLoader the class loader; if null, use this instance class
loader
*/
- public void setLoader(ClassLoader cloader) {
+ public void setLoader(ClassLoader classLoader) {
final ClassLoader previous = loader;
- if (cloader == null) {
- cloader = getClass().getClassLoader();
- }
- if (!cloader.equals(loader)) {
+ final ClassLoader current = classLoader == null?
getClass().getClassLoader() : classLoader;
+ if (!current.equals(loader)) {
lock.writeLock().lock();
try {
// clean up constructor and class maps
@@ -356,7 +354,7 @@ public final class Introspector {
centries.remove();
}
}
- loader = cloader;
+ loader = current;
} finally {
lock.writeLock().unlock();
}
@@ -389,4 +387,4 @@ public final class Introspector {
}
return false;
}
-}
\ No newline at end of file
+}
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/introspection/MethodExecutor.java
b/src/main/java/org/apache/commons/jexl3/internal/introspection/MethodExecutor.java
index c97c4f4..0ecab6d 100644
---
a/src/main/java/org/apache/commons/jexl3/internal/introspection/MethodExecutor.java
+++
b/src/main/java/org/apache/commons/jexl3/internal/introspection/MethodExecutor.java
@@ -112,15 +112,16 @@ public final class MethodExecutor extends
AbstractExecutor.Method {
/**
* Reassembles arguments if the method is a vararg method.
- * @param actual The actual arguments being passed to this method
+ * @param args The actual arguments being passed to this method
* @return The actual parameters adjusted for the varargs in order
* to fit the method declaration.
*/
@SuppressWarnings("SuspiciousSystemArraycopy")
- private Object[] handleVarArg(Object[] actual) {
+ private Object[] handleVarArg(Object[] args) {
final Class<?> vaclass = vaClass;
final int vastart = vaStart;
// variable arguments count
+ Object[] actual = args;
final int varargc = actual.length - vastart;
// if no values are being passed into the vararg, size == 0
if (varargc == 1) {
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/introspection/MethodKey.java
b/src/main/java/org/apache/commons/jexl3/internal/introspection/MethodKey.java
index 445a84f..8abf9fa 100644
---
a/src/main/java/org/apache/commons/jexl3/internal/introspection/MethodKey.java
+++
b/src/main/java/org/apache/commons/jexl3/internal/introspection/MethodKey.java
@@ -20,10 +20,10 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
+import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
-import java.util.List;
import java.util.Map;
/**
@@ -165,7 +165,7 @@ public final class MethodKey {
}
/**
- * Outputs a human readable debug representation of this key.
+ * Outputs a human-readable debug representation of this key.
* @return method(p0, p1, ...)
*/
public String debugString() {
@@ -183,7 +183,7 @@ public final class MethodKey {
/**
* Checks whether a method accepts a variable number of arguments.
- * <p>May be due to a subtle bug in some JVMs, if a varargs method is an
override, depending on (may be) the
+ * <p>May be due to a subtle bug in some JVMs, if a varargs method is an
override, depending on (perhaps) the
* class introspection order, the isVarargs flag on the method itself will
be false.
* To circumvent the potential problem, fetch the method with the same
signature from the super-classes,
* - which will be different if override -and get the varargs flag from
it.
@@ -252,11 +252,11 @@ public final class MethodKey {
* @param formal the formal parameter type to which the actual
* parameter type should be convertible
* @param actual the actual parameter type.
- * @param possibleVarArg whether or not we're dealing with the last
parameter
+ * @param possibleVarArg whether we're dealing with the last parameter
* in the method declaration
* @return true if either formal type is assignable from actual type,
* or formal is a primitive type and actual is its corresponding
object
- * type or an object type of a primitive type that can be
converted to
+ * type or an object-type of a primitive type that can be
converted to
* the formal type.
*/
public static boolean isInvocationConvertible(final Class<?> formal,
@@ -275,7 +275,7 @@ public final class MethodKey {
* @param formal the formal parameter type to which the actual
* parameter type should be convertible
* @param actual the actual parameter type.
- * @param possibleVarArg whether or not we're dealing with the last
parameter
+ * @param possibleVarArg whether not we're dealing with the last parameter
* in the method declaration
* @return true if either formal type is assignable from actual type,
* or formal and actual are both primitive types and actual can be
@@ -320,7 +320,7 @@ public final class MethodKey {
*/
private static final Map<Class<?>, Class<?>[]> CONVERTIBLES;
static {
- CONVERTIBLES = new HashMap<Class<?>, Class<?>[]>(PRIMITIVE_SIZE);
+ CONVERTIBLES = new HashMap<>(PRIMITIVE_SIZE);
CONVERTIBLES.put(Boolean.TYPE,
asArray(Boolean.class));
CONVERTIBLES.put(Character.TYPE,
@@ -346,7 +346,7 @@ public final class MethodKey {
*/
private static final Map<Class<?>, Class<?>[]> STRICT_CONVERTIBLES;
static {
- STRICT_CONVERTIBLES = new HashMap<Class<?>,
Class<?>[]>(PRIMITIVE_SIZE);
+ STRICT_CONVERTIBLES = new HashMap<>(PRIMITIVE_SIZE);
STRICT_CONVERTIBLES.put(Short.TYPE,
asArray(Byte.TYPE));
STRICT_CONVERTIBLES.put(Integer.TYPE,
@@ -363,18 +363,19 @@ public final class MethodKey {
* Determines parameter-argument invocation compatibility.
*
* @param formal the formal parameter type
- * @param actual the argument type
+ * @param type the argument type
* @param strict whether the check is strict or not
- * @param possibleVarArg whether or not we're dealing with the last
parameter in the method declaration
+ * @param possibleVarArg whether we're dealing with the last parameter in
the method declaration
* @return true if compatible, false otherwise
*/
private static boolean isInvocationConvertible(
- final Class<?> formal, Class<?> actual, final boolean strict,
final boolean possibleVarArg) {
- /* if it's a null, it means the arg was null */
+ final Class<?> formal, Class<?> type, final boolean strict, final
boolean possibleVarArg) {
+ Class<?> actual = type;
+ /* if it is a null, it means the arg was null */
if (actual == null && !formal.isPrimitive()) {
return true;
}
- /* system asssignable, both sides must be array or not */
+ /* system asssignable, both sides must be arrays or not */
if (actual != null && formal.isAssignableFrom(actual) &&
actual.isArray() == formal.isArray()) {
return true;
}
@@ -466,7 +467,6 @@ public final class MethodKey {
*/
protected abstract boolean isVarArgs(T app);
- // CSOFF: RedundantThrows
/**
* Gets the most specific method that is applicable to actual argument
types.<p>
* Attempts to find the most specific applicable method using the
@@ -486,9 +486,9 @@ public final class MethodKey {
* @return the most specific method.
* @throws MethodKey.AmbiguousException if there is more than one.
*/
- private T getMostSpecific(final MethodKey key, final T[] methods) {
- final Class<?>[] args = key.params;
- final LinkedList<T> applicables = getApplicables(methods, args);
+ T getMostSpecific(final MethodKey key, final T[] methods) {
+ final Class<?>[] args = key.getParameters();
+ final Deque<T> applicables = getApplicables(methods, args);
if (applicables.isEmpty()) {
return null;
}
@@ -502,7 +502,7 @@ public final class MethodKey {
* the end of the below loop, the list will contain exactly one
method,
* (the most specific method) otherwise we have ambiguity.
*/
- final LinkedList<T> maximals = new LinkedList<T>();
+ final Deque<T> maximals = new LinkedList<>();
for (final T app : applicables) {
final Class<?>[] parms = getParameterTypes(app);
boolean lessSpecific = false;
@@ -529,7 +529,7 @@ public final class MethodKey {
lessSpecific = true;
break;
default:
- // nothing do do
+ // nothing to do
}
}
@@ -564,7 +564,7 @@ public final class MethodKey {
* @param applicables the list of applicable methods or constructors
* @return an ambiguous exception
*/
- private AmbiguousException ambiguousException (final Class<?>[]
classes, final List<T> applicables) {
+ private AmbiguousException ambiguousException (final Class<?>[]
classes, final Deque<T> applicables) {
boolean severe = false;
int instanceArgCount = 0; // count the number of valid instances,
aka not null
for(int c = 0; c < classes.length; ++c) {
@@ -677,8 +677,8 @@ public final class MethodKey {
* formal and actual arguments matches, and argument types are
assignable
* to formal types through a method invocation conversion).
*/
- private LinkedList<T> getApplicables(final T[] methods, final
Class<?>[] classes) {
- final LinkedList<T> list = new LinkedList<T>();
+ private Deque<T> getApplicables(final T[] methods, final Class<?>[]
classes) {
+ final Deque<T> list = new LinkedList<>();
for (final T method : methods) {
if (isApplicable(method, classes)) {
list.add(method);
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/introspection/Permissions.java
b/src/main/java/org/apache/commons/jexl3/internal/introspection/Permissions.java
index 7f8baaf..c6fd0ee 100644
---
a/src/main/java/org/apache/commons/jexl3/internal/introspection/Permissions.java
+++
b/src/main/java/org/apache/commons/jexl3/internal/introspection/Permissions.java
@@ -156,7 +156,7 @@ public class Permissions {
* @param interf whether interfaces should be checked as well
* @return true if JEXL is allowed to introspect, false otherwise
*/
- protected boolean allow(Class<?> clazz, final boolean interf) {
+ protected boolean allow(final Class<?> clazz, final boolean interf) {
if (clazz == null) {
return false;
}
@@ -174,15 +174,15 @@ public class Permissions {
}
}
// lets walk all super classes
- clazz = clazz.getSuperclass();
+ Class<?> walk = clazz.getSuperclass();
// walk all superclasses
- while (clazz != null) {
+ while (walk != null) {
// is clazz annotated with nojexl ?
- final NoJexl nojexl = clazz.getAnnotation(NoJexl.class);
+ final NoJexl nojexl = walk.getAnnotation(NoJexl.class);
if (nojexl != null) {
return false;
}
- clazz = clazz.getSuperclass();
+ walk = walk.getSuperclass();
}
return true;
}
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/introspection/PropertySetExecutor.java
b/src/main/java/org/apache/commons/jexl3/internal/introspection/PropertySetExecutor.java
index f883371..0943d49 100644
---
a/src/main/java/org/apache/commons/jexl3/internal/introspection/PropertySetExecutor.java
+++
b/src/main/java/org/apache/commons/jexl3/internal/introspection/PropertySetExecutor.java
@@ -75,7 +75,8 @@ public class PropertySetExecutor extends AbstractExecutor.Set
{
}
@Override
- public Object invoke(final Object o, Object arg) throws
IllegalAccessException, InvocationTargetException {
+ public Object invoke(final Object o, final Object argument) throws
IllegalAccessException, InvocationTargetException {
+ Object arg = argument;
if (method != null) {
// handle the empty array case
if (isEmptyArray(arg)) {
@@ -86,8 +87,8 @@ public class PropertySetExecutor extends AbstractExecutor.Set
{
arg = Array.newInstance(componentType, 0);
}
}
- method.invoke(o, arg);
- }
+ method.invoke(o, arg);
+ }
return arg;
}
diff --git
a/src/main/java/org/apache/commons/jexl3/internal/introspection/Uberspect.java
b/src/main/java/org/apache/commons/jexl3/internal/introspection/Uberspect.java
index 8ca1379..6125ebf 100644
---
a/src/main/java/org/apache/commons/jexl3/internal/introspection/Uberspect.java
+++
b/src/main/java/org/apache/commons/jexl3/internal/introspection/Uberspect.java
@@ -420,7 +420,7 @@ public class Uberspect implements JexlUberspect {
* @param theArithmetic the arithmetic instance
* @param theOverloads the overloaded operators
*/
- private ArithmeticUberspect(final JexlArithmetic theArithmetic, final
Set<JexlOperator> theOverloads) {
+ ArithmeticUberspect(final JexlArithmetic theArithmetic, final
Set<JexlOperator> theOverloads) {
this.arithmetic = theArithmetic;
this.overloads = theOverloads;
}
diff --git a/src/main/java/org/apache/commons/jexl3/parser/ASTJexlScript.java
b/src/main/java/org/apache/commons/jexl3/parser/ASTJexlScript.java
index ed5f908..25eb84e 100644
--- a/src/main/java/org/apache/commons/jexl3/parser/ASTJexlScript.java
+++ b/src/main/java/org/apache/commons/jexl3/parser/ASTJexlScript.java
@@ -25,12 +25,14 @@ import org.apache.commons.jexl3.internal.Frame;
* Enhanced script to allow parameters declaration.
*/
public class ASTJexlScript extends JexlLexicalNode {
+ /** serial uid.*/
+ private static final long serialVersionUID = 202112111533L;
/** The pragmas. */
private Map<String, Object> pragmas = null;
/** Features. */
- private JexlFeatures features = null;
+ private transient JexlFeatures features = null;
/** The script scope. */
- private Scope scope = null;
+ private transient Scope scope = null;
public ASTJexlScript(final int id) {
super(id);
diff --git
a/src/main/java/org/apache/commons/jexl3/parser/ASTNumberLiteral.java
b/src/main/java/org/apache/commons/jexl3/parser/ASTNumberLiteral.java
index 24bd257..4ed052d 100644
--- a/src/main/java/org/apache/commons/jexl3/parser/ASTNumberLiteral.java
+++ b/src/main/java/org/apache/commons/jexl3/parser/ASTNumberLiteral.java
@@ -17,6 +17,7 @@
package org.apache.commons.jexl3.parser;
public final class ASTNumberLiteral extends JexlNode implements
JexlNode.Constant<Number> {
+ /** The number parser. */
private final NumberParser nlp;
ASTNumberLiteral(final int id) {
diff --git a/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java
b/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java
index f56fdb4..ed171ba 100644
--- a/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java
+++ b/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java
@@ -589,11 +589,12 @@ public abstract class JexlParser extends StringParser {
/**
* Throws a feature exception.
* @param feature the feature code
- * @param token the token that triggered it
+ * @param trigger the token that triggered it
* @throws JexlException.Parsing if actual error token can not be found
* @throws JexlException.Feature in all other cases
*/
- protected void throwFeatureException(final int feature, Token token) {
+ protected void throwFeatureException(final int feature, Token trigger) {
+ Token token = trigger;
if (token == null) {
token = this.getToken(0);
if (token == null) {
@@ -607,20 +608,21 @@ public abstract class JexlParser extends StringParser {
/**
* Creates a parsing exception.
* @param xclazz the class of exception
- * @param tok the token to report
+ * @param parsed the token to report
* @param <T> the parsing exception subclass
* @throws JexlException.Parsing in all cases
*/
- protected <T extends JexlException.Parsing> void
throwParsingException(final Class<T> xclazz, Token tok) {
+ protected <T extends JexlException.Parsing> void
throwParsingException(final Class<T> xclazz, final Token parsed) {
JexlInfo xinfo = null;
String msg = "unrecoverable state";
JexlException.Parsing xparse = null;
- if (tok == null) {
- tok = this.getToken(0);
+ Token token = parsed;
+ if (token == null) {
+ token = this.getToken(0);
}
- if (tok != null) {
- xinfo = info.at(tok.beginLine, tok.beginColumn);
- msg = tok.image;
+ if (token != null) {
+ xinfo = info.at(token.beginLine, token.beginColumn);
+ msg = token.image;
if (xclazz != null) {
try {
final Constructor<T> ctor =
xclazz.getConstructor(JexlInfo.class, String.class);
diff --git a/src/main/java/org/apache/commons/jexl3/parser/NumberParser.java
b/src/main/java/org/apache/commons/jexl3/parser/NumberParser.java
index 538660b..20a89d6 100644
--- a/src/main/java/org/apache/commons/jexl3/parser/NumberParser.java
+++ b/src/main/java/org/apache/commons/jexl3/parser/NumberParser.java
@@ -16,6 +16,7 @@
*/
package org.apache.commons.jexl3.parser;
+import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
@@ -25,7 +26,7 @@ import java.util.Locale;
/**
* Parses number literals.
*/
-public final class NumberParser {
+public final class NumberParser implements Serializable {
/** The type literal value. */
private Number literal = null;
/** The expected class. */
@@ -111,10 +112,11 @@ public final class NumberParser {
* Sets this node as a natural literal.
* Originally from OGNL.
* @param negative whether the natural should be negative
- * @param s the natural as string
+ * @param natural the natural as string
* @return this parser instance
*/
- NumberParser assignNatural(boolean negative, String s) {
+ NumberParser assignNatural(boolean negative, String natural) {
+ String s = natural;
Number result;
Class<? extends Number> rclass;
// determine the base
diff --git a/src/main/java/org/apache/commons/jexl3/parser/SimpleNode.java
b/src/main/java/org/apache/commons/jexl3/parser/SimpleNode.java
index 2ef0e83..0a83e9a 100644
--- a/src/main/java/org/apache/commons/jexl3/parser/SimpleNode.java
+++ b/src/main/java/org/apache/commons/jexl3/parser/SimpleNode.java
@@ -39,7 +39,7 @@ public class SimpleNode implements Node {
/** The node type id. */
protected final int id;
/** volatile value so it can be used as a last evaluation cache. */
- private volatile Object value;
+ private transient volatile Object value;
/**
* Creates a SimpleNode instance.
@@ -181,7 +181,7 @@ public class SimpleNode implements Node {
/* Override this method if you want to customize how the JexlNode dumps
out its children. */
public void dump(final String prefix) {
- System.out.println(toString(prefix));
+ dumpOut(toString(prefix));
if (children != null) {
for (final SimpleNode n : children) {
if (n != null) {
@@ -191,6 +191,14 @@ public class SimpleNode implements Node {
}
}
+ /**
+ * Override to dump output somewhere.
+ * @param str the string to output
+ */
+ protected void dumpOut(String str) {
+ // override to obtain an output
+ }
+
@Override
public int getId() {
return id;
diff --git a/src/main/java/org/apache/commons/jexl3/parser/StringParser.java
b/src/main/java/org/apache/commons/jexl3/parser/StringParser.java
index f3f15ae..89e2bf9 100644
--- a/src/main/java/org/apache/commons/jexl3/parser/StringParser.java
+++ b/src/main/java/org/apache/commons/jexl3/parser/StringParser.java
@@ -35,7 +35,8 @@ package org.apache.commons.jexl3.parser;
*/
public class StringParser {
/** Default constructor. */
- public StringParser() {
+ protected StringParser() {
+ // nothing to initialize
}
/**
@@ -179,7 +180,7 @@ public class StringParser {
private static int readUnicodeChar(final StringBuilder strb, final
CharSequence str, final int begin) {
char xc = 0;
int bits = SHIFT;
- int value = 0;
+ int value;
for (int offset = 0; offset < UCHAR_LEN; ++offset) {
final char c = str.charAt(begin + offset);
if (c >= '0' && c <= '9') {
@@ -221,31 +222,34 @@ public class StringParser {
case 0:
continue;
case '\b':
- strb.append("\\b");
+ strb.append('\\');
+ strb.append('b');
break;
case '\t':
- strb.append("\\t");
+ strb.append('\\');
+ strb.append('t');
break;
case '\n':
- strb.append("\\n");
+ strb.append('\\');
+ strb.append('n');
break;
case '\f':
- strb.append("\\f");
+ strb.append('\\');
+ strb.append('f');
break;
case '\r':
- strb.append("\\r");
- break;
- case '\"':
- strb.append("\\\"");
- break;
- case '\'':
- strb.append("\\\'");
+ strb.append('\\');
+ strb.append('r');
break;
case '\\':
- strb.append("\\\\");
+ strb.append('\\');
+ strb.append('\\');
break;
default:
- if (c >= FIRST_ASCII && c <= LAST_ASCII) {
+ if (c == delim) {
+ strb.append('\\');
+ strb.append(delim);
+ } else if (c >= FIRST_ASCII && c <= LAST_ASCII) {
strb.append(c);
} else {
// convert to Unicode escape sequence
@@ -278,7 +282,7 @@ public class StringParser {
if (c == '\\') {
if (strb == null) {
strb = new StringBuilder(last);
- strb.append(str.substring(0, n));
+ strb.append(str, 0, n);
}
} else if (strb != null) {
strb.append(c);
@@ -308,7 +312,7 @@ public class StringParser {
case '\\': {
if (strb == null) {
strb = new StringBuilder(last);
- strb.append(str.substring(0, n));
+ strb.append(str, 0, n);
}
strb.append('\\');
strb.append(c);
diff --git
a/src/main/java/org/apache/commons/jexl3/scripting/JexlScriptEngine.java
b/src/main/java/org/apache/commons/jexl3/scripting/JexlScriptEngine.java
index b7ca530..a8eaa42 100644
--- a/src/main/java/org/apache/commons/jexl3/scripting/JexlScriptEngine.java
+++ b/src/main/java/org/apache/commons/jexl3/scripting/JexlScriptEngine.java
@@ -36,6 +36,7 @@ import javax.script.SimpleBindings;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlEngine;
+import org.apache.commons.jexl3.JexlException;
import org.apache.commons.jexl3.JexlScript;
import org.apache.commons.logging.Log;
@@ -64,10 +65,10 @@ import org.apache.commons.logging.LogFactory;
public class JexlScriptEngine extends AbstractScriptEngine implements
Compilable {
/** The logger. */
- private static final Log LOG = LogFactory.getLog(JexlScriptEngine.class);
+ static final Log LOG = LogFactory.getLog(JexlScriptEngine.class);
/** The shared expression cache size. */
- private static final int CACHE_SIZE = 512;
+ static final int CACHE_SIZE = 512;
/** Reserved key for context (mandated by JSR-223). */
public static final String CONTEXT_KEY = "context";
@@ -76,13 +77,13 @@ public class JexlScriptEngine extends AbstractScriptEngine
implements Compilable
public static final String JEXL_OBJECT_KEY = "JEXL";
/** The JexlScriptObject instance. */
- private final JexlScriptObject jexlObject;
+ final JexlScriptObject jexlObject;
/** The factory which created this instance. */
- private final ScriptEngineFactory parentFactory;
+ final ScriptEngineFactory parentFactory;
/** The JEXL EL engine. */
- private final JexlEngine jexlEngine;
+ final JexlEngine jexlEngine;
/**
* Default constructor.
@@ -227,7 +228,7 @@ public class JexlScriptEngine extends AbstractScriptEngine
implements Compilable
final JexlContext ctxt = new JexlContextWrapper(context);
return jexlScript.execute(ctxt);
} catch (final Exception e) {
- throw new ScriptException(e.toString());
+ throw scriptException(e);
}
}
@@ -246,10 +247,22 @@ public class JexlScriptEngine extends
AbstractScriptEngine implements Compilable
final JexlScript jexlScript = jexlEngine.createScript(script);
return new JexlCompiledScript(jexlScript);
} catch (final Exception e) {
- throw new ScriptException(e.toString());
+ throw scriptException(e);
}
}
+ static ScriptException scriptException(Exception e) {
+ Exception xany = e;
+ // unwrap a jexl exception
+ if (xany instanceof JexlException) {
+ Throwable cause = xany.getCause();
+ if (cause instanceof Exception) {
+ xany = (Exception) cause;
+ }
+ }
+ return new ScriptException(xany);
+ }
+
@Override
public CompiledScript compile(final Reader script) throws ScriptException {
// This is mandated by JSR-223
@@ -316,14 +329,14 @@ public class JexlScriptEngine extends
AbstractScriptEngine implements Compilable
*/
private final class JexlContextWrapper implements JexlContext {
/** The wrapped script context. */
- private final ScriptContext scriptContext;
+ final ScriptContext scriptContext;
/**
* Creates a context wrapper.
*
* @param theContext the engine context.
*/
- private JexlContextWrapper (final ScriptContext theContext){
+ JexlContextWrapper (final ScriptContext theContext){
scriptContext = theContext;
}
@@ -368,7 +381,7 @@ public class JexlScriptEngine extends AbstractScriptEngine
implements Compilable
*
* @param theScript to wrap
*/
- private JexlCompiledScript(final JexlScript theScript) {
+ JexlCompiledScript(final JexlScript theScript) {
script = theScript;
}
@@ -385,7 +398,7 @@ public class JexlScriptEngine extends AbstractScriptEngine
implements Compilable
final JexlContext ctxt = new JexlContextWrapper(context);
return script.execute(ctxt);
} catch (final Exception e) {
- throw new ScriptException(e.toString());
+ throw scriptException(e);
}
}
diff --git a/src/main/java/org/apache/commons/jexl3/scripting/Main.java
b/src/main/java/org/apache/commons/jexl3/scripting/Main.java
index 9e26acb..c481408 100644
--- a/src/main/java/org/apache/commons/jexl3/scripting/Main.java
+++ b/src/main/java/org/apache/commons/jexl3/scripting/Main.java
@@ -22,6 +22,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
+import java.io.PrintStream;
import java.nio.charset.Charset;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
@@ -69,10 +70,11 @@ public class Main {
public static void main(final String[] args) throws Exception {
final JexlScriptEngineFactory fac = new JexlScriptEngineFactory();
final ScriptEngine engine = fac.getScriptEngine();
+ final PrintStream out = System.out;
engine.put("args", args);
if (args.length == 1){
final Object value = engine.eval(read(null, args[0]));
- System.out.println("Return value: "+value);
+ out.println("Return value: "+value);
} else {
final BufferedReader console = read(null, null);
String line;
@@ -80,11 +82,11 @@ public class Main {
while(null != (line=console.readLine())){
try {
final Object value = engine.eval(line);
- System.out.println("Return value: "+value);
+ out.println("Return value: "+value);
} catch (final ScriptException e) {
- System.out.println(e.getLocalizedMessage());
+ out.println(e.getLocalizedMessage());
}
- System.out.print("> ");
+ out.print("> ");
}
}
}
diff --git a/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java
b/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java
index b1f4d82..3cc31b6 100644
--- a/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java
+++ b/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java
@@ -33,6 +33,7 @@ import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.nio.charset.StandardCharsets;
+import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -42,10 +43,17 @@ public class ArithmeticTest extends JexlTestCase {
/** A small delta to compare doubles. */
private static final double EPSILON = 1.e-6;
private final Asserter asserter;
+ private final JexlArithmetic jexla;
+ private final JexlArithmetic jexlb;
+ private final Date date = new Date();
public ArithmeticTest() {
super("ArithmeticTest");
asserter = new Asserter(JEXL);
+ jexla = JEXL.getArithmetic();
+ JexlOptions options = new JexlOptions();
+ options.setStrictArithmetic(false);
+ jexlb = jexla.options(options);
}
@Before
@@ -53,6 +61,137 @@ public class ArithmeticTest extends JexlTestCase {
public void setUp() {
}
+ static private void assertNullOperand(java.util.function.Supplier<Object>
fun) {
+ try {
+ Assert.assertNull(fun.get());
+ } catch(JexlArithmetic.NullOperand xany) {
+ Assert.assertNotNull(xany);
+ }
+ }
+
+ static private void
assertArithmeticException(java.util.function.Supplier<Object> fun) {
+ try {
+ Assert.assertNull(fun.get());
+ } catch(ArithmeticException xany) {
+ Assert.assertNotNull(xany);
+ }
+ }
+
+ @Test
+ public void testModEdge() {
+ assertNullOperand(() -> jexla.mod(null, null));
+ Assert.assertEquals(0, jexlb.mod(null, null));
+ assertArithmeticException(() -> jexla.mod(1, 0));
+ assertArithmeticException(() -> jexla.mod(1L, 0L));
+ assertArithmeticException(() -> jexla.mod(1f, 0f));
+ assertArithmeticException(() -> jexla.mod(1d, 0d));
+ assertArithmeticException(() -> jexla.mod(BigInteger.ONE,
BigInteger.ZERO));
+ assertArithmeticException(() -> jexla.mod(BigInteger.ONE,
BigDecimal.ZERO));
+ assertNullOperand(()-> jexla.divide(null, null));
+ }
+
+ @Test
+ public void testUnaryopsEdges() {
+ assertArithmeticException(()-> jexla.positivize(date) );
+ assertNullOperand(()-> jexla.positivize(null));
+ Assert.assertNull(jexlb.positivize(null));
+ Assert.assertEquals(42, jexla.positivize((char) 42));
+ Assert.assertEquals(Boolean.TRUE, jexla.positivize(Boolean.TRUE));
+ Assert.assertEquals(Boolean.FALSE, jexla.positivize(Boolean.FALSE));
+ Assert.assertEquals(Boolean.TRUE, jexla.positivize(new
AtomicBoolean(true)));
+ Assert.assertEquals(Boolean.FALSE, jexla.positivize(new
AtomicBoolean(false)));
+
+ assertNullOperand(()-> jexla.negate(null));
+ Assert.assertNull(jexlb.negate(null));
+ assertArithmeticException(()-> jexla.negate(date));
+ Assert.assertEquals(Boolean.FALSE, jexla.negate(Boolean.TRUE));
+ Assert.assertEquals(Boolean.TRUE, jexla.negate(Boolean.FALSE));
+ }
+
+ @Test
+ public void testDivideEdges() {
+ assertNullOperand(()-> jexla.divide(null, null));
+ Assert.assertEquals(0, jexlb.divide(null, null));
+ assertNullOperand(() -> jexla.divide(null, null));
+ Assert.assertEquals(0, jexlb.mod(null, null));
+ assertArithmeticException(() -> jexla.divide(1, 0));
+ assertArithmeticException(() -> jexla.divide(1L, 0L));
+ assertArithmeticException(() -> jexla.divide(1f, 0f));
+ assertArithmeticException(() -> jexla.divide(1d, 0d));
+ assertArithmeticException(() -> jexla.divide(BigInteger.ONE,
BigInteger.ZERO));
+ assertArithmeticException(() -> jexla.divide(BigInteger.ONE,
BigDecimal.ZERO));
+ }
+
+
+ @Test
+ public void testOperatorsEdges() {
+ assertNullOperand(()-> jexla.multiply(null, null));
+ Assert.assertEquals(0, jexlb.multiply(null, null));
+ assertNullOperand(()-> jexla.add(null, null));
+ Assert.assertEquals(0, jexlb.add(null, null));
+ assertNullOperand(()-> jexla.subtract(null, null));
+ Assert.assertEquals(0, jexlb.subtract(null, null));
+
+ Assert.assertTrue(jexla.contains(null, null));
+ Assert.assertFalse(jexla.contains(true, null));
+ Assert.assertFalse(jexla.contains(null, true));
+ Assert.assertTrue(jexla.endsWith(null, null));
+ Assert.assertFalse(jexla.endsWith(true, null));
+ Assert.assertFalse(jexla.endsWith(null, true));
+ Assert.assertTrue(jexla.startsWith(null, null));
+ Assert.assertFalse(jexla.startsWith(true, null));
+ Assert.assertFalse(jexla.startsWith(null, true));
+ Assert.assertTrue(jexla.isEmpty(null));
+ }
+
+ @Test
+ public void testIntegerCoercionEdges() {
+ assertNullOperand(()-> jexla.toBoolean(null));
+ Assert.assertTrue(jexla.toBoolean(date));
+ // int coercions
+ assertNullOperand(()-> jexla.toInteger(null));
+ Assert.assertEquals(0, jexlb.toInteger(null));
+ assertArithmeticException(()-> jexla.toInteger(date));
+ Assert.assertEquals(0, jexla.toInteger(Double.NaN));
+ Assert.assertEquals(0, jexla.toInteger(""));
+ Assert.assertEquals((int) 'b', jexla.toInteger('b'));
+ Assert.assertEquals(1, jexla.toInteger(new AtomicBoolean(true)));
+ Assert.assertEquals(0, jexla.toInteger(new AtomicBoolean(false)));
+
+ // long coercions
+ assertNullOperand(()-> jexla.toLong(null));
+ Assert.assertEquals(0L, jexlb.toLong(null));
+ assertArithmeticException(()-> jexla.toLong(date));
+ Assert.assertEquals(0L, jexla.toLong(Double.NaN));
+ Assert.assertEquals(0L, jexla.toLong(""));
+ Assert.assertEquals('b', jexla.toLong('b'));
+ Assert.assertEquals(1L, jexla.toLong(new AtomicBoolean(true)));
+ Assert.assertEquals(0L, jexla.toLong(new AtomicBoolean(false)));
+ }
+
+ @Test
+ public void testRealCoercionEdges() {
+ assertNullOperand(()-> jexla.toDouble(null));
+ Assert.assertEquals(0.0d, jexlb.toDouble(null), EPSILON);
+ Assert.assertEquals(32.0d, jexlb.toDouble((char) 32), EPSILON);
+ assertArithmeticException(()-> jexla.toDouble(date));
+ Assert.assertTrue(Double.isNaN(jexla.toDouble("")));
+ Assert.assertEquals("", jexla.toString(Double.NaN));
+
+ assertNullOperand(()-> jexla.toBigInteger(null));
+ assertArithmeticException(()-> jexla.toBigInteger(date));
+ Assert.assertEquals(BigInteger.ZERO, jexla.toBigInteger(Double.NaN));
+ Assert.assertEquals(BigInteger.ZERO, jexla.toBigInteger(""));
+ Assert.assertEquals(BigInteger.ZERO, jexla.toBigInteger((char) 0));
+
+ assertNullOperand(()-> jexla.toBigDecimal(null));
+ assertArithmeticException(()-> jexla.toBigDecimal(date));
+
+ Assert.assertEquals(BigDecimal.ZERO, jexla.toBigDecimal(Double.NaN));
+ Assert.assertEquals(BigDecimal.ZERO, jexla.toBigDecimal(""));
+ Assert.assertEquals(BigDecimal.ZERO, jexla.toBigDecimal((char) 0));
+ }
+
@Test
public void testUndefinedVar() throws Exception {
asserter.failExpression("objects[1].status", ".*variable 'objects' is
undefined.*");
@@ -183,7 +322,7 @@ public class ArithmeticTest extends JexlTestCase {
asserter.assertExpression("-1 + (-9223372036854775808)", new
BigInteger("-9223372036854775809"));
asserter.assertExpression("-9223372036854775808 - 1", new
BigInteger("-9223372036854775809"));
final BigInteger maxl = BigInteger.valueOf(Long.MAX_VALUE);
- asserter.assertExpression(maxl.toString() + " * " + maxl.toString() ,
maxl.multiply(maxl));
+ asserter.assertExpression(maxl + " * " + maxl , maxl.multiply(maxl));
}
/**
@@ -324,7 +463,7 @@ public class ArithmeticTest extends JexlTestCase {
// JEXL-24: long integers (and doubles)
@Test
- public void testLongLiterals() throws Exception {
+ public void testLongLiterals() {
final JexlEvalContext ctxt = new JexlEvalContext();
final JexlOptions options = ctxt.getEngineOptions();
options.setStrictArithmetic(true);
@@ -339,13 +478,13 @@ public class ArithmeticTest extends JexlTestCase {
Assert.assertEquals(56.3f, ctxt.get("f"));
Assert.assertEquals(63.5d, ctxt.get("g"));
Assert.assertEquals(0x10, ctxt.get("h"));
- Assert.assertEquals(010, ctxt.get("i"));
- Assert.assertEquals(0x10L, ctxt.get("j"));
+ Assert.assertEquals(010, ctxt.get("i")); // octal 010
+ Assert.assertEquals(0x10L, ctxt.get("j")); // octal 010L
Assert.assertEquals(010L, ctxt.get("k"));
}
@Test
- public void testBigLiteralValue() throws Exception {
+ public void testBigLiteralValue() {
final JexlEvalContext ctxt = new JexlEvalContext();
final JexlOptions options = ctxt.getEngineOptions();
options.setStrictArithmetic(true);
@@ -355,7 +494,7 @@ public class ArithmeticTest extends JexlTestCase {
}
@Test
- public void testBigdOp() throws Exception {
+ public void testBigdOp() {
final BigDecimal sevendot475 = new BigDecimal("7.475");
final BigDecimal SO = new BigDecimal("325");
final JexlContext jc = new MapContext();
@@ -369,7 +508,7 @@ public class ArithmeticTest extends JexlTestCase {
// JEXL-24: big integers and big decimals
@Test
- public void testBigLiterals() throws Exception {
+ public void testBigLiterals() {
final JexlEvalContext ctxt = new JexlEvalContext();
final JexlOptions options = ctxt.getEngineOptions();
options.setStrictArithmetic(true);
@@ -384,7 +523,7 @@ public class ArithmeticTest extends JexlTestCase {
// JEXL-24: big decimals with exponent
@Test
- public void testBigExponentLiterals() throws Exception {
+ public void testBigExponentLiterals() {
final JexlEvalContext ctxt = new JexlEvalContext();
final JexlOptions options = ctxt.getEngineOptions();
options.setStrictArithmetic(true);
@@ -400,7 +539,7 @@ public class ArithmeticTest extends JexlTestCase {
// JEXL-24: doubles with exponent
@Test
- public void test2DoubleLiterals() throws Exception {
+ public void test2DoubleLiterals() {
final JexlEvalContext ctxt = new JexlEvalContext();
final JexlOptions options = ctxt.getEngineOptions();
options.setStrictArithmetic(true);
@@ -420,11 +559,10 @@ public class ArithmeticTest extends JexlTestCase {
*
* if silent, all arith exception return 0.0
* if not silent, all arith exception throw
- * @throws Exception
*/
@Test
public void testDivideByZero() throws Exception {
- final Map<String, Object> vars = new HashMap<String, Object>();
+ final Map<String, Object> vars = new HashMap<>();
final JexlEvalContext context = new JexlEvalContext(vars);
final JexlOptions options = context.getEngineOptions();
options.setStrictArithmetic(true);
@@ -494,8 +632,8 @@ public class ArithmeticTest extends JexlTestCase {
}
@Test
- public void testNaN() throws Exception {
- final Map<String, Object> ns = new HashMap<String, Object>();
+ public void testNaN() {
+ final Map<String, Object> ns = new HashMap<>();
ns.put("double", Double.class);
final JexlEngine jexl = new JexlBuilder().namespaces(ns).create();
JexlScript script;
@@ -518,7 +656,7 @@ public class ArithmeticTest extends JexlTestCase {
* JEXL-156.
*/
@Test
- public void testMultClass() throws Exception {
+ public void testMultClass(){
final JexlEngine jexl = new JexlBuilder().create();
final JexlContext jc = new MapContext();
final Object ra = jexl.createExpression("463.0d * 0.1").evaluate(jc);
@@ -530,7 +668,7 @@ public class ArithmeticTest extends JexlTestCase {
}
@Test
- public void testDivClass() throws Exception {
+ public void testDivClass() {
final JexlEngine jexl = new JexlBuilder().create();
final JexlContext jc = new MapContext();
final Object ra = jexl.createExpression("463.0d / 0.1").evaluate(jc);
@@ -542,7 +680,7 @@ public class ArithmeticTest extends JexlTestCase {
}
@Test
- public void testPlusClass() throws Exception {
+ public void testPlusClass() {
final JexlEngine jexl = new JexlBuilder().create();
final JexlContext jc = new MapContext();
final Object ra = jexl.createExpression("463.0d + 0.1").evaluate(jc);
@@ -554,7 +692,7 @@ public class ArithmeticTest extends JexlTestCase {
}
@Test
- public void testMinusClass() throws Exception {
+ public void testMinusClass() {
final JexlEngine jexl = new JexlBuilder().create();
final JexlContext jc = new MapContext();
final Object ra = jexl.createExpression("463.0d - 0.1").evaluate(jc);
@@ -566,7 +704,7 @@ public class ArithmeticTest extends JexlTestCase {
}
@Test
- public void testAddWithStringsLenient() throws Exception {
+ public void testAddWithStringsLenient() {
final JexlEngine jexl = new JexlBuilder().arithmetic(new
JexlArithmetic(false)).create();
JexlScript script;
Object result;
@@ -604,7 +742,7 @@ public class ArithmeticTest extends JexlTestCase {
}
@Test
- public void testAddWithStringsStrict() throws Exception {
+ public void testAddWithStringsStrict() {
final JexlEngine jexl = new JexlBuilder().arithmetic(new
JexlArithmetic(true)).create();
JexlScript script;
Object result;
diff --git a/src/test/java/org/apache/commons/jexl3/FeaturesTest.java
b/src/test/java/org/apache/commons/jexl3/FeaturesTest.java
index c2adea5..edaa2b7 100644
--- a/src/test/java/org/apache/commons/jexl3/FeaturesTest.java
+++ b/src/test/java/org/apache/commons/jexl3/FeaturesTest.java
@@ -24,7 +24,7 @@ import org.junit.Test;
* Tests for blocks
* @since 1.1
*/
-@SuppressWarnings({"UnnecessaryBoxing",
"AssertEqualsBetweenInconvertibleTypes"})
+@SuppressWarnings({"AssertEqualsBetweenInconvertibleTypes"})
public class FeaturesTest extends JexlTestCase {
private final JexlEngine jexl = new JexlBuilder().create();
/**
@@ -68,6 +68,7 @@ public class FeaturesTest extends JexlTestCase {
@Test
public void testNoScript() throws Exception {
final JexlFeatures f = new JexlFeatures().script(false);
+ Assert.assertTrue(f.supportsExpression());
final String[] scripts = new String[]{
"if (false) { block(); }",
"{ noway(); }",
diff --git a/src/test/java/org/apache/commons/jexl3/JXLTTest.java
b/src/test/java/org/apache/commons/jexl3/JXLTTest.java
index 67209e4..7ecca69 100644
--- a/src/test/java/org/apache/commons/jexl3/JXLTTest.java
+++ b/src/test/java/org/apache/commons/jexl3/JXLTTest.java
@@ -783,13 +783,32 @@ public class JXLTTest extends JexlTestCase {
@Test
public void testInterpolationParameter() throws Exception {
final String expr = "(user)->{`Hello \n${user}`}";
- Object value = ENGINE.createScript(expr).execute(context, "Henrib");
+ JexlScript script = ENGINE.createScript(expr);
+ Object value = script.execute(context, "Henrib");
Assert.assertEquals(expr, "Hello \nHenrib", value);
value = ENGINE.createScript(expr).execute(context, "Dimitri");
Assert.assertEquals(expr, "Hello \nDimitri", value);
}
@Test
+ public void testDbgEscapes() throws Exception {
+ String[] srcs = new String[]{
+ "jexl:print('hello\\'\\nworld')",
+ "'hello\\tworld'",
+ "'hello\\nworld'",
+ "'hello\\fworld'",
+ "'hello\\rworld'"
+ };
+ for(String src : srcs) {
+ JexlScript script = ENGINE.createScript(src);
+ Debugger dbg = new Debugger();
+ dbg.debug(script);
+ String msrc = dbg.toString();
+ Assert.assertEquals(src, msrc);
+ }
+ }
+
+ @Test
public void testImmediateTemplate() throws Exception {
context.set("tables", new String[]{"table1", "table2"});
context.set("w" ,"x=1");
diff --git
a/src/test/java/org/apache/commons/jexl3/scripting/JexlScriptEngineTest.java
b/src/test/java/org/apache/commons/jexl3/scripting/JexlScriptEngineTest.java
index 51f0e13..99d1368 100644
--- a/src/test/java/org/apache/commons/jexl3/scripting/JexlScriptEngineTest.java
+++ b/src/test/java/org/apache/commons/jexl3/scripting/JexlScriptEngineTest.java
@@ -23,8 +23,12 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import javax.script.CompiledScript;
+import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
+import javax.script.ScriptException;
+
import org.junit.Assert;
import org.junit.Test;
@@ -105,18 +109,32 @@ public class JexlScriptEngineTest {
Assert.assertNotNull("Manager should not be null", manager);
final ScriptEngine engine = manager.getEngineByName("jexl3");
Assert.assertNotNull("Engine should not be null (name)", engine);
+ Assert.assertNotNull(engine.getFactory());
try {
- engine.eval((String)null);
+ engine.eval((String) null);
Assert.fail("Should have caused NPE");
} catch (final NullPointerException e) {
// NOOP
}
try {
- engine.eval((Reader)null);
+ engine.eval((Reader) null);
Assert.fail("Should have caused NPE");
} catch (final NullPointerException e) {
// NOOP
}
+ ScriptContext ctxt = null;
+ try {
+ engine.eval((String) null, ctxt);
+ Assert.fail("Should have caused NPE");
+ } catch (final NullPointerException e) {
+ //NOOP
+ }
+ try {
+ engine.eval((Reader) null, ctxt);
+ Assert.fail("Should have caused NPE");
+ } catch (final NullPointerException e) {
+ //NOOP
+ }
}
@Test
@@ -141,6 +159,90 @@ public class JexlScriptEngineTest {
Assert.assertNull(manager.get("newvar"));
}
+ public static class Errors {
+ public int npe() {
+ throw new NullPointerException("jexl");
+ }
+ public int illegal() {
+ throw new IllegalArgumentException("jexl");
+ }
+ }
+
+ @Test
+ public void testErrors() throws Exception {
+ final ScriptEngineManager manager = new ScriptEngineManager();
+ final JexlScriptEngine engine = (JexlScriptEngine)
manager.getEngineByName("JEXL");
+ ScriptContext ctxt = engine.getContext();
+ engine.put("errors", new Errors());
+ try {
+ engine.eval("errors.npe()");
+ } catch(ScriptException xscript) {
+ Assert.assertTrue(xscript.getCause() instanceof
NullPointerException);
+ }
+ try {
+ engine.eval("errors.illegal()", ctxt);
+ } catch(ScriptException xscript) {
+ Assert.assertTrue(xscript.getCause() instanceof
IllegalArgumentException);
+ }
+ CompiledScript script0 = engine.compile("errors.npe()");
+ try {
+ script0.eval();
+ } catch(ScriptException xscript) {
+ Assert.assertTrue(xscript.getCause() instanceof
NullPointerException);
+ }
+ CompiledScript script1 = engine.compile("errors.illegal()");
+ try {
+ script1.eval(ctxt);
+ } catch(ScriptException xscript) {
+ Assert.assertTrue(xscript.getCause() instanceof
IllegalArgumentException);
+ }
+ }
+
+
+ @Test
+ public void testCompile() throws Exception {
+ final ScriptEngineManager manager = new ScriptEngineManager();
+ final JexlScriptEngine engine = (JexlScriptEngine)
manager.getEngineByName("JEXL");
+ ScriptContext ctxt = engine.getContext();
+ String str = null;
+ String reader = null;
+ try {
+ CompiledScript script0 = engine.compile(str);
+ Assert.fail("should have thrown npe");
+ } catch(NullPointerException npe) {
+ Assert.assertNotNull(npe);
+ }
+ try {
+ CompiledScript script0 = engine.compile(reader);
+ Assert.fail("should have thrown npe");
+ } catch(NullPointerException npe) {
+ Assert.assertNotNull(npe);
+ }
+ try {
+ CompiledScript script0 = engine.compile("3 + 4");
+ Assert.assertEquals(engine, script0.getEngine());
+ Object result = script0.eval();
+ Assert.assertEquals(7, result);
+ result = script0.eval();
+ Assert.assertEquals(7, result);
+ } catch(ScriptException xscript) {
+ Assert.assertTrue(xscript.getCause() instanceof
NullPointerException);
+ }
+ try {
+ ctxt.setAttribute("x", 20, ScriptContext.ENGINE_SCOPE);
+ ctxt.setAttribute("y", 22, ScriptContext.ENGINE_SCOPE);
+ CompiledScript script0 = engine.compile("x + y");
+ Object result = script0.eval();
+ Assert.assertEquals(42, result);
+ ctxt.setAttribute("x", -20, ScriptContext.ENGINE_SCOPE);
+ ctxt.setAttribute("y", -22, ScriptContext.ENGINE_SCOPE);
+ result = script0.eval();
+ Assert.assertEquals(-42, result);
+ } catch(ScriptException xscript) {
+ Assert.assertTrue(xscript.getCause() instanceof
NullPointerException);
+ }
+
+ }
@Test
public void testDottedNames() throws Exception {
final ScriptEngineManager manager = new ScriptEngineManager();