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:org.socialsignin.spring.data.dynamodb.repository.support.FieldAndGetterReflectionEntityInformation.java

/**
 * Creates a new {@link FieldAndGetterReflectionEntityInformation} inspecting the
 * given domain class for a getter carrying the given annotation.
 * //from   w  w w  . j  ava2s  .  co m
 * @param domainClass
 *            must not be {@literal null}.
 * @param annotation
 *            must not be {@literal null}.
 */
public FieldAndGetterReflectionEntityInformation(Class<T> domainClass,
        final Class<? extends Annotation> annotation) {

    super(domainClass);
    Assert.notNull(annotation);

    ReflectionUtils.doWithMethods(domainClass, new MethodCallback() {
        public void doWith(Method method) {
            if (method.getAnnotation(annotation) != null) {
                FieldAndGetterReflectionEntityInformation.this.method = method;
                return;
            }
        }
    });

    if (method == null) {
        ReflectionUtils.doWithFields(domainClass, new FieldCallback() {
            public void doWith(Field field) {
                if (field.getAnnotation(annotation) != null) {
                    FieldAndGetterReflectionEntityInformation.this.field = field;
                    return;
                }
            }
        });
    }

    Assert.isTrue(this.method != null || this.field != null,
            String.format("No field or method annotated with %s found!", annotation.toString()));
    Assert.isTrue(this.method == null || this.field == null,
            String.format("Both field and method annotated with %s found!", annotation.toString()));

    if (method != null) {
        ReflectionUtils.makeAccessible(method);
    }
}

From source file:net.nelz.simplesm.aop.ReadThroughAssignCacheAdvice.java

@Around("getSingleAssign()")
public Object cacheSingleAssign(final ProceedingJoinPoint pjp) throws Throwable {
    // This is injected caching.  If anything goes wrong in the caching, LOG the crap outta it,
    // but do not let it surface up past the AOP injection itself.
    final String cacheKey;
    final AnnotationData annotationData;
    try {/*ww  w.  j a v a  2 s.  c o m*/
        final Method methodToCache = getMethodToCache(pjp);
        final ReadThroughAssignCache annotation = methodToCache.getAnnotation(ReadThroughAssignCache.class);
        annotationData = AnnotationDataBuilder.buildAnnotationData(annotation, ReadThroughAssignCache.class,
                methodToCache);
        cacheKey = buildCacheKey(annotationData.getAssignedKey(), annotationData);
        final Object result = cache.get(cacheKey);
        if (result != null) {
            LOG.debug("Cache hit.");
            return (result instanceof PertinentNegativeNull) ? null : result;
        }
    } catch (Throwable ex) {
        LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
        return pjp.proceed();
    }

    final Object result = pjp.proceed();

    // This is injected caching.  If anything goes wrong in the caching, LOG the crap outta it,
    // but do not let it surface up past the AOP injection itself.
    try {
        final Object submission = (result == null) ? new PertinentNegativeNull() : result;
        cache.set(cacheKey, annotationData.getExpiration(), submission);
    } catch (Throwable ex) {
        LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
    }
    return result;
}

From source file:de.anhquan.config4j.internal.ConfigHandler.java

private String findPropertyName(Method getter) {
    ConfigParam annotation = getter.getAnnotation(ConfigParam.class);
    String paramName = (annotation != null) ? prefix + annotation.PropertyName() : getter.getName();
    return paramName;
}

From source file:com.heliumv.annotation.HvModulAspect.java

@Before("anyPublicOperation() && inHeliumv() && @annotation(com.heliumv.annotation.HvModul)")
public void processAttribute(JoinPoint pjp) throws Throwable {
    //      Class clazz = pjp.getSignature().getDeclaringType() ;
    //      List<HvJudge> attributesList = new ArrayList<HvJudge>() ;
    //   /*from   w w  w .  j av a  2s . c o m*/
    //      System.out.println("In declaring clazz " + clazz.getName() + " inspecting annotations...") ;

    MethodSignature methodSig = getMethodSignatureFrom(pjp);
    Method method = getMethodFrom(pjp);
    HvModul theModul = (HvModul) method.getAnnotation(HvModul.class);
    if (theModul == null)
        return;

    //      methodSig.getMethod().getAnnotations() ;
    //      System.out.println("In method signature: " + methodSig.getMethod().getAnnotations().length + "<") ;

    System.out.println("Having the HvModul Annotation with name '" + theModul.modul() + "' <"
            + methodSig.getMethod().getName() + ":" + theModul.modul() + ">");
    if (!mandantCall.hasNamedModul(theModul.modul())) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_UNZUREICHENDE_RECHTE,
                methodSig.getMethod().getName() + ":" + theModul.modul());
    }
    System.out.println("modul allowed: '" + theModul.modul() + "'");
}

From source file:Employee.java

 @PostConstruct
public void jndiInject(InvocationContext invocation) {
   Object target = invocation.getTarget();
   Field[] fields = target.getClass().getDeclaredFields();
   Method[] methods = target.getClass().getDeclaredMethods();

   // find all @JndiInjected fields methods and set them
   try {//from www . ja  v a 2  s .  co  m
      InitialContext ctx = new InitialContext();
      for (Method method : methods) {
         JndiInjected inject = method.getAnnotation(JndiInjected.class);
         if (inject != null) {
            Object obj = ctx.lookup(inject.value());
            method.setAccessible(true);
            method.invoke(target, obj);
         }
      }
      for (Field field : fields) {
         JndiInjected inject = field.getAnnotation(JndiInjected.class);
         if (inject != null) {
            Object obj = ctx.lookup(inject.value());
            field.setAccessible(true);
            field.set(target, obj);
         }
      }
      invocation.proceed();
   } catch (Exception ex) {
      throw new EJBException("Failed to execute @JndiInjected", ex);
   }
}

