Example usage for org.springframework.util ReflectionUtils findMethod

List of usage examples for org.springframework.util ReflectionUtils findMethod

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils findMethod.

Prototype

@Nullable
public static Method findMethod(Class<?> clazz, String name, @Nullable Class<?>... paramTypes) 

Source Link

Document

Attempt to find a Method on the supplied class with the supplied name and parameter types.

Usage

From source file:org.springframework.cloud.aws.messaging.endpoint.BaseNotificationMessageHandlerMethodArgumentResolverTest.java

@Test
public void resolveArgument_SubScriptionMessage_createsObjectWithAllFields() throws Exception {
    //Arrange//www  .  j  a v  a 2s.com
    AbstractNotificationMessageHandlerMethodArgumentResolver resolver = new AbstractNotificationMessageHandlerMethodArgumentResolver() {

        @Override
        protected Object doResolveArgumentFromNotificationMessage(JsonNode content, HttpInputMessage request,
                Class<?> parameterType) {
            return content;
        }

        @Override
        public boolean supportsParameter(MethodParameter parameter) {
            return true;
        }
    };

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    ServletWebRequest servletWebRequest = new ServletWebRequest(servletRequest);

    byte[] fileContent = FileCopyUtils.copyToByteArray(new ClassPathResource("subscriptionConfirmation.json",
            AbstractNotificationMessageHandlerMethodArgumentResolver.class).getInputStream());

    servletRequest.setContent(fileContent);

    MethodParameter methodParameter = new MethodParameter(ReflectionUtils.findMethod(NotificationMethods.class,
            "subscriptionMethod", NotificationStatus.class), 0);

    //Act
    @SuppressWarnings("unchecked")
    ObjectNode content = (ObjectNode) resolver.resolveArgument(methodParameter, null, servletWebRequest, null);

    //Assert
    assertEquals("SubscriptionConfirmation", content.get("Type").asText());
    assertEquals("e267b24c-5532-472f-889d-c2cdd2143bbc", content.get("MessageId").asText());
    assertEquals(
            "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
            content.get("Token").asText());
    assertEquals("arn:aws:sns:eu-west-1:111111111111:mySampleTopic", content.get("TopicArn").asText());
    assertEquals(
            "You have chosen to subscribe to the topic arn:aws:sns:eu-west-1:721324560415:mySampleTopic.To confirm the subscription, visit the SubscribeURL included in this message.",
            content.get("Message").asText());
    assertEquals(
            "https://sns.eu-west-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:eu-west-1:111111111111:mySampleTopic&Token=111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
            content.get("SubscribeURL").asText());
    assertEquals("2014-06-28T10:22:18.086Z", content.get("Timestamp").asText());
    assertEquals("1", content.get("SignatureVersion").asText());
    assertEquals(
            "JLdRUR+uhP4cyVW6bRuUSAkUosFMJyO7g7WCAwEUJoB4y8vQE1uDUWGpbQSEbruVTjPEM8hFsf4/95NftfM0W5IgND1uSnv4P/4AYyL+q0bLOJlquzXrw4w2NX3QShS3y+r/gXzo7p/UP4NOr35MGCEGPqHAEe1Coc5S0eaP3JvKU6xY1tcop6ze2RNHTwzhM43dda2bnjPYogAJzA5uHfmSjs3cMVvPCckj3zdLyvxISp+RgrogdvlNyu9ycND1SxagmbzjkBaqvF/4aiSYFxsEXX4e9zuNuHGmXGWgm1ppYUGLSPPJruCsPUa7Ii1mYvpX7SezuFZlAAXXBk0mHg==",
            content.get("Signature").asText());
    assertEquals(
            "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-e372f8ca30337fdb084e8ac449342c77.pem",
            content.get("SigningCertURL").asText());
}

From source file:org.springframework.cloud.aws.messaging.endpoint.BaseNotificationMessageHandlerMethodArgumentResolverTest.java

