Search in sources :

Example 6 with AccessException

use of org.springframework.expression.AccessException 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 AccessException

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

the class MethodInvocationTests method invokeMethodWithoutConversion.

@Test
public void invokeMethodWithoutConversion() throws Exception {
    final BytesService service = new BytesService();
    byte[] bytes = new byte[100];
    StandardEvaluationContext context = new StandardEvaluationContext(bytes);
    context.setBeanResolver(new BeanResolver() {

        @Override
        public Object resolve(EvaluationContext context, String beanName) throws AccessException {
            if ("service".equals(beanName)) {
                return service;
            }
            return null;
        }
    });
    Expression expression = parser.parseExpression("@service.handleBytes(#root)");
    byte[] outBytes = expression.getValue(context, byte[].class);
    assertSame(bytes, outBytes);
}
Also used : BeanResolver(org.springframework.expression.BeanResolver) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) AccessException(org.springframework.expression.AccessException) SpelExpression(org.springframework.expression.spel.standard.SpelExpression) Expression(org.springframework.expression.Expression) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Test(org.junit.Test)

Example 8 with AccessException

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

the class SpelReproTests method accessingNullPropertyViaReflection_SPR5663.

@Test
public void accessingNullPropertyViaReflection_SPR5663() throws AccessException {
    PropertyAccessor propertyAccessor = new ReflectivePropertyAccessor();
    EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
    assertFalse(propertyAccessor.canRead(context, null, "abc"));
    assertFalse(propertyAccessor.canWrite(context, null, "abc"));
    try {
        propertyAccessor.read(context, null, "abc");
        fail("Should have failed with an AccessException");
    } catch (AccessException ae) {
    // success
    }
    try {
        propertyAccessor.write(context, null, "abc", "foo");
        fail("Should have failed with an AccessException");
    } catch (AccessException ae) {
    // success
    }
}
Also used : ReflectivePropertyAccessor(org.springframework.expression.spel.support.ReflectivePropertyAccessor) PropertyAccessor(org.springframework.expression.PropertyAccessor) AccessException(org.springframework.expression.AccessException) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) ReflectivePropertyAccessor(org.springframework.expression.spel.support.ReflectivePropertyAccessor) Test(org.junit.Test)

Example 9 with AccessException

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

the class SpelReproTests method beanResolution.

// bean resolver tests
@Test
public void beanResolution() {
    StandardEvaluationContext eContext = new StandardEvaluationContext(new XX());
    Expression expr = null;
    // no resolver registered == exception
    try {
        expr = new SpelExpressionParser().parseRaw("@foo");
        assertEquals("custard", expr.getValue(eContext, String.class));
    } catch (SpelEvaluationException see) {
        assertEquals(SpelMessage.NO_BEAN_RESOLVER_REGISTERED, see.getMessageCode());
        assertEquals("foo", see.getInserts()[0]);
    }
    eContext.setBeanResolver(new MyBeanResolver());
    // bean exists
    expr = new SpelExpressionParser().parseRaw("@foo");
    assertEquals("custard", expr.getValue(eContext, String.class));
    // bean does not exist
    expr = new SpelExpressionParser().parseRaw("@bar");
    assertEquals(null, expr.getValue(eContext, String.class));
    // bean name will cause AccessException
    expr = new SpelExpressionParser().parseRaw("@goo");
    try {
        assertEquals(null, expr.getValue(eContext, String.class));
    } catch (SpelEvaluationException see) {
        assertEquals(SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION, see.getMessageCode());
        assertEquals("goo", see.getInserts()[0]);
        assertTrue(see.getCause() instanceof AccessException);
        assertTrue(see.getCause().getMessage().startsWith("DONT"));
    }
    // bean exists
    expr = new SpelExpressionParser().parseRaw("@'foo.bar'");
    assertEquals("trouble", expr.getValue(eContext, String.class));
    // bean exists
    try {
        expr = new SpelExpressionParser().parseRaw("@378");
        assertEquals("trouble", expr.getValue(eContext, String.class));
    } catch (SpelParseException spe) {
        assertEquals(SpelMessage.INVALID_BEAN_REFERENCE, spe.getMessageCode());
    }
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) AccessException(org.springframework.expression.AccessException) SpelExpression(org.springframework.expression.spel.standard.SpelExpression) Expression(org.springframework.expression.Expression) Test(org.junit.Test)

