Search in sources :

Example 6 with SpelEvaluationException

use of org.springframework.expression.spel.SpelEvaluationException in project spring-framework by spring-projects.

the class PropertyOrFieldReference method readProperty.

/**
	 * Attempt to read the named property from the current context object.
	 * @return the value of the property
	 * @throws EvaluationException if any problem accessing the property or it cannot be found
	 */
private TypedValue readProperty(TypedValue contextObject, EvaluationContext evalContext, String name) throws EvaluationException {
    Object targetObject = contextObject.getValue();
    if (targetObject == null && this.nullSafe) {
        return TypedValue.NULL;
    }
    PropertyAccessor accessorToUse = this.cachedReadAccessor;
    if (accessorToUse != null) {
        try {
            return accessorToUse.read(evalContext, contextObject.getValue(), name);
        } catch (Exception ex) {
            // This is OK - it may have gone stale due to a class change,
            // let's try to get a new one and call it before giving up...
            this.cachedReadAccessor = null;
        }
    }
    List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObject.getValue(), evalContext.getPropertyAccessors());
    // then ask them to read it
    if (accessorsToTry != null) {
        try {
            for (PropertyAccessor accessor : accessorsToTry) {
                if (accessor.canRead(evalContext, contextObject.getValue(), name)) {
                    if (accessor instanceof ReflectivePropertyAccessor) {
                        accessor = ((ReflectivePropertyAccessor) accessor).createOptimalAccessor(evalContext, contextObject.getValue(), name);
                    }
                    this.cachedReadAccessor = accessor;
                    return accessor.read(evalContext, contextObject.getValue(), name);
                }
            }
        } catch (Exception ex) {
            throw new SpelEvaluationException(ex, SpelMessage.EXCEPTION_DURING_PROPERTY_READ, name, ex.getMessage());
        }
    }
    if (contextObject.getValue() == null) {
        throw new SpelEvaluationException(SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL, name);
    } else {
        throw new SpelEvaluationException(getStartPosition(), SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, name, FormatHelper.formatClassNameForMessage(getObjectClass(contextObject.getValue())));
    }
}
Also used : SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) ReflectivePropertyAccessor(org.springframework.expression.spel.support.ReflectivePropertyAccessor) PropertyAccessor(org.springframework.expression.PropertyAccessor) CompilablePropertyAccessor(org.springframework.expression.spel.CompilablePropertyAccessor) ReflectivePropertyAccessor(org.springframework.expression.spel.support.ReflectivePropertyAccessor) SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) EvaluationException(org.springframework.expression.EvaluationException) AccessException(org.springframework.expression.AccessException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 7 with SpelEvaluationException

use of org.springframework.expression.spel.SpelEvaluationException in project spring-framework by spring-projects.

the class Selection method getValueRef.

@Override
protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
    TypedValue op = state.getActiveContextObject();
    Object operand = op.getValue();
    SpelNodeImpl selectionCriteria = this.children[0];
    if (operand instanceof Map) {
        Map<?, ?> mapdata = (Map<?, ?>) operand;
        // TODO don't lose generic info for the new map
        Map<Object, Object> result = new HashMap<>();
        Object lastKey = null;
        for (Map.Entry<?, ?> entry : mapdata.entrySet()) {
            try {
                TypedValue kvPair = new TypedValue(entry);
                state.pushActiveContextObject(kvPair);
                state.enterScope();
                Object val = selectionCriteria.getValueInternal(state).getValue();
                if (val instanceof Boolean) {
                    if ((Boolean) val) {
                        if (this.variant == FIRST) {
                            result.put(entry.getKey(), entry.getValue());
                            return new ValueRef.TypedValueHolderValueRef(new TypedValue(result), this);
                        }
                        result.put(entry.getKey(), entry.getValue());
                        lastKey = entry.getKey();
                    }
                } else {
                    throw new SpelEvaluationException(selectionCriteria.getStartPosition(), SpelMessage.RESULT_OF_SELECTION_CRITERIA_IS_NOT_BOOLEAN);
                }
            } finally {
                state.popActiveContextObject();
                state.exitScope();
            }
        }
        if ((this.variant == FIRST || this.variant == LAST) && result.isEmpty()) {
            return new ValueRef.TypedValueHolderValueRef(new TypedValue(null), this);
        }
        if (this.variant == LAST) {
            Map<Object, Object> resultMap = new HashMap<>();
            Object lastValue = result.get(lastKey);
            resultMap.put(lastKey, lastValue);
            return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultMap), this);
        }
        return new ValueRef.TypedValueHolderValueRef(new TypedValue(result), this);
    }
    if (operand instanceof Iterable || ObjectUtils.isArray(operand)) {
        Iterable<?> data = (operand instanceof Iterable ? (Iterable<?>) operand : Arrays.asList(ObjectUtils.toObjectArray(operand)));
        List<Object> result = new ArrayList<>();
        int index = 0;
        for (Object element : data) {
            try {
                state.pushActiveContextObject(new TypedValue(element));
                state.enterScope("index", index);
                Object val = selectionCriteria.getValueInternal(state).getValue();
                if (val instanceof Boolean) {
                    if ((Boolean) val) {
                        if (this.variant == FIRST) {
                            return new ValueRef.TypedValueHolderValueRef(new TypedValue(element), this);
                        }
                        result.add(element);
                    }
                } else {
                    throw new SpelEvaluationException(selectionCriteria.getStartPosition(), SpelMessage.RESULT_OF_SELECTION_CRITERIA_IS_NOT_BOOLEAN);
                }
                index++;
            } finally {
                state.exitScope();
                state.popActiveContextObject();
            }
        }
        if ((this.variant == FIRST || this.variant == LAST) && result.isEmpty()) {
            return ValueRef.NullValueRef.INSTANCE;
        }
        if (this.variant == LAST) {
            return new ValueRef.TypedValueHolderValueRef(new TypedValue(result.get(result.size() - 1)), this);
        }
        if (operand instanceof Iterable) {
            return new ValueRef.TypedValueHolderValueRef(new TypedValue(result), this);
        }
        Class<?> elementType = ClassUtils.resolvePrimitiveIfNecessary(op.getTypeDescriptor().getElementTypeDescriptor().getType());
        Object resultArray = Array.newInstance(elementType, result.size());
        System.arraycopy(result.toArray(), 0, resultArray, 0, result.size());
        return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultArray), this);
    }
    if (operand == null) {
        if (this.nullSafe) {
            return ValueRef.NullValueRef.INSTANCE;
        }
        throw new SpelEvaluationException(getStartPosition(), SpelMessage.INVALID_TYPE_FOR_SELECTION, "null");
    }
    throw new SpelEvaluationException(getStartPosition(), SpelMessage.INVALID_TYPE_FOR_SELECTION, operand.getClass().getName());
}
Also used : SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashMap(java.util.HashMap) Map(java.util.Map) TypedValue(org.springframework.expression.TypedValue)

