Example usage for org.springframework.util ReflectionUtils getAllDeclaredMethods

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

Introduction

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

Prototype

public static Method[] getAllDeclaredMethods(Class<?> leafClass) 

Source Link

Document

Get all declared methods on the leaf class and all superclasses.

Usage

From source file:com.shigengyu.hyperion.cache.WorkflowTransitionCacheLoader.java

@Override
public ImmutableList<WorkflowTransition> load(WorkflowDefinition workflowDefinition) throws Exception {

    List<WorkflowTransition> workflowTransitions = Lists.newArrayList();

    for (Method method : ReflectionUtils
            .getAllDeclaredMethods(workflowDefinition.getWorkflowDefinitionType())) {
        if (method.isAnnotationPresent(Transition.class)) {
            Transition transition = method.getAnnotation(Transition.class);
            TransitionShared transitionShared = method.getAnnotation(TransitionShared.class);
            workflowTransitions.add(new WorkflowTransition(method, transition, transitionShared));
        } else if (method.isAnnotationPresent(Transitions.class)) {
            Transitions transitions = method.getAnnotation(Transitions.class);
            for (Transition transition : transitions.value()) {
                TransitionShared transitionShared = method.getAnnotation(TransitionShared.class);
                workflowTransitions.add(new WorkflowTransition(method, transition, transitionShared));
            }/*  w ww  . ja  va2  s.co  m*/
        }
    }

    return ImmutableList.copyOf(workflowTransitions);
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.EnableScanAnnotationPermissions.java

public EnableScanAnnotationPermissions(Class<?> repositoryInterface) {
    // Check to see if global EnableScan is declared at interface level
    if (repositoryInterface.isAnnotationPresent(EnableScan.class)) {
        this.findAllUnpaginatedScanEnabled = true;
        this.countUnpaginatedScanEnabled = true;
        this.deleteAllUnpaginatedScanEnabled = true;
        this.findAllPaginatedScanEnabled = true;
    } else {//from w  ww .j  a v  a2  s. c o  m
        // Check declared methods for EnableScan annotation
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(repositoryInterface);
        for (Method method : methods) {

            if (!method.isAnnotationPresent(EnableScan.class) || method.getParameterTypes().length > 0) {
                // Only consider methods which have the EnableScan
                // annotation and which accept no parameters
                continue;
            }

            if (method.getName().equals("findAll")) {
                findAllUnpaginatedScanEnabled = true;
                continue;
            }

            if (method.getName().equals("deleteAll")) {
                deleteAllUnpaginatedScanEnabled = true;
                continue;
            }

            if (method.getName().equals("count")) {
                countUnpaginatedScanEnabled = true;
                continue;
            }

        }
        for (Method method : methods) {

            if (!method.isAnnotationPresent(EnableScanCount.class) || method.getParameterTypes().length != 1) {
                // Only consider methods which have the EnableScanCount
                // annotation and which have a single pageable parameter
                continue;
            }

            if (method.getName().equals("findAll")
                    && Pageable.class.isAssignableFrom(method.getParameterTypes()[0])) {
                findAllUnpaginatedScanCountEnabled = true;
                continue;
            }

        }
        for (Method method : methods) {

            if (!method.isAnnotationPresent(EnableScan.class) || method.getParameterTypes().length != 1) {
                // Only consider methods which have the EnableScan
                // annotation and which have a single pageable parameter
                continue;
            }

            if (method.getName().equals("findAll")
                    && Pageable.class.isAssignableFrom(method.getParameterTypes()[0])) {
                findAllPaginatedScanEnabled = true;
                continue;
            }

        }
    }
    if (!findAllUnpaginatedScanCountEnabled && repositoryInterface.isAnnotationPresent(EnableScanCount.class)) {
        findAllUnpaginatedScanCountEnabled = true;
    }

}

From source file:com.agileapes.couteau.context.spring.event.impl.GenericTranslationScheme.java

@Override
public ApplicationEvent translate(Event originalEvent) throws EventTranslationException {
    final Method[] methods = ReflectionUtils.getAllDeclaredMethods(originalEvent.getClass());
    final GenericApplicationEvent applicationEvent = new GenericApplicationEvent(originalEvent.getSource(),
            originalEvent);//w w w .  jav  a2  s . c  o  m
    for (Method method : methods) {
        if (!isGetter(method)) {
            continue;
        }
        final String propertyName = StringUtils
                .uncapitalize(method.getName().substring(method.getName().startsWith("get") ? 3 : 2));
        try {
            applicationEvent.setProperty(propertyName, method.invoke(originalEvent));
        } catch (Exception e) {
            throw new EventTranslationException("Failed to set property on translated event: " + propertyName);
        }
    }
    return applicationEvent;
}

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
 *//*w w  w  . j  a v a 2 s .  co 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:koper.MessageListenerBeanPostProcessor.java

/**
 * ?//w  w  w  .  ja v a 2  s. co m
 *
 * @param clazz
 * @param methodName
 * @return
 */
protected Method getMethod(Class<?> clazz, String methodName) {

    Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz); //clazz.getDeclaredMethods();
    Method findMethod = null;
    for (Method method : methods) {
        if (method.getName().equals(methodName) && method.getAnnotations().length != 0) {
            findMethod = method;
        }
    }
    return findMethod;
}

