Example usage for org.springframework.core.annotation AnnotationUtils findAnnotation

List of usage examples for org.springframework.core.annotation AnnotationUtils findAnnotation

Introduction

In this page you can find the example usage for org.springframework.core.annotation AnnotationUtils findAnnotation.

Prototype

@Nullable
public static <A extends Annotation> A findAnnotation(Class<?> clazz, @Nullable Class<A> annotationType) 

Source Link

Document

Find a single Annotation of annotationType on the supplied Class , traversing its interfaces, annotations, and superclasses if the annotation is not directly present on the given class itself.

Usage

From source file:org.alfresco.rest.framework.core.ResourceInspector.java

/**
 * For a given class, looks for @EmbeddedEntityResource annotations, using the annotation produce
 * a Map of the property name key and the entity key
 * @return A map of property key name and a value of the entity path name
 *//*www. j a va 2 s.  c o m*/
public static Map<String, Pair<String, Method>> findEmbeddedResources(Class<?> anyClass) {
    Map<String, Pair<String, Method>> embeds = new HashMap<String, Pair<String, Method>>();
    List<Method> annotatedMethods = ResourceInspectorUtil.findMethodsByAnnotation(anyClass,
            EmbeddedEntityResource.class);
    if (annotatedMethods != null && !annotatedMethods.isEmpty()) {
        for (Method annotatedMethod : annotatedMethods) {
            Annotation annot = AnnotationUtils.findAnnotation(annotatedMethod, EmbeddedEntityResource.class);
            if (annot != null) {
                Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
                String entityPath = findEntityNameByAnnotationAttributes(annotAttribs);
                String key = String.valueOf(annotAttribs.get("propertyName"));
                embeds.put(key, new Pair<String, Method>(entityPath, annotatedMethod));
            }
        }

    }
    return embeds;
}

From source file:org.alfresco.rest.framework.core.ResourceInspector.java

/**
 * Finds operations on an entity/*from ww  w  .  j a va  2  s  . c  o  m*/
 * @param entityPath path to the entity
 * @param anyClass resource clause
 * @return The operations
 */
private static Map<String, Pair<ResourceOperation, Method>> findOperations(String entityPath,
        Class<?> anyClass) {
    Map<String, Pair<ResourceOperation, Method>> embeds = new HashMap<String, Pair<ResourceOperation, Method>>();
    List<Method> annotatedMethods = ResourceInspectorUtil.findMethodsByAnnotation(anyClass, Operation.class);
    if (annotatedMethods != null && !annotatedMethods.isEmpty())
        for (Method annotatedMethod : annotatedMethods) {
            //validateOperationMethod(annotatedMethod, anyClass);
            Annotation annot = AnnotationUtils.findAnnotation(annotatedMethod, Operation.class);
            if (annot != null) {
                Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
                String actionName = String.valueOf(annotAttribs.get("value"));
                String actionPath = ResourceDictionary.propertyResourceKey(entityPath, actionName);
                ResourceOperation ro = inspectOperation(anyClass, annotatedMethod, HttpMethod.POST);
                embeds.put(actionPath, new Pair<ResourceOperation, Method>(ro, annotatedMethod));
            }
        }
    return embeds;
}

From source file:org.alfresco.rest.framework.core.ResourceInspector.java

/**
 * Inspects the annotated resource to understand its capabilities
 * /*from w ww  . ja  v a2 s  .  c o  m*/
 * @param resource Class
 */
@SuppressWarnings("rawtypes")
public static List<ResourceMetadata> inspect(Class resource) {
    EntityResource annot = AnnotationUtils.findAnnotation(resource, EntityResource.class);
    if (annot != null) {
        return inspectEntity(annot, resource);
    }

    RelationshipResource relAnnot = AnnotationUtils.findAnnotation(resource, RelationshipResource.class);
    if (relAnnot != null) {
        return inspectRelationship(relAnnot, resource);
    }

    throw new UnsupportedOperationException("Unable to inspect " + resource.getName());

}

From source file:org.alfresco.rest.framework.core.ResourceInspector.java

/**
 * Finds the property name that is used as the unique id.
 * @param uniqueIdMethod Method/* w  ww . j  ava 2s  .  c  om*/
 * @return String the property name that is used as the unique id.
 */
public static String findUniqueIdName(Method uniqueIdMethod) {
    Annotation annot = AnnotationUtils.findAnnotation(uniqueIdMethod, UniqueId.class);
    if (annot != null) {
        Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
        String uniqueIdName = String.valueOf(annotAttribs.get("name"));
        return uniqueIdName;
    }
    return UniqueId.UNIQUE_NAME;
}

From source file:org.alfresco.rest.framework.core.ResourceInspectorUtil.java

