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.grails.plugins.AbstractGrailsPluginManager.java

public void informOfClassChange(File file, @SuppressWarnings("rawtypes") Class cls) {
    if (file.getName().equals(CONFIG_FILE)) {
        ConfigSlurper configSlurper = getConfigSlurper(application);
        ConfigObject c;/*  w w  w .  ja  v a 2s .  co  m*/
        try {
            c = configSlurper.parse(file.toURI().toURL());
            application.getConfig().merge(c);
            final Map flat = c.flatten();
            application.getConfig().merge(flat);
            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);
                    }
                    Environment.setCurrentReloadError(null);
                } catch (Exception e) {
                    LOG.error("Plugin " + grailsPlugin + " could not reload changes to file [" + file + "]: "
                            + e.getMessage(), e);
                    Environment.setCurrentReloadError(e);
                }
            }
        }
    }
}

From source file:org.kuali.rice.krad.data.jpa.eclipselink.KradEclipseLinkCustomizer.java

/**
 * Checks class descriptors for {@link @DisableVersioning} annotations at the class level and removes the version
 * database mapping for optimistic locking.
 *
 * @param session the current session.//from   w ww .  j a  v  a  2 s  .  c om
 */
protected void handleDisableVersioning(Session session) {
    Map<Class, ClassDescriptor> descriptors = session.getDescriptors();

    if (descriptors == null || descriptors.isEmpty()) {
        return;
    }

    for (ClassDescriptor classDescriptor : descriptors.values()) {
        if (classDescriptor != null && AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
                DisableVersioning.class) != null) {
            OptimisticLockingPolicy olPolicy = classDescriptor.getOptimisticLockingPolicy();
            if (olPolicy != null) {
                classDescriptor.setOptimisticLockingPolicy(null);
            }
        }
    }
}

From source file:org.kuali.rice.krad.data.jpa.eclipselink.KradEclipseLinkCustomizer.java

/**
 * Gets any {@link RemoveMapping}s out of the given {@link ClassDescriptor}.
 *
 * @param classDescriptor the {@link ClassDescriptor} to scan.
 * @return a list of {@link RemoveMapping}s from the given {@link ClassDescriptor}.
 *///from  w  ww .  j  av  a 2s . c om
protected List<RemoveMapping> scanForRemoveMappings(ClassDescriptor classDescriptor) {
    List<RemoveMapping> removeMappings = new ArrayList<RemoveMapping>();
    RemoveMappings removeMappingsAnnotation = AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
            RemoveMappings.class);
    if (removeMappingsAnnotation == null) {
        RemoveMapping removeMappingAnnotation = AnnotationUtils.findAnnotation(classDescriptor.getJavaClass(),
                RemoveMapping.class);
        if (removeMappingAnnotation != null) {
            removeMappings.add(removeMappingAnnotation);
        }
    } else {
        for (RemoveMapping removeMapping : removeMappingsAnnotation.value()) {
            removeMappings.add(removeMapping);
        }
    }
    return removeMappings;
}

From source file:org.kuali.rice.krad.data.jpa.eclipselink.KradEclipseLinkCustomizer.java

/**
 * Gets any {@link Sequence} from the session.
 *
 * @param session the current session.// w w w.  j a  va  2  s.c o  m
 * @return a list of {@link Sequence}s.
 */
protected List<Sequence> loadSequences(Session session) {
    Map<Class, ClassDescriptor> descriptors = session.getDescriptors();
    List<PortableSequenceGenerator> sequenceGenerators = new ArrayList<PortableSequenceGenerator>();
    for (Class<?> entityClass : descriptors.keySet()) {
        PortableSequenceGenerator sequenceGenerator = AnnotationUtils.findAnnotation(entityClass,
                PortableSequenceGenerator.class);
        if (sequenceGenerator != null) {
            sequenceGenerators.add(sequenceGenerator);
        }
        loadFieldSequences(entityClass, sequenceGenerators);
        for (Method method : entityClass.getMethods()) {
            PortableSequenceGenerator methodSequenceGenerator = method
                    .getAnnotation(PortableSequenceGenerator.class);
            if (methodSequenceGenerator != null) {
                sequenceGenerators.add(methodSequenceGenerator);
            }
        }
    }
    List<Sequence> sequences = new ArrayList<Sequence>();
    for (PortableSequenceGenerator sequenceGenerator : sequenceGenerators) {
        Sequence sequence = new MaxValueIncrementerSequenceWrapper(sequenceGenerator);
        sequences.add(sequence);
    }
    return sequences;
}

From source file:org.kuali.rice.krad.data.util.ReferenceLinker.java