Example 10 with AccessException

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

the class SpelReproTests method SPR9495.

@Test
public void SPR9495() throws Exception {
    SpelParserConfiguration configuration = new SpelParserConfiguration(false, false);
    ExpressionParser parser = new SpelExpressionParser(configuration);
    StandardEvaluationContext context = new StandardEvaluationContext();
    Expression spel = parser.parseExpression("#enumType.values()");
    context.setVariable("enumType", ABC.class);
    Object result = spel.getValue(context);
    assertNotNull(result);
    assertTrue(result.getClass().isArray());
    assertEquals(ABC.A, Array.get(result, 0));
    assertEquals(ABC.B, Array.get(result, 1));
    assertEquals(ABC.C, Array.get(result, 2));
    context.addMethodResolver(new MethodResolver() {

        @Override
        public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name, List<TypeDescriptor> argumentTypes) throws AccessException {
            return new MethodExecutor() {

                @Override
                public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException {
                    try {
                        Method method = XYZ.class.getMethod("values");
                        Object value = method.invoke(target, arguments);
                        return new TypedValue(value, new TypeDescriptor(new MethodParameter(method, -1)).narrow(value));
                    } catch (Exception ex) {
                        throw new AccessException(ex.getMessage(), ex);
                    }
                }
            };
        }
    });
    result = spel.getValue(context);
    assertNotNull(result);
    assertTrue(result.getClass().isArray());
    assertEquals(XYZ.X, Array.get(result, 0));
    assertEquals(XYZ.Y, Array.get(result, 1));
    assertEquals(XYZ.Z, Array.get(result, 2));
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) MethodResolver(org.springframework.expression.MethodResolver) ReflectiveMethodResolver(org.springframework.expression.spel.support.ReflectiveMethodResolver) Method(java.lang.reflect.Method) ExpressionException(org.springframework.expression.ExpressionException) EvaluationException(org.springframework.expression.EvaluationException) ExpectedException(org.junit.rules.ExpectedException) AccessException(org.springframework.expression.AccessException) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) AccessException(org.springframework.expression.AccessException) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) SpelExpression(org.springframework.expression.spel.standard.SpelExpression) Expression(org.springframework.expression.Expression) MethodExecutor(org.springframework.expression.MethodExecutor) ExpressionParser(org.springframework.expression.ExpressionParser) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) MethodParameter(org.springframework.core.MethodParameter) TypedValue(org.springframework.expression.TypedValue) Test(org.junit.Test)

Aggregations

AccessException (org.springframework.expression.AccessException)14 TypeDescriptor (org.springframework.core.convert.TypeDescriptor)9 EvaluationException (org.springframework.expression.EvaluationException)6 SpelEvaluationException (org.springframework.expression.spel.SpelEvaluationException)5 Method (java.lang.reflect.Method)4 Test (org.junit.Test)4 MethodParameter (org.springframework.core.MethodParameter)4 EvaluationContext (org.springframework.expression.EvaluationContext)4 TypedValue (org.springframework.expression.TypedValue)4 StandardEvaluationContext (org.springframework.expression.spel.support.StandardEvaluationContext)4 ArrayList (java.util.ArrayList)3 Expression (org.springframework.expression.Expression)3 SpelExpression (org.springframework.expression.spel.standard.SpelExpression)3 Field (java.lang.reflect.Field)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 ConstructorExecutor (org.springframework.expression.ConstructorExecutor)2 MethodExecutor (org.springframework.expression.MethodExecutor)2 PropertyAccessor (org.springframework.expression.PropertyAccessor)2 TypeConverter (org.springframework.expression.TypeConverter)2 SpelExpressionParser (org.springframework.expression.spel.standard.SpelExpressionParser)2