Example usage for java.lang.reflect Method getAnnotation

List of usage examples for java.lang.reflect Method getAnnotation

Introduction

In this page you can find the example usage for java.lang.reflect Method getAnnotation.

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:com.rockagen.gnext.service.spring.aspect.OpLogAspect.java

/**
 * Get {@link com.rockagen.gnext.annotation.Plog} value
 * //from   w w w  . j a va 2s .  c  o  m
 * @param method method
 * @return {@link com.rockagen.gnext.annotation.Plog} value
 */
private String getPlogValue(Method method) {
    if (method.isAnnotationPresent(Plog.class)) {
        Plog plog = method.getAnnotation(Plog.class);
        return plog.value();
    } else {
        return method.getDeclaringClass() + "#" + method.getName();
    }
}

From source file:org.spring.data.gemfire.config.CacheableAnnotationDynamicRegionCreationBeanPostProcessor.java

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if (isProcessableBean(bean)) {
        processCacheableAnnotation(bean.getClass().getAnnotation(Cacheable.class));

        for (Method method : bean.getClass().getMethods()) {
            processCacheableAnnotation(method.getAnnotation(Cacheable.class));
        }//from  w  w w .j  av  a  2 s.c o  m
    }

    return bean;
}

From source file:org.ext4spring.parameter.DefaultParameterResolver.java

protected <T extends Annotation> T findAnnotation(Class<T> annotationType, Method method, Operation operation,
        String paramName) {/*w  w  w. java 2 s. co m*/
    T annotation = method.getAnnotation(annotationType);
    if (annotation == null) {
        //not found on the specified method. for setters it looks for getter annotations
        if (Operation.SET.equals(operation)) {
            for (Method currMethod : method.getDeclaringClass().getMethods()) {
                if (currMethod.getName().endsWith(paramName)) {
                    if (currMethod.getAnnotation(annotationType) != null) {
                        return currMethod.getAnnotation(annotationType);
                    }
                }
            }
        }
    }
    return annotation;
}

From source file:com.baomidou.kisso.web.interceptor.SSOPermissionInterceptor.java

/**
 * <p>/*ww w.j av a2 s . c  o m*/
 * ????? 1?? 2??
 * </p>
 * @param request
 * @param handler
 * @param token
 * @return
 */
protected boolean isVerification(HttpServletRequest request, Object handler, SSOToken token) {
    /*
     * URL ???
     */
    if (SSOConfig.getInstance().isPermissionUri()) {
        String uri = request.getRequestURI();
        if (uri == null || authorization.isPermitted(token, uri)) {
            return true;
        }
    }
    /*
     * ???
     */
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    Permission pm = method.getAnnotation(Permission.class);
    if (pm != null) {
        if (pm.action() == Action.Skip) {
            /**
             * 
             */
            return true;
        } else if (!"".equals(pm.value()) && authorization.isPermitted(token, pm.value())) {
            /**
             * ???
             */
            return true;
        }
    }
    /*
     * ?
     */
    return false;
}

From source file:com.kixeye.chassis.transport.websocket.WebSocketMessageMappingRegistry.java

