Search in sources :

Example 6 with EvaluationException

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

the class ReflectiveMethodResolver method resolve.

/**
	 * Locate a method on a type. There are three kinds of match that might occur:
	 * <ol>
	 * <li>an exact match where the types of the arguments match the types of the constructor
	 * <li>an in-exact match where the types we are looking for are subtypes of those defined on the constructor
	 * <li>a match where we are able to convert the arguments into those expected by the constructor,
	 * according to the registered type converter
	 * </ol>
	 */
@Override
public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name, List<TypeDescriptor> argumentTypes) throws AccessException {
    try {
        TypeConverter typeConverter = context.getTypeConverter();
        Class<?> type = (targetObject instanceof Class ? (Class<?>) targetObject : targetObject.getClass());
        List<Method> methods = new ArrayList<>(getMethods(type, targetObject));
        // If a filter is registered for this type, call it
        MethodFilter filter = (this.filters != null ? this.filters.get(type) : null);
        if (filter != null) {
            List<Method> filtered = filter.filter(methods);
            methods = (filtered instanceof ArrayList ? filtered : new ArrayList<>(filtered));
        }
        // Sort methods into a sensible order
        if (methods.size() > 1) {
            Collections.sort(methods, new Comparator<Method>() {

                @Override
                public int compare(Method m1, Method m2) {
                    int m1pl = m1.getParameterCount();
                    int m2pl = m2.getParameterCount();
                    // varargs methods go last
                    if (m1pl == m2pl) {
                        if (!m1.isVarArgs() && m2.isVarArgs()) {
                            return -1;
                        } else if (m1.isVarArgs() && !m2.isVarArgs()) {
                            return 1;
                        } else {
                            return 0;
                        }
                    }
                    return (m1pl < m2pl ? -1 : (m1pl > m2pl ? 1 : 0));
                }
            });
        }
        // Resolve any bridge methods
        for (int i = 0; i < methods.size(); i++) {
            methods.set(i, BridgeMethodResolver.findBridgedMethod(methods.get(i)));
        }
        // Remove duplicate methods (possible due to resolved bridge methods)
        Set<Method> methodsToIterate = new LinkedHashSet<>(methods);
        Method closeMatch = null;
        int closeMatchDistance = Integer.MAX_VALUE;
        Method matchRequiringConversion = null;
        boolean multipleOptions = false;
        for (Method method : methodsToIterate) {
            if (method.getName().equals(name)) {
                Class<?>[] paramTypes = method.getParameterTypes();
                List<TypeDescriptor> paramDescriptors = new ArrayList<>(paramTypes.length);
                for (int i = 0; i < paramTypes.length; i++) {
                    paramDescriptors.add(new TypeDescriptor(new MethodParameter(method, i)));
                }
                ReflectionHelper.ArgumentsMatchInfo matchInfo = null;
                if (method.isVarArgs() && argumentTypes.size() >= (paramTypes.length - 1)) {
                    // *sigh* complicated
                    matchInfo = ReflectionHelper.compareArgumentsVarargs(paramDescriptors, argumentTypes, typeConverter);
                } else if (paramTypes.length == argumentTypes.size()) {
                    // Name and parameter number match, check the arguments
                    matchInfo = ReflectionHelper.compareArguments(paramDescriptors, argumentTypes, typeConverter);
                }
                if (matchInfo != null) {
                    if (matchInfo.isExactMatch()) {
                        return new ReflectiveMethodExecutor(method);
                    } else if (matchInfo.isCloseMatch()) {
                        if (this.useDistance) {
                            int matchDistance = ReflectionHelper.getTypeDifferenceWeight(paramDescriptors, argumentTypes);
                            if (closeMatch == null || matchDistance < closeMatchDistance) {
                                // This is a better match...
                                closeMatch = method;
                                closeMatchDistance = matchDistance;
                            }
                        } else {
                            // Take this as a close match if there isn't one already
                            if (closeMatch == null) {
                                closeMatch = method;
                            }
                        }
                    } else if (matchInfo.isMatchRequiringConversion()) {
                        if (matchRequiringConversion != null) {
                            multipleOptions = true;
                        }
                        matchRequiringConversion = method;
                    }
                }
            }
        }
        if (closeMatch != null) {
            return new ReflectiveMethodExecutor(closeMatch);
        } else if (matchRequiringConversion != null) {
            if (multipleOptions) {
                throw new SpelEvaluationException(SpelMessage.MULTIPLE_POSSIBLE_METHODS, name);
            }
            return new ReflectiveMethodExecutor(matchRequiringConversion);
        } else {
            return null;
        }
    } catch (EvaluationException ex) {
        throw new AccessException("Failed to resolve method", ex);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) MethodFilter(org.springframework.expression.MethodFilter) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) EvaluationException(org.springframework.expression.EvaluationException) TypeConverter(org.springframework.expression.TypeConverter) AccessException(org.springframework.expression.AccessException) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) MethodParameter(org.springframework.core.MethodParameter)