/**
* Gets indexes that have been modified./*w w w.  j  a va  2 s. co  m*/
*
* <p>
*     Returns a list of cascade links in the field names that are also in the decomposed paths.
* </p>
*
* @param decomposedPaths contains field names to be used.
* @param linked
* @param wrapped used to get all field names.
*/
protected void cascadeLinkingAnnotations(DataObjectWrapper<?> wrapped, Map<String, Set<String>> decomposedPaths,
        Set<Object> linked) {
    Field[] fields = FieldUtils.getAllFields(wrapped.getWrappedClass());
    Map<String, Field> modifiedFieldMap = new HashMap<String, Field>();
    for (Field field : fields) {
        if (decomposedPaths.containsKey(field.getName())) {
            modifiedFieldMap.put(field.getName(), field);
        }
    }
    for (String modifiedFieldName : modifiedFieldMap.keySet()) {
        Field modifiedField = modifiedFieldMap.get(modifiedFieldName);
        Link link = modifiedField.getAnnotation(Link.class);
        if (link == null) {
            // check if they have an @Link on the class itself
            link = AnnotationUtils.findAnnotation(modifiedField.getType(), Link.class);
        }
        if (link != null && link.cascade()) {
            List<String> linkingPaths = assembleLinkingPaths(link);
            for (String linkingPath : linkingPaths) {
                Map<String, Set<String>> decomposedLinkingPath = decomposePropertyPaths(
                        decomposedPaths.get(modifiedFieldName), linkingPath);
                String valuePath = modifiedFieldName;
                if (StringUtils.isNotBlank(linkingPath)) {
                    valuePath = valuePath + "." + link.path();
                }
                Object linkRootObject = wrapped.getPropertyValueNullSafe(valuePath);
                linkChangesInternal(linkRootObject, decomposedLinkingPath, linked);
            }
        }
    }
}

From source file:org.kuali.rice.krad.web.bind.UifServletRequestDataBinder.java

/**
 * Return true if the target of this data binder has change tracking enabled.
 *//*from w w w  .  ja v a 2  s. com*/
private static boolean determineChangeTracking(Object target) {
    ChangeTracking changeTracking = AnnotationUtils.findAnnotation(target.getClass(), ChangeTracking.class);
    if (changeTracking != null && changeTracking.enabled()) {
        return true;
    }
    return false;
}

From source file:org.kuali.rice.krad.web.bind.UifServletRequestDataBinder.java

/**
 * Determines the root property paths relative to the given root object type against which to perform automatic
 * linking./* w w  w .  ja v a2s.  c o  m*/
 *
 * <p>This will be determined based on the presence of {@link Link} annotations on the given root object type.
 * This method is invoked recursively as it walks the class structure looking for Link annotations. It uses the
 * path
 * and scanned arguments to keep track of how deep into the structure the scanning is and to prevent infinite
 * recursion.</p>
 *
 * @param rootObjectType the root object type from which to perform the scan for auto-linking paths
 * @param path the current property path relative to the original root object type at which the scan began, if null
 * then we are scanning from the root-most object type. Each recursive call of this method will append
 * a new property to this path
 * @param scanned used to track classes that have already been scanned and prevent infinite recursion
 * @return a set of property paths that should be auto linked
 */
protected Set<String> determineRootAutoLinkingPaths(Class<?> rootObjectType, String path,
        Set<Class<?>> scanned) {
    Set<String> autoLinkingPaths = new HashSet<String>();
    if (scanned.contains(rootObjectType)) {
        return autoLinkingPaths;
    } else {
        scanned.add(rootObjectType);
    }
    Link autoLink = AnnotationUtils.findAnnotation(rootObjectType, Link.class);
    if (autoLink != null && autoLink.cascade()) {
        autoLinkingPaths.addAll(assembleAutoLinkingPaths(path, autoLink));
    } else if (autoLink == null) {
        Field[] fields = FieldUtils.getAllFields(rootObjectType);
        for (Field field : fields) {
            autoLink = field.getAnnotation(Link.class);
            if (autoLink != null) {
                if (autoLink.cascade()) {
                    String fieldPath = appendToPath(path, field.getName());
                    autoLinkingPaths.addAll(assembleAutoLinkingPaths(fieldPath, autoLink));
                }
            } else {
                autoLinkingPaths.addAll(determineRootAutoLinkingPaths(field.getType(),
                        appendToPath(path, field.getName()), scanned));
            }
        }
    }
    return autoLinkingPaths;
}

From source file:org.lexevs.cache.AbstractMethodCachingBean.java

/**
 * Clear cache.//from   w w w  .j ava  2 s  .c o  m
 * 
 * @param pjp the pjp
 * 
 * @return the object
 * 
 * @throws Throwable the throwable
 */