Example 8 with SpelEvaluationException

use of org.springframework.expression.spel.SpelEvaluationException in project spring-framework by spring-projects.

the class Ternary method getValueInternal.

/**
	 * Evaluate the condition and if true evaluate the first alternative, otherwise
	 * evaluate the second alternative.
	 * @param state the expression state
	 * @throws EvaluationException if the condition does not evaluate correctly to
	 * a boolean or there is a problem executing the chosen alternative
	 */
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
    Boolean value = this.children[0].getValue(state, Boolean.class);
    if (value == null) {
        throw new SpelEvaluationException(getChild(0).getStartPosition(), SpelMessage.TYPE_CONVERSION_ERROR, "null", "boolean");
    }
    TypedValue result = this.children[value ? 1 : 2].getValueInternal(state);
    computeExitTypeDescriptor();
    return result;
}
Also used : SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) TypedValue(org.springframework.expression.TypedValue)

Example 9 with SpelEvaluationException

use of org.springframework.expression.spel.SpelEvaluationException in project spring-framework by spring-projects.

the class StandardTypeComparator method compare.

@Override
@SuppressWarnings("unchecked")
public int compare(Object left, Object right) throws SpelEvaluationException {
    // If one is null, check if the other is
    if (left == null) {
        return (right == null ? 0 : -1);
    } else if (right == null) {
        // left cannot be null at this point
        return 1;
    }
    // Basic number comparisons
    if (left instanceof Number && right instanceof Number) {
        Number leftNumber = (Number) left;
        Number rightNumber = (Number) right;
        if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
            BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
            BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
            return leftBigDecimal.compareTo(rightBigDecimal);
        } else if (leftNumber instanceof Double || rightNumber instanceof Double) {
            return Double.compare(leftNumber.doubleValue(), rightNumber.doubleValue());
        } else if (leftNumber instanceof Float || rightNumber instanceof Float) {
            return Float.compare(leftNumber.floatValue(), rightNumber.floatValue());
        } else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) {
            BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
            BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class);
            return leftBigInteger.compareTo(rightBigInteger);
        } else if (leftNumber instanceof Long || rightNumber instanceof Long) {
            // Don't call Long.compare here - only available on JDK 1.7+
            return compare(leftNumber.longValue(), rightNumber.longValue());
        } else if (leftNumber instanceof Integer || rightNumber instanceof Integer) {
            // Don't call Integer.compare here - only available on JDK 1.7+
            return compare(leftNumber.intValue(), rightNumber.intValue());
        } else if (leftNumber instanceof Short || rightNumber instanceof Short) {
            // Don't call Short.compare here - only available on JDK 1.7+
            return compare(leftNumber.shortValue(), rightNumber.shortValue());
        } else if (leftNumber instanceof Byte || rightNumber instanceof Byte) {
            // Don't call Short.compare here - only available on JDK 1.7+
            return compare(leftNumber.byteValue(), rightNumber.byteValue());
        } else {
            // Unknown Number subtypes -> best guess is double multiplication
            return Double.compare(leftNumber.doubleValue(), rightNumber.doubleValue());
        }
    }
    try {
        if (left instanceof Comparable) {
            return ((Comparable<Object>) left).compareTo(right);
        }
    } catch (ClassCastException ex) {
        throw new SpelEvaluationException(ex, SpelMessage.NOT_COMPARABLE, left.getClass(), right.getClass());
    }
    throw new SpelEvaluationException(SpelMessage.NOT_COMPARABLE, left.getClass(), right.getClass());
}
Also used : BigInteger(java.math.BigInteger) SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) BigInteger(java.math.BigInteger) BigDecimal(java.math.BigDecimal)

