Search in sources :

Example 1 with EvaluationException

use of org.springframework.expression.EvaluationException 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 2 with EvaluationException

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

the class AbstractExpressionTests method evaluateAndCheckError.

/**
	 * Evaluate the specified expression and ensure the expected message comes out.
	 * The message may have inserts and they will be checked if otherProperties is specified.
	 * The first entry in otherProperties should always be the position.
	 * @param expression the expression to evaluate
	 * @param expectedReturnType ask the expression return value to be of this type if possible
	 * ({@code null} indicates don't ask for conversion)
	 * @param expectedMessage the expected message
	 * @param otherProperties the expected inserts within the message
	 */
protected void evaluateAndCheckError(String expression, Class<?> expectedReturnType, SpelMessage expectedMessage, Object... otherProperties) {
    try {
        Expression expr = parser.parseExpression(expression);
        if (expr == null) {
            fail("Parser returned null for expression");
        }
        if (expectedReturnType != null) {
            expr.getValue(eContext, expectedReturnType);
        } else {
            expr.getValue(eContext);
        }
        fail("Should have failed with message " + expectedMessage);
    } catch (EvaluationException ee) {
        SpelEvaluationException ex = (SpelEvaluationException) ee;
        if (ex.getMessageCode() != expectedMessage) {
            assertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode());
        }
        if (otherProperties != null && otherProperties.length != 0) {
            // first one is expected position of the error within the string
            int pos = ((Integer) otherProperties[0]).intValue();
            assertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
            if (otherProperties.length > 1) {
                // Check inserts match
                Object[] inserts = ex.getInserts();
                if (inserts == null) {
                    inserts = new Object[0];
                }
                if (inserts.length < otherProperties.length - 1) {
                    fail("Cannot check " + (otherProperties.length - 1) + " properties of the exception, it only has " + inserts.length + " inserts");
                }
                for (int i = 1; i < otherProperties.length; i++) {
                    if (otherProperties[i] == null) {
                        if (inserts[i - 1] != null) {
                            fail("Insert does not match, expected 'null' but insert value was '" + inserts[i - 1] + "'");
                        }
                    } else if (inserts[i - 1] == null) {
                        if (otherProperties[i] != null) {
                            fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was 'null'");
                        }
                    } else if (!inserts[i - 1].equals(otherProperties[i])) {
                        fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was '" + inserts[i - 1] + "'");
                    }
                }
            }
        }
    }
}
Also used : Expression(org.springframework.expression.Expression) EvaluationException(org.springframework.expression.EvaluationException)

Example 3 with EvaluationException

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

the class PropertyOrFieldReference method writeProperty.