From source file:com.predic8.membrane.core.interceptor.rest.RESTInterceptor.java

private Outcome dispatchRequest(Exchange exc) throws Exception {
    String path = router.getUriFactory().create(exc.getDestinations().get(0)).getPath();
    for (Method m : getClass().getMethods()) {
        Mapping a = m.getAnnotation(Mapping.class);
        if (a == null)
            continue;
        Matcher matcher = Pattern.compile(a.value()).matcher(path);
        if (matcher.matches()) {
            Object[] parameters;/*  w  w w.  j  ava 2  s .  co  m*/
            switch (m.getParameterTypes().length) {
            case 2:
                parameters = new Object[] {
                        new QueryParameter(URLParamUtil.getParams(router.getUriFactory(), exc), matcher),
                        getRelativeRootPath(path) };
                break;
            case 3:
                parameters = new Object[] {
                        new QueryParameter(URLParamUtil.getParams(router.getUriFactory(), exc), matcher),
                        getRelativeRootPath(path), exc };
                break;
            default:
                throw new InvalidParameterException("@Mapping is supposed to annotate a 2-parameter method.");
            }
            exc.setResponse((Response) m.invoke(this, parameters));
            return Outcome.RETURN;
        }
    }
    return Outcome.CONTINUE;
}

From source file:corner.cache.services.impl.CacheableDefinitionParserImpl.java

/**
 * @see corner.cache.services.CacheableDefinitionParser#parseAsKey(org.apache.tapestry5.ioc.Invocation, java.lang.reflect.Method, corner.cache.services.CacheManager)
 *//*ww w  .j a  v  a2s .c  o  m*/
@Override
public String parseAsKey(Invocation invocation, Method method) {
    Cacheable cacheable = method.getAnnotation(Cacheable.class);
    if (cacheable == null) {
        return null;
    }
    Definition define = null;
    //if (define == null) { // ?
    Builder defineBuilder = CacheableDefine.Definition.newBuilder();
    Annotation[][] parametersAnnotations = method.getParameterAnnotations();
    for (int i = 0; i < parametersAnnotations.length; i++) {
        Annotation[] pa = parametersAnnotations[i];
        for (Annotation a : pa) {
            if (a instanceof CacheKeyParameter) {
                defineBuilder.addParameterIndex(i);
            }
        }
    }
    define = defineBuilder.build();

    // ?
    List<String> keyParameter = new ArrayList<String>();
    Object pObj;
    Class pType;
    for (int i = 0; i < define.getParameterIndexCount(); i++) {
        int pIndex = define.getParameterIndex(i);
        pObj = invocation.getParameter(pIndex);
        pType = null;
        if (pObj != null) {
            pType = entityService.getEntityClass(pObj);
        }
        if (pType == null) {
            pType = method.getParameterTypes()[pIndex];
        }
        ValueEncoder encoder = valueEncoderSource.getValueEncoder(pType);
        keyParameter.add(encoder.toClient(pObj));
    }
    //key
    String key = null;
    String keyFormat = cacheable.keyFormat();
    logger.debug("key parameter:{}", keyParameter);
    if (!StringUtils.hasText(keyFormat)) {
        key = DigestUtils.shaHex(method.toString() + keyParameter.toString());
    } else {
        key = String.format(keyFormat, keyParameter.toArray(new Object[0]));
    }

    CacheStrategy strategy = this.source.findStrategy(cacheable.strategy());
    CacheNsParameter[] nses = cacheable.namespaces();
    if (strategy == null) {
        throw new RuntimeException("fail to find cache strategy instance!");
    }
    return strategy.appendNamespace(cacheManager, cacheable.clazz(), nses, key, keyParameter.toArray());
}

From source file:net.firejack.platform.core.validation.NotNullProcessor.java

@Override
public List<Constraint> generate(Method readMethod, String property, Map<String, String> params) {
    List<Constraint> constraints = null;
    Annotation annotation = readMethod.getAnnotation(NotNull.class);
    if (annotation != null) {
        NotNull notNull = (NotNull) annotation;
        Constraint constraint = new Constraint(notNull.annotationType().getSimpleName());
        String errorMessage = MessageResolver.messageFormatting(notNull.msgKey(), Locale.ENGLISH, property); //TODO need to set real locale
        constraint.setErrorMessage(errorMessage);
        constraints = new ArrayList<Constraint>();
        constraints.add(constraint);/*from   w  ww .  j  a v a  2  s.  c  o  m*/
    }
    return constraints;
}

From source file:org.craftercms.commons.security.permissions.annotations.HasPermissionAnnotationHandler.java

protected HasPermission getHasPermissionAnnotation(Method method, ProceedingJoinPoint pjp) {
    HasPermission hasPermission = method.getAnnotation(HasPermission.class);

    if (hasPermission == null) {
        Class<?> targetClass = pjp.getTarget().getClass();
        hasPermission = targetClass.getAnnotation(HasPermission.class);
    }/*  www  .  j  a  v a2s  .  co  m*/

    return hasPermission;
}

From source file:com.bstek.dorado.common.service.ExposedServiceAnnotationBeanPostProcessor.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType,
        String beanName) {// w  ww .j  a  v a  2s.  co  m
    boolean defaultExposed = (beanType.getAnnotation(Expose.class) != null)
            && (beanType.getAnnotation(Unexpose.class) == null);

    for (Method method : beanType.getMethods()) {
        Expose annotation = method.getAnnotation(Expose.class);
        boolean exposed = defaultExposed
                || ((annotation != null) && (beanType.getAnnotation(Unexpose.class) == null));
        if (!exposed) {
            continue;
        }
        pendingDataObjects.add(new PendingObject(annotation, beanName, method.getName()));
    }
}