@PostConstruct
public void registerWebSocketActions() throws BeansException {
    String[] controllerBeanNames = beanFactory.getBeanNamesForAnnotation(WebSocketController.class);

    if (controllerBeanNames != null && controllerBeanNames.length > 0) {
        try {//w  w  w .j a v  a  2  s .c om
            for (String beanName : controllerBeanNames) {
                BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);

                Class<?> beanClass = Class.forName(beanDef.getBeanClassName());

                for (Method method : beanClass.getMethods()) {
                    ActionMapping mapping = method.getAnnotation(ActionMapping.class);

                    if (mapping != null) {
                        if (mapping.value() != null && mapping.value().length > 0) {
                            Map<String, String> requirements = new HashMap<>();

                            if (mapping.propertyRequirements() != null) {
                                for (ActionPropertyRequirement requirement : mapping.propertyRequirements()) {
                                    requirements.put(requirement.name(), requirement.value());
                                }
                            }

                            for (String action : mapping.value()) {
                                logger.info("Registering destination [{}] with handler [{}].", action,
                                        method.toString());

                                Map<String, WebSocketActionArgumentResolver> argumentResolverBeans = beanFactory
                                        .getBeansOfType(WebSocketActionArgumentResolver.class);

                                if (argumentResolverBeans != null && !argumentResolverBeans.isEmpty()) {
                                    logger.info(
                                            "Registering WebSocketActionArgumentResolver beans {} with action {}",
                                            Joiner.on(",").join(argumentResolverBeans.keySet(), action));
                                }

                                actions.put(action, new WebSocketAction(method, requirements,
                                        argumentResolverBeans == null ? null
                                                : argumentResolverBeans.values().toArray(
                                                        new WebSocketActionArgumentResolver[argumentResolverBeans
                                                                .size()])));
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new FatalBeanException("Unable to configure bean", e);
        }
    } else {
        logger.warn("No WebSocketController beans defined.");
    }
}

From source file:com.autentia.tnt.tracking.annotation.ChangesHistoryAspect.java

/**
 * @return Devuelve un properties con los atributos de la anotacin
 * @throws NoSuchMethodException/*from  w  w w  .  j a  v a 2s .c  o  m*/
 * @throws SecurityException
 * @throws ClassNotFoundException
 */
private Properties getAnnotationProperties(JoinPoint call) throws SecurityException, NoSuchMethodException {
    Properties properties = new Properties();
    Method metodo = this.getCallMethod(call);

    ChangesHistory anotacion = metodo.getAnnotation(ChangesHistory.class);
    properties.put(FIELD_KEY, anotacion.fieldName());
    properties.put(METHOD_KEY, anotacion.method());

    return properties;
}

From source file:com.openmeap.web.form.ParameterMapBuilder.java

public void toParameters(Map<String, Object> map, Object obj, String prefix)
        throws ParameterMapBuilderException {

    for (Method method : obj.getClass().getMethods()) {
        Parameter param = method.getAnnotation(Parameter.class);
        if (param != null) {
            String paramName = prefix + formNameForMethod(param, method);
            Validation validation = param.validation();
            try {
                Object value = method.invoke(obj);
                if (value != null && !PropertyUtils.isSimpleType(value.getClass())) {
                    throw new ParameterMapBuilderException("Expecting a simple type");
                }/*from w ww  . j  ava  2  s.  c  om*/
                if (value == null && noNulls) {
                    continue;
                }
                map.put(paramName, mapValuesAsStrings ? value.toString() : value);
                if (validation.verify()) {
                    map.put(paramName + validation.verifySuffix(),
                            mapValuesAsStrings ? value.toString() : value);
                }
            } catch (Exception e) {
                throw new ParameterMapBuilderException(e);
            }
        }
    }
}

From source file:edu.umn.msi.tropix.persistence.aop.SecurityAspect.java

@Before(value = "execution(* edu.umn.msi.tropix.persistence.service.*+.*(..))")
public void doAccessCheck(final JoinPoint joinPoint) {
    LOG.trace("Verifying persistence layer access to " + joinPoint.getSignature().toLongString());
    final Method method = AopUtils.getMethod(joinPoint);
    if (method.getAnnotation(PersistenceMethod.class) == null) {
        return;//from  ww w  .j av  a  2s .c o  m
    }
    final Annotation[][] annotations = method.getParameterAnnotations();
    String userId = null;
    for (int i = 0; i < annotations.length; i++) {
        final UserId userIdAnnotation = getAnnnotation(UserId.class, annotations[i]);
        if (userIdAnnotation != null) {
            final Object arg = joinPoint.getArgs()[i];
            userId = (String) arg;
            break;
        }
    }
    Preconditions.checkNotNull(userId, "No parameter ananotations of type UserId found, but one is required.");
    @SuppressWarnings("unchecked")
    final Collection<Class<? extends Annotation>> securityAnnotations = Arrays.asList(Owns.class, Reads.class,
            Modifies.class, MemberOf.class);
    for (int i = 0; i < annotations.length; i++) {
        for (final Annotation annotation : annotations[i]) {
            if (securityAnnotations.contains(annotation.annotationType())) {
                verify(userId, joinPoint.getArgs()[i], annotations[i],
                        joinPoint.getSignature() + "[" + i + "]");
            }
        }
    }

}

From source file:py.una.pol.karaku.log.LogPostProcessor.java

/**
 * Revisa todos los mtodos o campos que tengan la anotacin {@link Log} y
 * le asigna el valor el Log del bean en cuestin.
 * // www  .j  a  v a  2s  . c  o  m
 * <br />
 * 
 * {@inheritDoc}
 * 
 * @param bean
 *            bean a procesar
 * @param beanName
 *            nombre del bean
 * @return el mismo bean
 * @throws BeansException
 *             nunca
 */
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) {

    ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {

        @Override
        public void doWith(Field field) throws IllegalAccessException {

            if (!Modifier.isFinal(field.getModifiers())) {
                field.setAccessible(true);
                Log log = field.getAnnotation(Log.class);
                field.set(bean, getLogger(bean, log));
            }
        }

    }, new FieldFilter() {

        @Override
        public boolean matches(Field field) {

            return field.getAnnotation(Log.class) != null;
        }
    });

    ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalAccessException {

            Log log = method.getAnnotation(Log.class);
            try {
                method.invoke(bean, getLogger(bean, log));
            } catch (InvocationTargetException e) {
                LOGGER.warn("Error extracting proxy object from {}", bean.getClass().getName(), e);
            }
        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {

            return method.getAnnotation(Log.class) != null;

        }
    });

    return bean;

}

From source file:cn.com.esrichina.gcloud.commons.LicenseLevelCheckAspect.java

@Around("execution(* cn.com.esrichina.gcloud.*.web.resources.*.*(..))")
public Object doCheck(ProceedingJoinPoint pjp) throws Throwable {
    Object target = pjp.getTarget();
    String methodName = pjp.getSignature().getName();
    Class[] parameterTypes = ((MethodSignature) pjp.getSignature()).getMethod().getParameterTypes();
    Method method = target.getClass().getMethod(methodName, parameterTypes);
    LicenseLevelCheck licenseLevelCheck = null;
    if (method != null) {
        licenseLevelCheck = method.getAnnotation(LicenseLevelCheck.class);
    }//  w ww .  jav  a 2  s.c  o  m

    if (licenseLevelCheck == null) {
        try {
            return pjp.proceed();
        } catch (Exception e) {
            throw e;
        }
    } else {
        String needLevel = licenseLevelCheck.level();
        GCloudLicense license = LicenseContext.getInstance().getLicense();
        // if (license == null || license.getLicenseLevel() == null) {
        // throw new
        // RuntimeException(Messages.getMessage("license_not_load"));
        // }

        if (needLevel.equals(GCloudLicense.LEVEL_ADVANCED) && !license.isAdvanced()) {
            throw new RuntimeException(Messages.getMessage("license_level_adv_limit"));
        } else if (needLevel.equals(GCloudLicense.LEVEL_STANDARD) && license.isBasic()) {
            throw new RuntimeException(Messages.getMessage("license_level_adv_limit"));
        }
        try {
            return pjp.proceed();
        } catch (Exception e) {
            throw e;
        }
    }
}