From source file:com.github.dactiv.fear.service.RemoteApiCaller.java

/**
 * ??//w  ww.j  a va 2 s.co  m
 *
 * @param targetClass  class
 * @param method      ??
 * @param paramTypes  ?
 *
 * @return 
 */
private Method findParamMethod(Class<?> targetClass, String method, Class<?>[] paramTypes) {

    // ?
    Method[] methods = (targetClass.isInterface() ? targetClass.getMethods()
            : ReflectionUtils.getAllDeclaredMethods(targetClass));

    // ?
    for (Method m : methods) {
        // ??
        Class<?>[] methodParamTypes = m.getParameterTypes();
        // ??????
        if (m.getName().equals(method) && methodParamTypes.length == paramTypes.length) {
            // ??
            Boolean flag = Boolean.TRUE;
            // ??flag  true
            for (int i = 0; i < methodParamTypes.length; i++) {

                Class<?> paramTarget = paramTypes[i];
                Class<?> paramSource = methodParamTypes[i];

                if (paramTarget != null && paramTarget != paramSource
                        && !paramSource.isAssignableFrom(paramTarget)) {
                    flag = Boolean.FALSE;
                }

            }

            if (flag) {
                cacheService(targetClass, m, paramTypes);
                return m;
            }

        }

    }

    return null;
}

From source file:com.consol.citrus.admin.service.TestCaseServiceImpl.java

/**
 * Finds all Citrus annotated test methods in test class. Do only return methods when more than one test method
 * is found. Otherwise use class itself as test representation.
 * @param testClass//w  w w.j a  v  a2 s.  c  o m
 * @return
 */
private List<String> getTestMethods(Class<?> testClass) {
    List<String> methodNames = new ArrayList<String>();
    for (Method method : ReflectionUtils.getAllDeclaredMethods(testClass)) {
        if (method.getAnnotation(CitrusTest.class) != null) {
            CitrusTest citrusAnnotation = method.getAnnotation(CitrusTest.class);

            if (StringUtils.hasText(citrusAnnotation.name())) {
                methodNames.add(citrusAnnotation.name());
            } else {
                // use default method name as test
                methodNames.add(method.getName());
            }
        }
    }

    return methodNames;
}

From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java

/**
 * Constructor: Sets up hTablePool and scans base package paths looking for classes annotated with @HBasePersistance
 * //from   ww  w. j a  va2 s  .co  m
 * @param hTablePool
 * @param basePackages
 */