/**
 * Determine the expected type as the returned type of the method.
 * If the return type is a List it will return the generic element type instead of a List.
 * @param resource - resource with methods
 * @param method Method//from w  w w  .  j  a  v a 2s. c  om
 * @return Class - type of class it needs.
 */
@SuppressWarnings("rawtypes")
protected static Class determineType(Class resource, Method method) {
    Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);

    /*
    * The api is consistent that the object passed in must match the object passed out
    * however, operations are different, if the param is supplied  it doesn't have to match
    * the return type.
    * So we need special logic for operations
     */
    Annotation annot = AnnotationUtils.findAnnotation(resolvedMethod, Operation.class);
    if (annot != null) {
        return determineOperationType(resource, method);
    } else {
        Class returnType = GenericTypeResolver.resolveReturnType(resolvedMethod, resource);
        if (List.class.isAssignableFrom(returnType)) {
            return GenericCollectionTypeResolver.getCollectionReturnType(method);
        }
        return returnType;
    }
}

From source file:org.alfresco.rest.framework.core.ResourceInspectorUtil.java

/**
 * Finds methods for the given annotation
 * /*from  w  w  w . j  ava  2 s. c om*/
 * It first finds all public member methods of the class or interface represented by objClass, 
 * including those inherited from superclasses and superinterfaces.
 * 
 * It then loops through these methods searching for a single Annotation of annotationType,
 * traversing its super methods if no annotation can be found on the given method itself.
 * 
 * @param objClass - the class
 * @param annotationType - the annotation to find
 * @return - the List of Method or an empty List
 */
@SuppressWarnings("rawtypes")
public static List<Method> findMethodsByAnnotation(Class objClass, Class<? extends Annotation> annotationType) {

    List<Method> annotatedMethods = new ArrayList<Method>();
    Method[] methods = objClass.getMethods();
    for (Method method : methods) {
        Annotation annot = AnnotationUtils.findAnnotation(method, annotationType);
        if (annot != null) {
            //Just to be sure, lets make sure its not a Bridged (Generic) Method
            Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
            annotatedMethods.add(resolvedMethod);
        }
    }

    return annotatedMethods;

}

From source file:org.codehaus.groovy.grails.plugins.AbstractGrailsPluginManager.java

public void informOfClassChange(File file, @SuppressWarnings("rawtypes") Class cls) {
    if (cls != null && (cls.getName().equals(CONFIG_FILE)
            || cls.getName().equals(GrailsApplication.DATA_SOURCE_CLASS))) {
        ConfigSlurper configSlurper = ConfigurationHelper.getConfigSlurper(Environment.getCurrent().getName(),
                application);//  w w w .  j  a v a 2s  .com
        ConfigObject c;
        try {
            c = configSlurper.parse(file.toURI().toURL());
            application.getConfig().merge(c);
            application.configChanged();
            informPluginsOfConfigChange();
        } catch (Exception e) {
            // ignore
            LOG.debug("Error in changing Config", e);
        }
    } else {

        if (cls != null) {
            MetaClassRegistry registry = GroovySystem.getMetaClassRegistry();
            registry.removeMetaClass(cls);
            ExpandoMetaClass newMc = new ExpandoMetaClass(cls, true, true);
            newMc.initialize();
            registry.setMetaClass(cls, newMc);

            Enhanced en = AnnotationUtils.findAnnotation(cls, Enhanced.class);
            if (en != null) {
                Class<?>[] mixinClasses = en.mixins();
                if (mixinClasses != null) {
                    DefaultGroovyMethods.mixin(newMc, mixinClasses);
                }
            }
        }

        for (GrailsPlugin grailsPlugin : pluginList) {
            if (grailsPlugin.hasInterestInChange(file.getAbsolutePath())) {
                try {
                    if (cls == null) {
                        grailsPlugin.notifyOfEvent(GrailsPlugin.EVENT_ON_CHANGE, new FileSystemResource(file));
                    } else {
                        grailsPlugin.notifyOfEvent(GrailsPlugin.EVENT_ON_CHANGE, cls);
                    }
                    GrailsProjectWatcher.setCurrentReloadError(null);
                } catch (Exception e) {
                    LOG.error("Plugin " + grailsPlugin + " could not reload changes to file [" + file + "]: "
                            + e.getMessage(), e);
                    GrailsProjectWatcher.setCurrentReloadError(e);
                }
            }
        }
    }
}

From source file:org.finra.dm.core.StopWatchAdvice.java

/**
 * Logs the time it takes to execute the method at the join point if the class or method isn't annotated with SuppressLogging and if the log level is set to
 * info.//  w  w  w  .ja  va  2  s . co  m
 *
 * @param pjp the join point.
 *
 * @return the return value of the method at the join point.
 * @throws Throwable if any errors were encountered.
 */