Example 7 with EvaluationException

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

the class ExpressionLanguageScenarioTests method testScenario_UsingStandardInfrastructure.

/**
	 * Scenario: using the standard infrastructure and running simple expression evaluation.
	 */
@Test
public void testScenario_UsingStandardInfrastructure() {
    try {
        // Create a parser
        SpelExpressionParser parser = new SpelExpressionParser();
        // Parse an expression
        Expression expr = parser.parseRaw("new String('hello world')");
        // Evaluate it using a 'standard' context
        Object value = expr.getValue();
        // They are reusable
        value = expr.getValue();
        assertEquals("hello world", value);
        assertEquals(String.class, value.getClass());
    } catch (EvaluationException ee) {
        ee.printStackTrace();
        fail("Unexpected Exception: " + ee.getMessage());
    } catch (ParseException pe) {
        pe.printStackTrace();
        fail("Unexpected Exception: " + pe.getMessage());
    }
}
Also used : SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) Expression(org.springframework.expression.Expression) EvaluationException(org.springframework.expression.EvaluationException) ParseException(org.springframework.expression.ParseException) Test(org.junit.Test)

Example 8 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 9 with EvaluationException

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

the class ExpressionLanguageScenarioTests method testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem.

/**
	 * Scenario: using your own java methods and calling them from the expression
	 */
@Test
public void testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem() throws SecurityException, NoSuchMethodException {
    try {
        // Create a parser
        SpelExpressionParser parser = new SpelExpressionParser();
        // Use the standard evaluation context
        StandardEvaluationContext ctx = new StandardEvaluationContext();
        ctx.registerFunction("repeat", ExpressionLanguageScenarioTests.class.getDeclaredMethod("repeat", String.class));
        Expression expr = parser.parseRaw("#repeat('hello')");
        Object value = expr.getValue(ctx);
        assertEquals("hellohello", value);
    } catch (EvaluationException ee) {
        ee.printStackTrace();
        fail("Unexpected Exception: " + ee.getMessage());
    } catch (ParseException pe) {
        pe.printStackTrace();
        fail("Unexpected Exception: " + pe.getMessage());
    }
}
Also used : SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Expression(org.springframework.expression.Expression) EvaluationException(org.springframework.expression.EvaluationException) ParseException(org.springframework.expression.ParseException) Test(org.junit.Test)

Example 10 with EvaluationException

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

the class SetValueTests method setValueExpectError.

/**
	 * Call setValue() but expect it to fail.
	 */
protected void setValueExpectError(String expression, Object value) {
    try {
        Expression e = parser.parseExpression(expression);
        if (e == null) {
            fail("Parser returned null for expression");
        }
        if (DEBUG) {
            SpelUtilities.printAbstractSyntaxTree(System.out, e);
        }
        StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
        e.setValue(lContext, value);
        fail("expected an error");
    } catch (ParseException pe) {
        pe.printStackTrace();
        fail("Unexpected Exception: " + pe.getMessage());
    } catch (EvaluationException ee) {
    // success!
    }
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Expression(org.springframework.expression.Expression) ParseException(org.springframework.expression.ParseException) EvaluationException(org.springframework.expression.EvaluationException)

Aggregations

EvaluationException (org.springframework.expression.EvaluationException)25 Expression (org.springframework.expression.Expression)16 Test (org.junit.Test)14 SpelExpressionParser (org.springframework.expression.spel.standard.SpelExpressionParser)11 StandardEvaluationContext (org.springframework.expression.spel.support.StandardEvaluationContext)10 ArrayList (java.util.ArrayList)5 AccessException (org.springframework.expression.AccessException)5 ParseException (org.springframework.expression.ParseException)5 TypeDescriptor (org.springframework.core.convert.TypeDescriptor)4 SpelEvaluationException (org.springframework.expression.spel.SpelEvaluationException)4 MethodParameter (org.springframework.core.MethodParameter)3 TypeConverter (org.springframework.expression.TypeConverter)3 SpelExpression (org.springframework.expression.spel.standard.SpelExpression)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 PropertyAccessor (org.springframework.expression.PropertyAccessor)2 CompilablePropertyAccessor (org.springframework.expression.spel.CompilablePropertyAccessor)2 ReflectivePropertyAccessor (org.springframework.expression.spel.support.ReflectivePropertyAccessor)2 StandardTypeLocator (org.springframework.expression.spel.support.StandardTypeLocator)2 Constructor (java.lang.reflect.Constructor)1