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) 

Source Link

Document

Attempt to find a Method on the supplied class with the supplied name and no parameters.

Usage

From source file:com.cloudera.csd.validation.references.components.ReflectionHelperTest.java

private static Method method(Class<?> clazz, String name) {
    Method m = ReflectionUtils.findMethod(clazz, name);
    assertNotNull("Method name: " + name + " for class: " + clazz.getSimpleName(), m);
    return m;/*from  ww w .  ja  va2 s. c o  m*/
}

From source file:es.logongas.ix3.util.ReflectionUtilTest.java

/**
 * Test of getMethod method, of class ReflectionUtil.
 *///w  w w  . jav  a  2 s.  c om
@Test
public void testGetMethod() {
    System.out.println("getMethod");
    Class clazz = BeanTestC.class;
    String methodName = "getProp";
    Method expResult = ReflectionUtils.findMethod(clazz, methodName);
    Method result = ReflectionUtil.getMethod(clazz, methodName);
    assertEquals(expResult, result);
}

From source file:es.logongas.ix3.util.ReflectionUtilTest.java

@Test
public void testGetMethodNull() {
    System.out.println("testGetMethodNull");
    Class clazz = BeanTestC.class;
    String methodName = "nada";
    Method expResult = ReflectionUtils.findMethod(clazz, methodName);
    Method result = ReflectionUtil.getMethod(clazz, methodName);
    assertEquals(expResult, result);/*  w  w  w . j ava2 s  . c  om*/
}

From source file:org.synyx.hades.dao.query.QueryMethod.java

/**
 * Returns whether the given field is valid field name and thus a persistent
 * field to the underlying domain class.
 * //from  w  w  w . j  a  v a  2  s .  c om
 * @param fieldName
 * @return
 */
boolean isValidField(String fieldName) {

    Class<?> returnType = ClassUtils.getReturnedDomainClass(method);

    if (null != ReflectionUtils.findMethod(returnType, "get" + fieldName)) {
        return true;
    }

    return null != ReflectionUtils.findField(returnType, StringUtils.uncapitalize(fieldName));
}

From source file:com.reactive.hzdfs.io.MemoryMappedChunkHandler.java

private static boolean unmap(MappedByteBuffer bb) {
    /*/*from   w  ww  .  j  av  a2  s.com*/
     * From  sun.nio.ch.FileChannelImpl
     * private static void  unmap(MappedByteBuffer bb) {
                  
           Cleaner cl = ((DirectBuffer)bb).cleaner();
           if (cl != null)
       cl.clean();
            
            
       }
     */
    try {
        Method cleaner_method = ReflectionUtils.findMethod(bb.getClass(), "cleaner");
        if (cleaner_method != null) {
            cleaner_method.setAccessible(true);
            Object cleaner = cleaner_method.invoke(bb);
            if (cleaner != null) {
                Method clean_method = ReflectionUtils.findMethod(cleaner.getClass(), "clean");
                clean_method.setAccessible(true);
                clean_method.invoke(cleaner);
                return true;
            }
        }

    } catch (Exception ex) {
        log.debug("", ex);
    }
    return false;
}

From source file:net.paslavsky.springrest.SpringRestClientMethodInterceptorTest.java

@Test
public void testInvoke() throws Throwable {
    Assert.assertEquals(interceptor.invoke(methodInvocation), "Test OK!");

    Mockito.verify(methodInvocation, Mockito.times(1)).getMethod();
    Mockito.verify(annotationPreprocessor, Mockito.times(1)).parse(Mockito.eq(getClass()),
            Mockito.eq(ReflectionUtils.findMethod(getClass(), "testInvoke")));
    Mockito.verify(methodInvocation, Mockito.times(1)).getArguments();
    Mockito.verify(authenticationManager, Mockito.times(1)).getAuthenticationHeaders();
    Mockito.verifyNoMoreInteractions(methodInvocation, annotationPreprocessor, authenticationManager);
    Mockito.verify(requestFactory, Mockito.times(1)).createRequest(
            Mockito.eq(URI.create("http://example.com/somePath/subPath")), Mockito.eq(HttpMethod.GET));

    Mockito.verify(request, Mockito.atLeastOnce()).getHeaders();
    Mockito.verify(request, Mockito.atLeastOnce()).getBody();

    Assert.assertEquals(request.getHeaders().getFirst("Auth"), "######");
    Assert.assertEquals(request.getBodyAsString(), "Request");
}

From source file:org.openmrs.module.webservices.rest.web.DelegatingCrudResourceTest.java

/**
 * This test looks at all subclasses of DelegatingCrudResource, and test all {@link RepHandler}
 * methods to make sure they are all capable of running without exceptions. It also checks that
 *//*  www .  j ava  2 s. c o m*/