@SuppressWarnings("unchecked")
public HBaseEntityMapper(HTablePool hTablePool, String... basePackages) {

    final HBaseAdmin hBaseAdmin;
    try {
        hBaseAdmin = new HBaseAdmin((Configuration) Whitebox.getInternalState(hTablePool, "config"));
    } catch (IOException e) {
        LOG.fatal("Could not connect to HBase failing HBase object mapping!", e);
        this.hTablePool = null;
        this.annotatedClassToAnnotatedHBaseRowKey = null;
        this.annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethod = null;
        this.annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethod = null;
        this.annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod = null;
        return;
    }

    this.hTablePool = hTablePool;

    final Map<Class<?>, AccessibleObject> annotatedClassToAnnotatedHBaseRowKeyMap = new HashMap<Class<?>, AccessibleObject>();

    final Map<Class<?>, ImmutableMap<Field, Method>> annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethodMap = new HashMap<Class<?>, ImmutableMap<Field, Method>>();

    final Map<Class<?>, ImmutableMap<Field, Method>> annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethodMap = new HashMap<Class<?>, ImmutableMap<Field, Method>>();

    final Map<Class<?>, ImmutableMap<Field, Method>> annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethodMap = new HashMap<Class<?>, ImmutableMap<Field, Method>>();

    /*
     * Only include classes annotated with @HBasePersistance
     */
    scanner.addIncludeFilter(new AnnotationTypeFilter(HBasePersistance.class));

    for (final String basePackage : basePackages) {

        for (final BeanDefinition beanDefinition : scanner.findCandidateComponents(basePackage)) {
            final Class<?> annotatedClass;
            try {
                annotatedClass = Class.forName(beanDefinition.getBeanClassName());
            } catch (ClassNotFoundException e) {
                // should never happen
                LOG.error("ClassNotFoundException while loading class for HBase entity mapper", e);
                throw new RuntimeException(e);
            }
            /*
             * Get the hbase table name - required!
             */
            final String tableName = annotatedClass.getAnnotation(HBasePersistance.class).tableName();
            if (StringUtils.isEmpty(tableName)) {
                LOG.error("@HBasePersistance must have a non-empty tableName. Ignoring: " + annotatedClass);
                continue;
            }

            try {
                if (!hBaseAdmin.tableExists(tableName)) {
                    LOG.error("table " + tableName
                            + " in @HBasePersistance.tableName() does not exist. Ignoring: " + annotatedClass);
                    continue;
                }
            } catch (IOException e) {
                LOG.error("Could not verify table " + tableName
                        + "in @HBasePersistance.tableName() exists. Ignoring: " + annotatedClass, e);
                continue;
            }

            /*
             * Get the default hbase column family name. This will be used as default column family where fields are
             * mapped to but not required if all annotated fields specifically mention the column family they belong
             * to.
             * 
             * TODO: Current implementation makes this field required but it really isn't based on my
             * comment made previously. That is, if all annotated fields specifically mention the column family
             * where they will be found then a default column family name is unneeded.
             */
            final String defaultColumnFamilyName = annotatedClass.getAnnotation(HBasePersistance.class)
                    .defaultColumnFamilyName();
            if (StringUtils.isEmpty(defaultColumnFamilyName)) {
                LOG.error("@HBasePersistance must have a non-empty defaultColumnFamilyName. Ignoring: "
                        + annotatedClass);
                continue;
            }

            try {
                /*
                 * Confirm the hbase table and column family exists
                 */
                if (!hBaseAdmin.getTableDescriptor(Bytes.toBytes(tableName))
                        .hasFamily(Bytes.toBytes(defaultColumnFamilyName))) {
                    LOG.error("defaultColumnFamilyName (" + defaultColumnFamilyName + ") in " + tableName
                            + "in @HBasePersistance.defaultColumnFamilyName() does not exist. Ignoring: "
                            + annotatedClass);
                    continue;
                }
            } catch (IOException e) {
                LOG.error("Could not verify defaultColumnFamilyName (" + defaultColumnFamilyName + ") in "
                        + tableName + "in @HBasePersistance.defaultColumnFamilyName() exists. Ignoring: "
                        + annotatedClass, e);
                continue;
            }

            /*
             * @HBaseField : Find fields with this annotation and their corresponding getter method
             */
            Set<Field> hBaseFieldAnnotatedFieldsSet = Whitebox
                    .getFieldsAnnotatedWith(Whitebox.newInstance(annotatedClass), HBaseField.class);

            /*
             * Use a Predicate to look through all @HBaseField annotated fields and skip whole class if even one
             * field is not supported
             */
            if (CollectionUtils.exists(hBaseFieldAnnotatedFieldsSet,
                    new org.apache.commons.collections.Predicate() {

                        @Override
                        public boolean evaluate(Object object) {

                            return !TypeHandler.supports(((Field) object).getType());
                        }
                    })) {
                LOG.error("Unsupported type annotated with @HBaseField. Ignoring: " + annotatedClass);
                continue;
            }

            annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethodMap.put(annotatedClass,
                    fieldsToGetterMap(annotatedClass, ImmutableSet.copyOf(hBaseFieldAnnotatedFieldsSet)));

            /*
             * @HBaseObjectField : Find all fields with this annotation and their corresponding getter method
             */
            annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethodMap.put(annotatedClass,
                    fieldsToGetterMap(annotatedClass, ImmutableSet.copyOf(Whitebox.getFieldsAnnotatedWith(
                            Whitebox.newInstance(annotatedClass), HBaseObjectField.class))));

            /*
             * @HBaseMapField : See if this annotation exists and if so, make sure there is only one
             */
            final Set<Field> hBaseMapFieldAnnotatedFieldsSet = Whitebox
                    .getFieldsAnnotatedWith(Whitebox.newInstance(annotatedClass), HBaseMapField.class);

            if (hBaseMapFieldAnnotatedFieldsSet.size() > 1) {
                LOG.error(
                        "@HBaseMapField can only be used on one field per class. Ignoring: " + annotatedClass);
                continue;
            }
            final Iterator<Field> hBaseMapFieldsIterator = hBaseMapFieldAnnotatedFieldsSet.iterator();
            if (hBaseMapFieldsIterator.hasNext()) {
                final Field field = hBaseMapFieldsIterator.next();
                final Type[] types = TypeHandler.getGenericTypesFromField(field);

                if ((Modifier.isAbstract(field.getType().getModifiers()) && !Map.class.equals(field.getType()))
                        || !Map.class.isAssignableFrom(field.getType())
                        || !String.class.equals((Class<?>) types[0])
                        || !String.class.equals((Class<?>) types[1])) {
                    LOG.error(
                            "@HBaseMapField must be used on a field of type java.util.Map<String, String> OR a concrete fields assignable from java.util.Map<String, String> . Ignoring: "
                                    + annotatedClass);
                    continue;
                }
                annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethodMap.put(annotatedClass,
                        fieldsToGetterMap(annotatedClass,
                                ImmutableSet.copyOf(hBaseMapFieldAnnotatedFieldsSet)));

            }

            /*
             * Figure out which method or field to use as the HBaseRowKey this has to be at the end since
             * 
             * @HBaseRowKey is required in the class we can use this to key the other maps we are collecting
             */
            final Set<Field> hBaseRowKeyFields = Whitebox
                    .getFieldsAnnotatedWith(Whitebox.newInstance(annotatedClass), HBaseRowKey.class);
            if (hBaseRowKeyFields.size() > 1) {
                LOG.error("@HBaseRowKey can only be used once per class. Ignoring: " + annotatedClass);
                continue;
            }
            final Collection<Method> hBaseRowKeyMethods = Collections2.filter(
                    Arrays.asList(ReflectionUtils.getAllDeclaredMethods(annotatedClass)),
                    new Predicate<Method>() {

                        @Override
                        public boolean apply(final Method method) {
                            return method.getAnnotation(HBaseRowKey.class) != null;
                        }
                    });
            if (hBaseRowKeyFields.size() + hBaseRowKeyMethods.size() > 1) {
                LOG.error("@HBaseRowKey can only be used once per class. Ignoring: " + annotatedClass);
                continue;
            }

            if (hBaseRowKeyFields.size() + hBaseRowKeyMethods.size() == 0) {
                LOG.error("@HBaseRowKey is required. Ignoring: " + annotatedClass);
                continue;
            }

            if (hBaseRowKeyFields.isEmpty()) {
                final Method hBaseRowKeyMethod = hBaseRowKeyMethods.iterator().next();
                if (hBaseRowKeyMethod.getParameterTypes().length > 0) {
                    LOG.error("@HBaseRowKey can only be used on a no arguemnt method. Ignoring: "
                            + annotatedClass);
                    continue;
                }
                annotatedClassToAnnotatedHBaseRowKeyMap.put(annotatedClass, hBaseRowKeyMethod);
            } else {
                annotatedClassToAnnotatedHBaseRowKeyMap.put(annotatedClass,
                        hBaseRowKeyFields.iterator().next());
            }
        }
    }

    /*
     * keep only the valid classed in our maps
     */
    annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethodMap.keySet()
            .retainAll(annotatedClassToAnnotatedHBaseRowKeyMap.keySet());
    annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethodMap.keySet()
            .retainAll(annotatedClassToAnnotatedHBaseRowKeyMap.keySet());
    annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethodMap.keySet()
            .retainAll(annotatedClassToAnnotatedHBaseRowKeyMap.keySet());

    // set our state
    this.annotatedClassToAnnotatedHBaseRowKey = ImmutableMap.copyOf(annotatedClassToAnnotatedHBaseRowKeyMap);
    this.annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethod = ImmutableMap
            .copyOf(annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethodMap);
    this.annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethod = ImmutableMap
            .copyOf(annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethodMap);
    this.annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod = ImmutableMap
            .copyOf(annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethodMap);
}

From source file:org.codehaus.groovy.grails.web.servlet.mvc.CommandObjectEnablingPostProcessor.java

private void scanMethodActions(GroovyObject controller) {
    Method[] methods = ReflectionUtils.getAllDeclaredMethods(controller.getClass());
    Action actionAnn = null;/*from w w  w  . jav a2  s.c  om*/
    for (Method method : methods) {
        actionAnn = method.getAnnotation(Action.class);
        Class[] commandObjectClasses = actionAnn != null ? actionAnn.commandObjects() : null;
        if (commandObjectClasses != null && commandObjectClasses.length > 0) {
            WebMetaUtils.prepareCommandObjectBindingAction(method, commandObjectClasses, applicationContext);
        }
    }
}