@Test
public void resolveArgument_NotificationMessage_createsObjectWithAllFields() throws Exception {
    //Arrange//  w  w w  .j a  v  a 2 s .co  m
    AbstractNotificationMessageHandlerMethodArgumentResolver resolver = new AbstractNotificationMessageHandlerMethodArgumentResolver() {

        @Override
        protected Object doResolveArgumentFromNotificationMessage(JsonNode content, HttpInputMessage request,
                Class<?> parameterType) {
            return content;
        }

        @Override
        public boolean supportsParameter(MethodParameter parameter) {
            return true;
        }
    };

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    ServletWebRequest servletWebRequest = new ServletWebRequest(servletRequest);

    byte[] fileContent = FileCopyUtils.copyToByteArray(new ClassPathResource("notificationMessage.json",
            AbstractNotificationMessageHandlerMethodArgumentResolver.class).getInputStream());

    servletRequest.setContent(fileContent);

    MethodParameter methodParameter = new MethodParameter(ReflectionUtils.findMethod(NotificationMethods.class,
            "subscriptionMethod", NotificationStatus.class), 0);
    //Act
    ObjectNode content = (ObjectNode) resolver.resolveArgument(methodParameter, null, servletWebRequest, null);

    //Assert
    assertEquals("Notification", content.get("Type").asText());
    assertEquals("f2c15fec-c617-5b08-b54d-13c4099fec60", content.get("MessageId").asText());
    assertEquals("arn:aws:sns:eu-west-1:111111111111:mySampleTopic", content.get("TopicArn").asText());
    assertEquals("asdasd", content.get("Subject").asText());
    assertEquals("asdasd", content.get("Message").asText());
    assertEquals("2014-06-28T14:12:24.418Z", content.get("Timestamp").asText());
    assertEquals("1", content.get("SignatureVersion").asText());
    assertEquals(
            "XDvKSAnhxECrAmyIrs0Dsfbp/tnKD1IvoOOYTU28FtbUoxr/CgziuW87yZwTuSNNbHJbdD3BEjHS0vKewm0xBeQ0PToDkgtoORXo5RWnmShDQ2nhkthFhZnNulKtmFtRogjBtCwbz8sPnbOCSk21ruyXNdV2RUbdDalndAW002CWEQmYMxFSN6OXUtMueuT610aX+tqeYP4Z6+8WTWLWjAuVyy7rOI6KHYBcVDhKtskvTOPZ4tiVohtQdQbO2Gjuh1vblRzzwMkfaoFTSWImd4pFXxEsv/fq9aGIlqq9xEryJ0w2huFwI5gxyhvGt0RnTd9YvmAEC+WzdJDOqaDNxg==",
            content.get("Signature").asText());
    assertEquals(
            "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-e372f8ca30337fdb084e8ac449342c77.pem",
            content.get("SigningCertURL").asText());
    assertEquals(
            "https://sns.eu-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:eu-west-1:721324560415:mySampleTopic:9859a6c9-6083-4690-ab02-d1aead3442df",
            content.get("UnsubscribeURL").asText());
}

From source file:org.springframework.cloud.function.web.RequestProcessor.java

private Method handlerMethod(Object handler) {
    return ReflectionUtils.findMethod(handler.getClass(), "apply", (Class<?>[]) null);
}

From source file:org.springframework.cloud.sleuth.instrument.async.ExecutorBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof Executor && !(bean instanceof ThreadPoolTaskExecutor)) {
        Method execute = ReflectionUtils.findMethod(bean.getClass(), "execute", Runnable.class);
        boolean methodFinal = Modifier.isFinal(execute.getModifiers());
        boolean classFinal = Modifier.isFinal(bean.getClass().getModifiers());
        boolean cglibProxy = !methodFinal && !classFinal;
        Executor executor = (Executor) bean;
        try {/*from   w w  w.ja  v  a 2s.c  o m*/
            return createProxy(bean, cglibProxy, executor);
        } catch (AopConfigException ex) {
            if (cglibProxy) {
                if (log.isDebugEnabled()) {
                    log.debug("Exception occurred while trying to create a proxy, falling back to JDK proxy",
                            ex);
                }
                return createProxy(bean, false, executor);
            }
            throw ex;
        }
    } else if (bean instanceof ThreadPoolTaskExecutor) {
        if (isProxyNeeded(beanName)) {
            boolean classFinal = Modifier.isFinal(bean.getClass().getModifiers());
            boolean cglibProxy = !classFinal;
            ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) bean;
            return createThreadPoolTaskExecutorProxy(bean, cglibProxy, executor);
        } else {
            log.info("Not instrumenting bean " + beanName);
        }
    }
    return bean;
}

From source file:org.springframework.cloud.sleuth.instrument.async.ExecutorBeanPostProcessor.java

private Method getMethod(MethodInvocation invocation, Object object) {
    Method method = invocation.getMethod();
    return ReflectionUtils.findMethod(object.getClass(), method.getName(), method.getParameterTypes());
}

From source file:org.springframework.data.hadoop.pig.PigUtils.java

static void validateEachStatement(PigServer pig, boolean validate) {
    Method validateMethod = ReflectionUtils.findMethod(PigServer.class, "setValidateEachStatement",
            boolean.class);
    if (validateMethod != null) {
        ReflectionUtils.invokeMethod(validateMethod, pig, validate);
    }//ww w  .  j a  v a 2 s  .  c  o m
}

From source file:org.springframework.flex.core.MessageBrokerFactoryBean.java