protected Object clearCache(T joinPoint, Method method) throws Throwable {
    try {
        logger.debug("Clearing cache.");

        if (isolateCachesOnClear) {
            this.cacheRegistry.setInThreadCacheClearingState(true);
        }

        Object target = this.getTarget(joinPoint);

        Cacheable cacheableAnnotation = AnnotationUtils.findAnnotation(target.getClass(), Cacheable.class);

        ClearCache clearCacheAnnotation = method.getAnnotation(ClearCache.class);

        Object returnObj = this.proceed(joinPoint);

        clearCache(cacheableAnnotation, clearCacheAnnotation);

        return returnObj;
    } finally {
        if (isolateCachesOnClear) {
            this.cacheRegistry.setInThreadCacheClearingState(false);
        }
    }
}

From source file:org.lexevs.cache.AbstractMethodCachingBean.java

/**
 * Cache method.// w ww  . j ava  2 s.c om
 * 
 * @param pjp the pjp
 * 
 * @return the object
 * 
 * @throws Throwable the throwable
 */
protected Object doCacheMethod(T joinPoint) throws Throwable {

    if (!CacheSessionManager.getCachingStatus()) {
        return this.proceed(joinPoint);
    }

    Method method = this.getMethod(joinPoint);

    if (method.isAnnotationPresent(CacheMethod.class) && method.isAnnotationPresent(ClearCache.class)) {
        throw new RuntimeException("Cannot both Cache method results and clear the Cache in "
                + "the same method. Please only use @CacheMethod OR @ClearCache -- not both. "
                + " This occured on method: " + method.toString());
    }

    Object target = this.getTarget(joinPoint);

    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    String key = this.getKeyFromMethod(target.getClass().getName(), method.getName(),
            this.getArguments(joinPoint), parameterAnnotations);

    Cacheable cacheableAnnotation = AnnotationUtils.findAnnotation(target.getClass(), Cacheable.class);
    CacheMethod cacheMethodAnnotation = AnnotationUtils.findAnnotation(method, CacheMethod.class);

    CacheWrapper<String, Object> cache = this.getCacheFromName(cacheableAnnotation.cacheName(), true);

    if (method.isAnnotationPresent(ClearCache.class)) {
        return this.clearCache(joinPoint, method);
    }

    Object value = cache.get(key);
    if (value != null) {
        this.logger.debug("Cache hit on: " + key);
        if (value.equals(NULL_VALUE_CACHE_PLACEHOLDER)) {
            return null;
        } else {
            return returnResult(value, cacheMethodAnnotation);
        }
    } else {
        this.logger.debug("Caching miss on: " + key);
    }

    Object result = this.proceed(joinPoint);

    if (this.isolateCachesOnClear == false
            || (this.isolateCachesOnClear == true && (this.cacheRegistry.getInThreadCacheClearingState() == null
                    || this.cacheRegistry.getInThreadCacheClearingState() == false))) {
        this.logger.debug("Thread is not in @Clear state, caching can continue for key: " + key);

        if (result != null) {
            cache.put(key, result);
        } else {
            cache.put(key, NULL_VALUE_CACHE_PLACEHOLDER);
        }
    } else {
        this.logger.debug("Thread is in @Clear state, caching skipped for key: " + key);
    }

    return returnResult(result, cacheMethodAnnotation);
}

From source file:org.lexevs.dao.database.service.error.ErrorCallbackDatabaseServiceFactory.java

/**
 * Gets the error callback database service.
 * //from   w  ww .  java 2s.com
 * @param databaseService the database service
 * @param callback the callback
 * 
 * @return the error callback database service
 */
@SuppressWarnings("unchecked")
public <T> T getErrorCallbackDatabaseService(T databaseService, ErrorCallbackListener callback) {
    ErrorHandlingService serviceAnnotation = AnnotationUtils.findAnnotation(databaseService.getClass(),
            ErrorHandlingService.class);

    if (serviceAnnotation == null) {
        throw new RuntimeException(
                "Class: " + databaseService.getClass().getName() + " is not an Error Handling Service.");
    }

    ProxyFactory pf = new ProxyFactory(databaseService);

    pf.setProxyTargetClass(true);
    ErrorCallbackInterceptor interceptor = new ErrorCallbackInterceptor(callback);

    if (serviceAnnotation.matchAllMethods()) {
        pf.addAdvice(interceptor);
    } else {
        AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(null,
                DatabaseErrorIdentifier.class);
        Advisor advisor = new DefaultPointcutAdvisor(pointcut, interceptor);
        pf.addAdvisor(advisor);

        Class<?>[] annotationClasses = serviceAnnotation.matchAnnotatedMethods();

        if (!ArrayUtils.isEmpty(annotationClasses)) {
            for (Class clazz : annotationClasses) {
                AnnotationMatchingPointcut methodAnnotationPointcuts = new AnnotationMatchingPointcut(
                        ErrorHandlingService.class, clazz);
                pf.addAdvisor(new DefaultPointcutAdvisor(methodAnnotationPointcuts, interceptor));
            }
        }
    }

    Object obj = pf.getProxy();
    return (T) obj;
}