Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* 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.
*/
package org.apache.commons.jexl3;
import static java.lang.StrictMath.floor;
import static org.apache.commons.jexl3.JexlOperator.EQ;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.jexl3.introspection.JexlMethod;
/**
* Perform arithmetic, implements JexlOperator methods.
*
*
This is the class to derive to implement new operator behaviors.
*
*
The 5 base arithmetic operators (+, - , *, /, %) follow the same evaluation rules regarding their arguments.
*
*
If both are null, result is 0 if arithmetic (or operator) is non-strict, ArithmeticException is thrown
* otherwise
*
If both arguments are numberable - any kind of integer including boolean -, coerce both to Long and coerce
* result to the most precise argument class ({@code boolean < byte < short < int < long});
* if long operation would cause overflow, return a BigInteger
*
If either argument is a BigDecimal, coerce both to BigDecimal, operator returns BigDecimal
*
If either argument is a floating point number, coerce both to Double, operator returns Double
*
Else treat as BigInteger, perform operation and narrow result to the most precise argument class
*
*
*
* Note that the only exception thrown by JexlArithmetic is and must be ArithmeticException.
*
* @see JexlOperator
* @since 2.0
*/
public class JexlArithmetic {
/**
* Helper interface used when creating an array literal.
*
*
The default implementation creates an array and attempts to type it strictly.
*
*
*
If all objects are of the same type, the array returned will be an array of that same type
*
If all objects are Numbers, the array returned will be an array of Numbers
*
If all objects are convertible to a primitive type, the array returned will be an array
* of the primitive type
*
*/
public interface ArrayBuilder {
/**
* Adds a literal to the array.
*
* @param value the item to add
*/
void add(Object value);
/**
* Creates the actual "array" instance.
*
* @param extended true when the last argument is ', ...'
* @return the array
*/
Object create(boolean extended);
}
/** Marker class for coercion operand exceptions. */
public static class CoercionException extends ArithmeticException {
private static final long serialVersionUID = 202402081150L;
/**
* Constructs a new instance.
*
* @param msg the detail message.
*/
public CoercionException(final String msg) {
super(msg);
}
/**
* Constructs a new instance.
*
* @param msg the detail message.
* @param cause The cause of this Throwable.
* @since 3.5.0
*/
public CoercionException(final String msg, final Throwable cause) {
super(msg);
initCause(cause);
}
}
/**
* Helper interface used when creating a map literal.
*
The default implementation creates a java.util.HashMap.
*/
public interface MapBuilder {
/**
* Creates the actual "map" instance.
*
* @return the map
*/
Object create();
/**
* Adds a new entry to the map.
*
* @param key the map entry key
* @param value the map entry value
*/
void put(Object key, Object value);
}
/** Marker class for null operand exceptions. */
public static class NullOperand extends ArithmeticException {
private static final long serialVersionUID = 4720876194840764770L;
/** Default constructor */
public NullOperand() {
} // satisfy Javadoc
}
/**
* Helper interface used when creating a set literal.
*
The default implementation creates a java.util.HashSet.
*/
public interface SetBuilder {
/**
* Adds a literal to the set.
*
* @param value the item to add
*/
void add(Object value);
/**
* Creates the actual "set" instance.
*
* @return the set
*/
Object create();
}
/**
* The interface that uberspects JexlArithmetic classes.
*
This allows overloaded operator methods discovery.
*/
public interface Uberspect {
/**
* Gets the most specific method for an operator.
*
* @param operator the operator
* @param args the arguments
* @return the most specific method or null if no specific override could be found
*/
JexlMethod getOperator(JexlOperator operator, Object... args);
/**
* Checks whether this uberspect has overloads for a given operator.
*
* @param operator the operator to check
* @return true if an overload exists, false otherwise
*/
boolean overloads(JexlOperator operator);
}
/** Double.MAX_VALUE as BigDecimal. */
protected static final BigDecimal BIGD_DOUBLE_MAX_VALUE = BigDecimal.valueOf(Double.MAX_VALUE);
/** -Double.MAX_VALUE as BigDecimal. */
protected static final BigDecimal BIGD_DOUBLE_MIN_VALUE = BigDecimal.valueOf(-Double.MAX_VALUE);
/** Long.MAX_VALUE as BigInteger. */
protected static final BigInteger BIGI_LONG_MAX_VALUE = BigInteger.valueOf(Long.MAX_VALUE);
/** Long.MIN_VALUE as BigInteger. */
protected static final BigInteger BIGI_LONG_MIN_VALUE = BigInteger.valueOf(Long.MIN_VALUE);
/** Default BigDecimal scale. */
protected static final int BIGD_SCALE = -1;
/**
* The float regular expression pattern.
*
* The decimal and exponent parts are optional and captured allowing to determine if the number is a real
* by checking whether one of these 2 capturing groups is not empty.
*/
public static final Pattern FLOAT_PATTERN = Pattern.compile("^[+-]?\\d*(\\.\\d*)?([eE][+-]?\\d+)?$");
/**
* Attempts transformation of potential array in an abstract list or leave as is.
*
An array (as in int[]) is not convenient to call methods so when encountered we turn them into lists
* @param container an array or on object
* @return an abstract list wrapping the array instance or the initial argument
* @see org.apache.commons.jexl3.internal.introspection.ArrayListWrapper
*/
private static Object arrayWrap(final Object container) {
return container.getClass().isArray()
? new org.apache.commons.jexl3.internal.introspection.ArrayListWrapper(container)
: container;
}
private static boolean computeCompare321(final JexlArithmetic arithmetic) {
Class> arithmeticClass = arithmetic.getClass();
while(arithmeticClass != JexlArithmetic.class) {
try {
final Method cmp = arithmeticClass.getDeclaredMethod("compare", Object.class, Object.class, String.class);
if (cmp.getDeclaringClass() != JexlArithmetic.class) {
return true;
}
} catch (final NoSuchMethodException xany) {
arithmeticClass = arithmeticClass.getSuperclass();
}
}
return false;
}
/**
* Checks if the product of the arguments overflows a {@code long}.
*
see java8 Math.multiplyExact
* @param x the first value
* @param y the second value
* @param r the product
* @return true if product fits a long, false if it overflows
*/
@SuppressWarnings("MagicNumber")
protected static boolean isMultiplyExact(final long x, final long y, final long r) {
final long ax = Math.abs(x);
final long ay = Math.abs(y);
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
return !((ax | ay) >>> Integer.SIZE - 1 != 0
&& (y != 0 && r / y != x
|| x == Long.MIN_VALUE && y == -1));
}
/** Whether this JexlArithmetic instance behaves in strict or lenient mode. */
private final boolean strict;
/** The big decimal math context. */
private final MathContext mathContext;
/** The big decimal scale. */
private final int mathScale;
/** The dynamic constructor. */
private final Constructor extends JexlArithmetic> ctor;
/**
* Determines if the compare method(Object, Object, String) is overriden in this class or one of its
* superclasses.
*/
private final boolean compare321 = computeCompare321(this);
/**
* Creates a JexlArithmetic.
*
If you derive your own arithmetic, implement the
* other constructor that may be needed when dealing with options.
*
* @param astrict whether this arithmetic is strict or lenient
*/
public JexlArithmetic(final boolean astrict) {
this(astrict, null, Integer.MIN_VALUE);
}
/**
* Creates a JexlArithmetic.
*
The constructor to define in derived classes.
*
* @param astrict whether this arithmetic is lenient or strict
* @param bigdContext the math context instance to use for +,-,/,*,% operations on big decimals.
* @param bigdScale the scale used for big decimals.
*/
public JexlArithmetic(final boolean astrict, final MathContext bigdContext, final int bigdScale) {
this.strict = astrict;
this.mathContext = bigdContext == null ? MathContext.DECIMAL128 : bigdContext;
this.mathScale = bigdScale == Integer.MIN_VALUE ? BIGD_SCALE : bigdScale;
Constructor extends JexlArithmetic> actor = null;
try {
actor = getClass().getConstructor(boolean.class, MathContext.class, int.class);
} catch (final Exception xany) {
// ignore
}
this.ctor = actor;
}
/**
* Add two values together.
*
* If any numeric add fails on coercion to the appropriate type,
* treat as Strings and do concatenation.
*
*
* @param left left argument
* @param right right argument
* @return left + right.
*/
public Object add(final Object left, final Object right) {
if (left == null && right == null) {
return controlNullNullOperands(JexlOperator.ADD);
}
final boolean strconcat = strict
? left instanceof String || right instanceof String
: left instanceof String && right instanceof String;
if (!strconcat) {
try {
final boolean strictCast = isStrict(JexlOperator.ADD);
// if both (non-null) args fit as long
final Number ln = asLongNumber(strictCast, left);
final Number rn = asLongNumber(strictCast, right);
if (ln != null && rn != null) {
final long x = ln.longValue();
final long y = rn.longValue();
final long result = x + y;
// detect overflow, see java8 Math.addExact
if (((x ^ result) & (y ^ result)) < 0) {
return BigInteger.valueOf(x).add(BigInteger.valueOf(y));
}
return narrowLong(left, right, result);
}
// if either are BigDecimal, use that type
if (left instanceof BigDecimal || right instanceof BigDecimal) {
final BigDecimal l = toBigDecimal(strictCast, left);
final BigDecimal r = toBigDecimal(strictCast, right);
return l.add(r, getMathContext());
}
// if either are floating point (double or float), use double
if (isFloatingPointNumber(left) || isFloatingPointNumber(right)) {
final double l = toDouble(strictCast, left);
final double r = toDouble(strictCast, right);
return l + r;
}
// otherwise treat as BigInteger
final BigInteger l = toBigInteger(strictCast, left);
final BigInteger r = toBigInteger(strictCast, right);
final BigInteger result = l.add(r);
return narrowBigInteger(left, right, result);
} catch (final ArithmeticException nfe) {
// ignore and continue in sequence
}
}
return (left == null ? "" : toString(left)).concat(right == null ? "" : toString(right));
}
/**
* Performs a bitwise and.
*
* @param left the left operand
* @param right the right operator
* @return left & right
*/
public Object and(final Object left, final Object right) {
final long l = toLong(left);
final long r = toLong(right);
return l & r;
}
/**
* Creates an array builder.
* @param size the number of elements in the array
* @return an array builder instance
* @deprecated since 3.3.1
*/
@Deprecated
public ArrayBuilder arrayBuilder(final int size) {
return arrayBuilder(size, false);
}
/**
* Called by the interpreter when evaluating a literal array.
*
* @param size the number of elements in the array
* @param extended whether the map is extended or not
* @return the array builder
*/
public ArrayBuilder arrayBuilder(final int size, final boolean extended) {
return new org.apache.commons.jexl3.internal.ArrayBuilder(size, extended);
}
/**
* Checks if value class is a number that can be represented exactly in a long.
*
For convenience, booleans are converted as 1/0 (true/false).
*
* @param strict whether null argument is converted as 0 or remains null
* @param value argument
* @return a non-null value if argument can be represented by a long
*/
protected Number asLongNumber(final boolean strict, final Object value) {
if (value instanceof Long
|| value instanceof Integer
|| value instanceof Short
|| value instanceof Byte) {
return (Number) value;
}
if (value instanceof Boolean) {
return (boolean) value ? 1L : 0L;
}
if (value instanceof AtomicBoolean) {
final AtomicBoolean b = (AtomicBoolean) value;
return b.get() ? 1L : 0L;
}
if (value == null && !strict) {
return 0L;
}
return null;
}
/**
* Checks if value class is a number that can be represented exactly in a long.
*
For convenience, booleans are converted as 1/0 (true/false).
*
* @param value argument
* @return a non-null value if argument can be represented by a long
*/
protected Number asLongNumber(final Object value) {
return asLongNumber(strict, value);
}
/**
* Use or overload and() instead.
* @param lhs left hand side
* @param rhs right hand side
* @return lhs & rhs
* @see JexlArithmetic#and
* @deprecated 3.0
*/
@Deprecated
public final Object bitwiseAnd(final Object lhs, final Object rhs) {
return and(lhs, rhs);
}
/**
* Use or overload or() instead.
*
* @param lhs left hand side
* @param rhs right hand side
* @return lhs | rhs
* @see JexlArithmetic#or
* @deprecated 3.0
*/
@Deprecated
public final Object bitwiseOr(final Object lhs, final Object rhs) {
return or(lhs, rhs);
}
/**
* Use or overload xor() instead.
*
* @param lhs left hand side
* @param rhs right hand side
* @return lhs ^ rhs
* @see JexlArithmetic#xor
* @deprecated 3.0
*/
@Deprecated
public final Object bitwiseXor(final Object lhs, final Object rhs) {
return xor(lhs, rhs);
}
/**
* Checks whether a potential collection contains another.
*
Made protected to make it easier to override if needed.
* @param collection the container which can be a collection or an array (even of primitive)
* @param value the value which can be a collection or an array (even of primitive) or a singleton
* @return test result or null if there is no arithmetic solution
*/
protected Boolean collectionContains(final Object collection, final Object value) {
// convert arrays if needed
final Object left = arrayWrap(collection);
if (left instanceof Collection) {
final Object right = arrayWrap(value);
if (right instanceof Collection) {
return ((Collection>) left).containsAll((Collection>) right);
}
return ((Collection>) left).contains(value);
}
return null;
}
/**
* Performs a comparison.
*
* @param left the left operand
* @param right the right operator
* @param operator the operator
* @return -1 if left < right; +1 if left > right; 0 if left == right
* @throws ArithmeticException if either left or right is null
*/
protected int compare(final Object left, final Object right, final JexlOperator operator) {
// this is a temporary way of allowing pre-3.3 code that overrode compare() to still call
// the user method. This method will merge with doCompare in 3.4 and the compare321 flag will disappear.
return compare321
? compare(left, right, operator.toString())
: doCompare(left, right, operator);
}
/**
* Any override of this method (pre 3.3) should be modified to match the new signature.
* @param left left operand
* @param right right operand
* @param symbol the operator symbol
* @return -1 if left < right; +1 if left > right; 0 if left == right
* {@link JexlArithmetic#compare(Object, Object, JexlOperator)}
* @deprecated 3.3
*/
@Deprecated
protected int compare(final Object left, final Object right, final String symbol) {
JexlOperator operator;
try {
operator = JexlOperator.valueOf(symbol);
} catch (final IllegalArgumentException xill) {
// ignore
operator = EQ;
}
return doCompare(left, right, operator);
}
/**
* Performs a bitwise complement.
*
* @param val the operand
* @return ~val
*/
public Object complement(final Object val) {
final boolean strictCast = isStrict(JexlOperator.COMPLEMENT);
final long l = toLong(strictCast, val);
return ~l;
}
/**
* Test if left contains right (right matches/in left).
*
Beware that this "contains " method arguments order is the opposite of the
* "in/matches" operator arguments.
* {@code x =~ y} means {@code y contains x} thus {@code contains(x, y)}.
*
When this method returns null during evaluation, the operator code continues trying to find
* one through the uberspect.
* @param container the container
* @param value the value
* @return test result or null if there is no arithmetic solution
*/
public Boolean contains(final Object container, final Object value) {
if (value == null && container == null) {
//if both are null L == R
return true;
}
if (value == null || container == null) {
// we know both aren't null, therefore L != R
return false;
}
// use arithmetic / pattern matching ?
if (container instanceof java.util.regex.Pattern) {
return ((java.util.regex.Pattern) container).matcher(value.toString()).matches();
}
if (container instanceof CharSequence) {
return value.toString().matches(container.toString());
}
// try contains on map key
if (container instanceof Map, ?>) {
if (value instanceof Map, ?>) {
return ((Map, ?>) container).keySet().containsAll(((Map, ?>) value).keySet());
}
return ((Map, ?>) container).containsKey(value);
}
// try contains on collection
return collectionContains(container, value);
}
/**
* The result of +,/,-,*,% when both operands are null.
*
* @return Integer(0) if lenient
* @throws JexlArithmetic.NullOperand if strict
* @deprecated 3.3
*/
@Deprecated
protected Object controlNullNullOperands() {
if (isStrict()) {
throw new NullOperand();
}
return 0;
}
/**
* The result of +,/,-,*,% when both operands are null.
* @param operator the actual operator
* @return Integer(0) if lenient
* @throws JexlArithmetic.NullOperand if strict-cast
* @since 3.3
*/
protected Object controlNullNullOperands(final JexlOperator operator) {
if (isStrict(operator)) {
throw new NullOperand();
}
return 0;
}
/**
* Throws an NullOperand exception if arithmetic is strict-cast.
*
* @throws JexlArithmetic.NullOperand if strict
* @deprecated 3.3
*/
@Deprecated
protected void controlNullOperand() {
if (isStrict()) {
throw new NullOperand();
}
}
/**
* Throws an NullOperand exception if arithmetic is strict-cast.
*
This method is called by the cast methods ({@link #toBoolean(boolean, Object)},
* {@link #toInteger(boolean, Object)}, {@link #toDouble(boolean, Object)},
* {@link #toString(boolean, Object)}, {@link #toBigInteger(boolean, Object)},
* {@link #toBigDecimal(boolean, Object)}) when they encounter a null argument.
*
* @param strictCast whether strict cast is required
* @param defaultValue the default value to return, if not strict
* @param the value type
* @return the default value is strict is false
* @throws JexlArithmetic.NullOperand if strict-cast
* @since 3.3
*/
protected T controlNullOperand(final boolean strictCast, final T defaultValue) {
if (strictCast) {
throw new NullOperand();
}
return defaultValue;
}
/**
* The last method called before returning a result from a script execution.
* @param returned the returned value
* @return the controlled returned value
*/
public Object controlReturn(final Object returned) {
return returned;
}
/**
* Creates a literal range.
*
The default implementation only accepts integers and longs.
*
* @param from the included lower bound value (null if none)
* @param to the included upper bound value (null if none)
* @return the range as an iterable
* @throws ArithmeticException as an option if creation fails
*/
public Iterable> createRange(final Object from, final Object to) throws ArithmeticException {
final long lfrom = toLong(from);
final long lto = toLong(to);
if (lfrom >= Integer.MIN_VALUE && lfrom <= Integer.MAX_VALUE
&& lto >= Integer.MIN_VALUE && lto <= Integer.MAX_VALUE) {
return org.apache.commons.jexl3.internal.IntegerRange.create((int) lfrom, (int) lto);
}
return org.apache.commons.jexl3.internal.LongRange.create(lfrom, lto);
}
/**
* Creates a JexlArithmetic instance.
* Called by options(...) method when another instance of the same class of arithmetic is required.
* @see #options(org.apache.commons.jexl3.JexlEngine.Options)
* @param astrict whether this arithmetic is lenient or strict
* @param bigdContext the math context instance to use for +,-,/,*,% operations on big decimals.
* @param bigdScale the scale used for big decimals.
* @return default is a new JexlArithmetic instance
* @since 3.1
*/
protected JexlArithmetic createWithOptions(final boolean astrict, final MathContext bigdContext, final int bigdScale) {
if (ctor != null) {
try {
return ctor.newInstance(astrict, bigdContext, bigdScale);
} catch (IllegalAccessException | IllegalArgumentException
| InstantiationException | InvocationTargetException xany) {
// it was worth the try
}
}
return new JexlArithmetic(astrict, bigdContext, bigdScale);
}
/**
* Decrements argument by 1.
* @param val the argument
* @return val - 1
*/
public Object decrement(final Object val) {
return increment(val, -1);
}
/**
* Divide the left value by the right.
*
* @param left left argument
* @param right right argument
* @return left / right
* @throws ArithmeticException if right == 0
*/
public Object divide(final Object left, final Object right) {
if (left == null && right == null) {
return controlNullNullOperands(JexlOperator.DIVIDE);
}
final boolean strictCast = isStrict(JexlOperator.DIVIDE);
// if both (non-null) args fit as long
final Number ln = asLongNumber(strictCast, left);
final Number rn = asLongNumber(strictCast, right);
if (ln != null && rn != null) {
final long x = ln.longValue();
final long y = rn.longValue();
if (y == 0L) {
throw new ArithmeticException("/");
}
final long result = x / y;
return narrowLong(left, right, result);
}
// if either are BigDecimal, use that type
if (left instanceof BigDecimal || right instanceof BigDecimal) {
final BigDecimal l = toBigDecimal(strictCast, left);
final BigDecimal r = toBigDecimal(strictCast, right);
if (BigDecimal.ZERO.equals(r)) {
throw new ArithmeticException("/");
}
return l.divide(r, getMathContext());
}
// if either are floating point (double or float), use double
if (isFloatingPointNumber(left) || isFloatingPointNumber(right)) {
final double l = toDouble(strictCast, left);
final double r = toDouble(strictCast, right);
if (r == 0.0) {
throw new ArithmeticException("/");
}
return l / r;
}
// otherwise treat as BigInteger
final BigInteger l = toBigInteger(strictCast, left);
final BigInteger r = toBigInteger(strictCast, right);
if (BigInteger.ZERO.equals(r)) {
throw new ArithmeticException("/");
}
final BigInteger result = l.divide(r);
return narrowBigInteger(left, right, result);
}
private int doCompare(final Object left, final Object right, final JexlOperator operator) {
final boolean strictCast = isStrict(operator);
if (left != null && right != null) {
try {
if (left instanceof BigDecimal || right instanceof BigDecimal) {
final BigDecimal l = toBigDecimal(strictCast, left);
final BigDecimal r = toBigDecimal(strictCast, right);
return l.compareTo(r);
}
if (left instanceof BigInteger || right instanceof BigInteger) {
final BigInteger l = toBigInteger(strictCast, left);
final BigInteger r = toBigInteger(strictCast, right);
return l.compareTo(r);
}
if (isFloatingPoint(left) || isFloatingPoint(right)) {
final double lhs = toDouble(strictCast, left);
final double rhs = toDouble(strictCast, right);
if (Double.isNaN(lhs)) {
if (Double.isNaN(rhs)) {
return 0;
}
return -1;
}
if (Double.isNaN(rhs)) {
// lhs is not NaN
return +1;
}
return Double.compare(lhs, rhs);
}
if (isNumberable(left) || isNumberable(right)) {
final long lhs = toLong(strictCast, left);
final long rhs = toLong(strictCast, right);
return Long.compare(lhs, rhs);
}
if (left instanceof String || right instanceof String) {
return toString(left).compareTo(toString(right));
}
} catch (final CoercionException ignore) {
// ignore it, continue in sequence
}
if (EQ == operator) {
return left.equals(right) ? 0 : -1;
}
if (left instanceof Comparable>) {
@SuppressWarnings("unchecked") // OK because of instanceof check above
final Comparable