@SuppressWarnings("rawtypes")
public static Object logMethodTime(ProceedingJoinPoint pjp) throws Throwable {
    // Get the target class being called.
    Class targetClass = pjp.getTarget().getClass();

    // Get the target method being called.
    MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature();
    Method targetMethod = targetMethodSignature.getMethod();
    if (targetMethod.getDeclaringClass().isInterface()) {
        // Get the underlying implementation if we are given an interface.
        targetMethod = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(),
                targetMethod.getParameterTypes());
    }

    // Only keep a stop watch if the class and method aren't suppressing logging and the log level is info.
    if ((AnnotationUtils.findAnnotation(targetClass, SuppressLogging.class) == null)
            && (AnnotationUtils.findAnnotation(targetMethod, SuppressLogging.class) == null)
            && (LOGGER.isInfoEnabled())) {
        // Start the stop watch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Proceed to the join point (i.e. call the method and let it return).
        Object returnValue = pjp.proceed();

        // Log the duration.
        LOGGER.info("Method " + targetClass.getName() + "." + targetMethodSignature.getName() + " took "
                + DmDateUtils.formatDuration(stopWatch.getTime(), true) + ".");

        // Return the method return value.
        return returnValue;
    } else {
        // Invoke the method normally.
        return pjp.proceed();
    }
}

From source file:org.finra.herd.core.StopWatchAdvice.java

/**
 * Logs the time it takes to execute the method at the join point if the class or method isn't annotated with SuppressLogging and if the log level is set to
 * info.//  w w w .ja  v  a 2  s  .  c  o  m
 *
 * @param pjp the join point.
 *
 * @return the return value of the method at the join point.
 * @throws Throwable if any errors were encountered.
 */
@SuppressWarnings("rawtypes")
public static Object logMethodTime(ProceedingJoinPoint pjp) throws Throwable {
    // Get the target class being called.
    Class targetClass = pjp.getTarget().getClass();

    // Get the target method being called.
    MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature();
    Method targetMethod = targetMethodSignature.getMethod();
    if (targetMethod.getDeclaringClass().isInterface()) {
        // Get the underlying implementation if we are given an interface.
        targetMethod = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(),
                targetMethod.getParameterTypes());
    }

    // Only keep a stop watch if the class and method aren't suppressing logging and the log level is info.
    if ((AnnotationUtils.findAnnotation(targetClass, SuppressLogging.class) == null)
            && (AnnotationUtils.findAnnotation(targetMethod, SuppressLogging.class) == null)
            && (LOGGER.isInfoEnabled())) {
        // Start the stop watch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Proceed to the join point (i.e. call the method and let it return).
        Object returnValue = pjp.proceed();

        // Log the duration.
        LOGGER.info("Method " + targetClass.getName() + "." + targetMethodSignature.getName() + " took "
                + HerdDateUtils.formatDuration(stopWatch.getTime(), true) + ".");

        // Return the method return value.
        return returnValue;
    } else {
        // Invoke the method normally.
        return pjp.proceed();
    }
}

From source file:org.finra.herd.service.advice.StopWatchAdvice.java

/**
 * Around advice that logs methods times for all service methods.
 *
 * @param pjp the proceeding join point.
 *
 * @return the return value of the method we are advising.
 * @throws Throwable if there were any problems executing the method.
 *//* w w w  .ja v  a2s .com*/
@Around("serviceMethods()")
public Object logMethodTime(ProceedingJoinPoint pjp) throws Throwable {
    // Get the target class being called.
    Class<?> targetClass = pjp.getTarget().getClass();

    // Get the target method being called.
    MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature();
    Method targetMethod = targetMethodSignature.getMethod();
    if (targetMethod.getDeclaringClass().isInterface()) {
        // Get the underlying implementation if we are given an interface.
        targetMethod = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(),
                targetMethod.getParameterTypes());
    }

    // Only keep a stop watch if the class and method aren't suppressing logging and the log level is info.
    if ((AnnotationUtils.findAnnotation(targetClass, SuppressLogging.class) == null)
            && (AnnotationUtils.findAnnotation(targetMethod, SuppressLogging.class) == null)
            && (LOGGER.isInfoEnabled())) {
        // Start the stop watch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Proceed to the join point (i.e. call the method and let it return).
        Object returnValue = pjp.proceed();

        // Log the duration.
        long durationMilliseconds = stopWatch.getTime();
        LOGGER.info(
                "javaMethod=\"{}.{}\" javaMethodDurationTimeInMilliseconds={} javaMethodDurationTimeFormatted=\"{}\"",
                targetClass.getName(), targetMethodSignature.getName(), durationMilliseconds,
                HerdDateUtils.formatDuration(durationMilliseconds));

        // Return the method return value.
        return returnValue;
    } else {
        // Invoke the method normally.
        return pjp.proceed();
    }
}