private void setInitServletContext() {

    // This is undesirable but necessary at the moment for LCDS to be able to load its license configuration.
    // Hopefully we can get the BlazeDS/LCDS team to give us a better option in the future.
    Method initMethod = ReflectionUtils.findMethod(MessageBroker.class, "setServletContext",
            new Class[] { ServletContext.class });
    if (initMethod == null) {
        initMethod = ReflectionUtils.findMethod(MessageBroker.class, "setInitServletContext",
                new Class[] { ServletContext.class });
    }//from   ww  w.  j  av a2 s  .c om
    ReflectionUtils.makeAccessible(initMethod);
    ReflectionUtils.invokeMethod(initMethod, this.messageBroker, new Object[] { this.servletContext });
}

From source file:org.springframework.test.util.ReflectionTestUtils.java

/**
 * Invoke the setter method with the given {@code name} on the supplied
 * target object with the supplied {@code value}.
 * <p>This method traverses the class hierarchy in search of the desired
 * method. In addition, an attempt will be made to make non-{@code public}
 * methods <em>accessible</em>, thus allowing one to invoke {@code protected},
 * {@code private}, and <em>package-private</em> setter methods.
 * <p>In addition, this method supports JavaBean-style <em>property</em>
 * names. For example, if you wish to set the {@code name} property on the
 * target object, you may pass either &quot;name&quot; or
 * &quot;setName&quot; as the method name.
 * @param target the target object on which to invoke the specified setter
 * method/*from w  w w  .j  a v  a 2s . c o  m*/
 * @param name the name of the setter method to invoke or the corresponding
 * property name
 * @param value the value to provide to the setter method
 * @param type the formal parameter type declared by the setter method
 * @see ReflectionUtils#findMethod(Class, String, Class[])
 * @see ReflectionUtils#makeAccessible(Method)
 * @see ReflectionUtils#invokeMethod(Method, Object, Object[])
 */
public static void invokeSetterMethod(Object target, String name, @Nullable Object value,
        @Nullable Class<?> type) {
    Assert.notNull(target, "Target object must not be null");
    Assert.hasText(name, "Method name must not be empty");
    Class<?>[] paramTypes = (type != null ? new Class<?>[] { type } : null);

    String setterMethodName = name;
    if (!name.startsWith(SETTER_PREFIX)) {
        setterMethodName = SETTER_PREFIX + StringUtils.capitalize(name);
    }

    Method method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
    if (method == null && !setterMethodName.equals(name)) {
        setterMethodName = name;
        method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
    }
    if (method == null) {
        throw new IllegalArgumentException(
                String.format("Could not find setter method '%s' on %s with parameter type [%s]",
                        setterMethodName, safeToString(target), type));
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Invoking setter method '%s' on %s with value [%s]", setterMethodName,
                safeToString(target), value));
    }

    ReflectionUtils.makeAccessible(method);
    ReflectionUtils.invokeMethod(method, target, value);
}

From source file:org.springframework.webflow.validation.ValidationHelper.java

private boolean invokeValidateMethodForCurrentState(Object model) {
    String methodName = "validate" + StringUtils.capitalize(requestContext.getCurrentState().getId());
    // preferred/*from   w ww .j  ava 2  s .  c  om*/
    Method validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName,
            new Class[] { ValidationContext.class });
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Invoking current state model validation method '" + methodName + "(ValidationContext)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, model,
                new Object[] { new DefaultValidationContext(requestContext, eventId, mappingResults) });
        return true;
    }
    // web flow 2.0.3 or < compatibility only
    validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName,
            new Class[] { MessageContext.class });
    if (validateMethod != null) {
        ReflectionUtils.invokeMethod(validateMethod, model,
                new Object[] { requestContext.getMessageContext() });
        return true;
    }
    // mvc 2 compatibility only
    validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName, new Class[] { Errors.class });
    if (validateMethod != null) {
        MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
                model, expressionParser, messageCodesResolver, mappingResults);
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking current state model validation method '" + methodName + "(Errors)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { errors });
        return true;
    }
    return false;
}

From source file:org.springframework.webflow.validation.ValidationHelper.java

private boolean invokeDefaultValidateMethod(Object model) {
    // preferred//  w w  w  . j  ava 2 s .c  om
    Method validateMethod = ReflectionUtils.findMethod(model.getClass(), "validate",
            new Class[] { ValidationContext.class });
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking default model validation method 'validate(ValidationContext)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, model,
                new Object[] { new DefaultValidationContext(requestContext, eventId, mappingResults) });
        return true;
    }
    // mvc 2 compatibility only
    validateMethod = ReflectionUtils.findMethod(model.getClass(), "validate", new Class[] { Errors.class });
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking default model validation method 'validate(Errors)'");
        }
        MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
                model, expressionParser, messageCodesResolver, mappingResults);
        ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { errors });
        return true;
    }
    return false;
}