Example 10 with SpelEvaluationException

use of org.springframework.expression.spel.SpelEvaluationException in project spring-framework by spring-projects.

the class OperatorMatches method getValueInternal.

/**
	 * Check the first operand matches the regex specified as the second operand.
	 * @param state the expression state
	 * @return {@code true} if the first operand matches the regex specified as the
	 * second operand, otherwise {@code false}
	 * @throws EvaluationException if there is a problem evaluating the expression
	 * (e.g. the regex is invalid)
	 */
@Override
public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException {
    SpelNodeImpl leftOp = getLeftOperand();
    SpelNodeImpl rightOp = getRightOperand();
    Object left = leftOp.getValue(state, String.class);
    Object right = getRightOperand().getValueInternal(state).getValue();
    if (!(left instanceof String)) {
        throw new SpelEvaluationException(leftOp.getStartPosition(), SpelMessage.INVALID_FIRST_OPERAND_FOR_MATCHES_OPERATOR, left);
    }
    if (!(right instanceof String)) {
        throw new SpelEvaluationException(rightOp.getStartPosition(), SpelMessage.INVALID_SECOND_OPERAND_FOR_MATCHES_OPERATOR, right);
    }
    try {
        String leftString = (String) left;
        String rightString = (String) right;
        Pattern pattern = this.patternCache.get(rightString);
        if (pattern == null) {
            pattern = Pattern.compile(rightString);
            this.patternCache.putIfAbsent(rightString, pattern);
        }
        Matcher matcher = pattern.matcher(leftString);
        return BooleanTypedValue.forValue(matcher.matches());
    } catch (PatternSyntaxException ex) {
        throw new SpelEvaluationException(rightOp.getStartPosition(), ex, SpelMessage.INVALID_PATTERN, right);
    }
}
Also used : Pattern(java.util.regex.Pattern) SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) Matcher(java.util.regex.Matcher) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

SpelEvaluationException (org.springframework.expression.spel.SpelEvaluationException)30 TypedValue (org.springframework.expression.TypedValue)18 ExpressionState (org.springframework.expression.spel.ExpressionState)8 TypeDescriptor (org.springframework.core.convert.TypeDescriptor)6 AccessException (org.springframework.expression.AccessException)6 ArrayList (java.util.ArrayList)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 Map (java.util.Map)4 EvaluationException (org.springframework.expression.EvaluationException)4 BigDecimal (java.math.BigDecimal)3 BigInteger (java.math.BigInteger)3 TypeConverter (org.springframework.expression.TypeConverter)3 HashMap (java.util.HashMap)2 List (java.util.List)2 MethodParameter (org.springframework.core.MethodParameter)2 ConstructorExecutor (org.springframework.expression.ConstructorExecutor)2 EvaluationContext (org.springframework.expression.EvaluationContext)2 PropertyAccessor (org.springframework.expression.PropertyAccessor)2 CompilablePropertyAccessor (org.springframework.expression.spel.CompilablePropertyAccessor)2 ReflectiveConstructorExecutor (org.springframework.expression.spel.support.ReflectiveConstructorExecutor)2