@SuppressWarnings("rawtypes")
@Test
@Ignore
public void testAllReprsentationDescriptions() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            true);
    //only match subclasses of BaseDelegatingResource
    provider.addIncludeFilter(new AssignableTypeFilter(BaseDelegatingResource.class));

    // scan in org.openmrs.module.webservices.rest.web.resource package 
    Set<BeanDefinition> components = provider
            .findCandidateComponents("org.openmrs.module.webservices.rest.web.resource");
    if (CollectionUtils.isEmpty(components))
        Assert.fail("Faile to load any resource classes");

    for (BeanDefinition component : components) {
        Class resourceClass = Class.forName(component.getBeanClassName());
        for (Method method : ReflectionUtils.getAllDeclaredMethods(resourceClass)) {
            ParameterizedType parameterizedType = (ParameterizedType) resourceClass.getGenericSuperclass();
            Class openmrsClass = (Class) parameterizedType.getActualTypeArguments()[0];
            //User Resource is special in that the Actual parameterized Type isn't a standard domain object, so we also
            //need to look up fields and methods from the org.openmrs.User class 
            boolean isUserResource = resourceClass.equals(UserResource1_8.class);
            List<Object> refDescriptions = new ArrayList<Object>();

            if (method.getName().equals("getRepresentationDescription")
                    && method.getDeclaringClass().equals(resourceClass)) {
                //get all the rep definitions for all representations
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.REF }));
                refDescriptions.add(
                        method.invoke(resourceClass.newInstance(), new Object[] { Representation.DEFAULT }));
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.FULL }));
            }

            for (Object value : refDescriptions) {
                if (value != null) {
                    DelegatingResourceDescription des = (DelegatingResourceDescription) value;
                    for (String key : des.getProperties().keySet()) {
                        if (!key.equals("uri") && !key.equals("display") && !key.equals("auditInfo")) {
                            boolean hasFieldOrPropertySetter = (ReflectionUtils.findField(openmrsClass,
                                    key) != null);
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findField(User.class,
                                            key) != null);
                            }
                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);

                            //TODO replace this hacky way that we are using to check if there is a get method for a 
                            //collection that has no actual getter e.g activeIdentifers and activeAttributes for Patient
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = (ReflectionUtils.findMethod(openmrsClass,
                                        "get" + StringUtils.capitalize(key)) != null);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findMethod(User.class,
                                            "get" + StringUtils.capitalize(key)) != null);
                            }

                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = isallowedMissingProperty(resourceClass, key);

                            Assert.assertTrue(
                                    "No property found for '" + key + "' for " + openmrsClass
                                            + " nor setter method on resource " + resourceClass,
                                    hasFieldOrPropertySetter);
                        }
                    }
                }
            }
        }
    }
}

From source file:lodsve.core.condition.BeanTypeRegistry.java

private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
        throws Exception {
    if (definition instanceof AnnotatedBeanDefinition) {
        MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition)
                .getFactoryMethodMetadata();
        if (factoryMethodMetadata instanceof StandardMethodMetadata) {
            return ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod();
        }//  w w w .j a v a  2s. c o m
    }
    BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition.getFactoryBeanName());
    Class<?> factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(),
            beanFactory.getBeanClassLoader());
    return ReflectionUtils.findMethod(factoryClass, definition.getFactoryMethodName());
}

From source file:es.logongas.ix3.dao.impl.ExceptionTranslator.java

private ClassAndLabel getMethodLabel(Class clazz, String methodName) {
    String suffixMethodName = StringUtils.capitalize(methodName);
    Method method = ReflectionUtils.findMethod(clazz, "get" + suffixMethodName);
    if (method == null) {
        method = ReflectionUtils.findMethod(clazz, "is" + suffixMethodName);
        if (method == null) {
            return null;
        }/*from w ww  . j  a v  a 2 s . c  o  m*/
    }

    Label label = method.getAnnotation(Label.class);
    if (label != null) {
        return new ClassAndLabel(method.getReturnType(), label.value());
    } else {
        return new ClassAndLabel(method.getReturnType(), null);
    }

}

From source file:ch.qos.logback.ext.spring.web.WebLogbackConfigurer.java

/**
 * Initialize Logback, including setting the web app root system property.
 *
 * @param servletContext the current ServletContext
 * @see org.springframework.web.util.WebUtils#setWebAppRootSystemProperty
 *///from ww w  . j a v a2s . com
public static void initLogging(ServletContext servletContext) {
    // Expose the web app root system property.
    if (exposeWebAppRoot(servletContext)) {
        WebUtils.setWebAppRootSystemProperty(servletContext);
    }

    // Only perform custom Logback initialization in case of a config file.
    String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
    if (location != null) {
        // Perform actual Logback initialization; else rely on Logback's default initialization.
        try {
            // Resolve system property placeholders before potentially resolving real path.
            location = ServletContextPropertyUtils.resolvePlaceholders(location);
            // Return a URL (e.g. "classpath:" or "file:") as-is;
            // consider a plain file path as relative to the web application root directory.
            if (!ResourceUtils.isUrl(location)) {
                location = WebUtils.getRealPath(servletContext, location);
            }

            // Write log message to server log.
            servletContext.log("Initializing Logback from [" + location + "]");

            // Initialize
            LogbackConfigurer.initLogging(location);
        } catch (FileNotFoundException ex) {
            throw new IllegalArgumentException("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage());
        } catch (JoranException e) {
            throw new RuntimeException("Unexpected error while configuring logback", e);
        }
    }

    //If SLF4J's java.util.logging bridge is available in the classpath, install it. This will direct any messages
    //from the Java Logging framework into SLF4J. When logging is terminated, the bridge will need to be uninstalled
    try {
        Class<?> julBridge = ClassUtils.forName("org.slf4j.bridge.SLF4JBridgeHandler",
                ClassUtils.getDefaultClassLoader());

        Method removeHandlers = ReflectionUtils.findMethod(julBridge, "removeHandlersForRootLogger");
        if (removeHandlers != null) {
            servletContext.log("Removing all previous handlers for JUL to SLF4J bridge");
            ReflectionUtils.invokeMethod(removeHandlers, null);
        }

        Method install = ReflectionUtils.findMethod(julBridge, "install");
        if (install != null) {
            servletContext.log("Installing JUL to SLF4J bridge");
            ReflectionUtils.invokeMethod(install, null);
        }
    } catch (ClassNotFoundException ignored) {
        //Indicates the java.util.logging bridge is not in the classpath. This is not an indication of a problem.
        servletContext.log("JUL to SLF4J bridge is not available on the classpath");
    }
}