private void writeProperty(TypedValue contextObject, EvaluationContext evalContext, String name, Object newValue) throws EvaluationException {
    if (contextObject.getValue() == null && this.nullSafe) {
        return;
    }
    PropertyAccessor accessorToUse = this.cachedWriteAccessor;
    if (accessorToUse != null) {
        try {
            accessorToUse.write(evalContext, contextObject.getValue(), name, newValue);
            return;
        } 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.cachedWriteAccessor = null;
        }
    }
    List<PropertyAccessor> accessorsToTry = getPropertyAccessorsToTry(contextObject.getValue(), evalContext.getPropertyAccessors());
    if (accessorsToTry != null) {
        try {
            for (PropertyAccessor accessor : accessorsToTry) {
                if (accessor.canWrite(evalContext, contextObject.getValue(), name)) {
                    this.cachedWriteAccessor = accessor;
                    accessor.write(evalContext, contextObject.getValue(), name, newValue);
                    return;
                }
            }
        } catch (AccessException ex) {
            throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.EXCEPTION_DURING_PROPERTY_WRITE, name, ex.getMessage());
        }
    }
    if (contextObject.getValue() == null) {
        throw new SpelEvaluationException(getStartPosition(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, name);
    } else {
        throw new SpelEvaluationException(getStartPosition(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE, 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) AccessException(org.springframework.expression.AccessException) SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) EvaluationException(org.springframework.expression.EvaluationException) AccessException(org.springframework.expression.AccessException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 4 with EvaluationException

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

the class PropertyAccessTests method testAddingSpecificPropertyAccessor.

@Test
public // Adding a new property accessor just for a particular type
void testAddingSpecificPropertyAccessor() throws Exception {
    SpelExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    // Even though this property accessor is added after the reflection one, it specifically
    // names the String class as the type it is interested in so is chosen in preference to
    // any 'default' ones
    ctx.addPropertyAccessor(new StringyPropertyAccessor());
    Expression expr = parser.parseRaw("new String('hello').flibbles");
    Integer i = expr.getValue(ctx, Integer.class);
    assertEquals((int) i, 7);
    // The reflection one will be used for other properties...
    expr = parser.parseRaw("new String('hello').CASE_INSENSITIVE_ORDER");
    Object o = expr.getValue(ctx);
    assertNotNull(o);
    expr = parser.parseRaw("new String('hello').flibbles");
    expr.setValue(ctx, 99);
    i = expr.getValue(ctx, Integer.class);
    assertEquals((int) i, 99);
    // Cannot set it to a string value
    try {
        expr.setValue(ctx, "not allowed");
        fail("Should not have been allowed");
    } catch (EvaluationException ex) {
    // success - message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
    // 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''
    // System.out.println(e.getMessage());
    }
}
Also used : SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) SpelExpression(org.springframework.expression.spel.standard.SpelExpression) Expression(org.springframework.expression.Expression) EvaluationException(org.springframework.expression.EvaluationException) Test(org.junit.Test)

Example 5 with EvaluationException

use of org.springframework.expression.EvaluationException in project scheduling by ow2-proactive.

the class SpelValidator method validate.

@Override
public String validate(String parameterValue, ModelValidatorContext context) throws ValidationException {
    try {
        context.getSpELContext().setVariable("value", parameterValue);
        Object untypedResult = spelExpression.getValue(context.getSpELContext());
        if (!(untypedResult instanceof Boolean)) {
            throw new ValidationException("SPEL expression did not return a boolean value.");
        }
        boolean evaluationResult = (Boolean) untypedResult;
        if (!evaluationResult) {
            throw new ValidationException("SPEL expression returned false, received " + parameterValue);
        }
    } catch (EvaluationException e) {
        throw new ValidationException("SPEL expression raised an error: " + e.getMessage(), e);
    }
    return parameterValue;
}
Also used : ValidationException(org.ow2.proactive.scheduler.common.job.factories.spi.model.exceptions.ValidationException) EvaluationException(org.springframework.expression.EvaluationException)

Aggregations

EvaluationException (org.springframework.expression.EvaluationException)24 Expression (org.springframework.expression.Expression)14 SpelExpressionParser (org.springframework.expression.spel.standard.SpelExpressionParser)9 Test (org.junit.jupiter.api.Test)8 ArrayList (java.util.ArrayList)5 AccessException (org.springframework.expression.AccessException)5 StandardEvaluationContext (org.springframework.expression.spel.support.StandardEvaluationContext)5 TypeDescriptor (org.springframework.core.convert.TypeDescriptor)4 ParseException (org.springframework.expression.ParseException)4 SpelEvaluationException (org.springframework.expression.spel.SpelEvaluationException)4 Test (org.junit.Test)3 MethodParameter (org.springframework.core.MethodParameter)3 TypeConverter (org.springframework.expression.TypeConverter)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 ValidationException (org.ow2.proactive.scheduler.common.job.factories.spi.model.exceptions.ValidationException)2 PropertyAccessor (org.springframework.expression.PropertyAccessor)2 CompilablePropertyAccessor (org.springframework.expression.spel.CompilablePropertyAccessor)2 SpelExpression (org.springframework.expression.spel.standard.SpelExpression)2 ReflectivePropertyAccessor (org.springframework.expression.spel.support.ReflectivePropertyAccessor)2