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.zht.framework.interceptors.TokenInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RepeatToken annotation = method.getAnnotation(RepeatToken.class);
        if (annotation != null) {
            HttpSession session = request.getSession(false);
            if (session == null) {
                return true;
            }/*from   w ww.  j  a va2 s.c  o m*/
            String seesionId = session.getId();
            String uri = request.getRequestURI();

            Boolean isPosted = (Boolean) session.getAttribute("_Token" + seesionId + uri);
            if (isPosted == null || isPosted == false) {
                session.setAttribute("_Token" + seesionId + uri, true);
                return true;
            } else {
                //??
                return false;
            }
        }
        return true;
    } else {
        return super.preHandle(request, response, handler);
    }

}

From source file:org.callimachusproject.rewrite.MissingAdviceFactory.java

private StatusLine getStatusLine(Method method) {
    if (method.isAnnotationPresent(disabled.class)) {
        String[] phrase = method.getAnnotation(disabled.class).value();
        if (phrase.length < 1) {
            phrase = new String[] { "Disabled" };
        }//from w  w  w.j av  a  2  s  .  co m
        return new BasicStatusLine(HttpVersion.HTTP_1_1, 404, phrase[0]);
    }
    if (method.isAnnotationPresent(deleted.class)) {
        String[] phrase = method.getAnnotation(deleted.class).value();
        if (phrase.length < 1) {
            phrase = new String[] { "Deleted" };
        }
        return new BasicStatusLine(HttpVersion.HTTP_1_1, 410, phrase[0]);
    }
    throw new AssertionError();
}

From source file:com.newtranx.util.mysql.fabric.SpringMybatisSetShardKeyAspect.java

@Around("@annotation(com.newtranx.util.mysql.fabric.WithShardKey) || @within(com.newtranx.util.mysql.fabric.WithShardKey)")
public Object setShardKey(ProceedingJoinPoint pjp) throws Throwable {
    Method method = AspectJUtils.getMethod(pjp);
    String key = null;//from w  w w. j  av  a 2s  .co m
    boolean force = method.getAnnotation(WithShardKey.class).force();
    int i = 0;
    for (Parameter p : method.getParameters()) {
        ShardKey a = p.getAnnotation(ShardKey.class);
        if (a != null) {
            if (key != null)
                throw new RuntimeException("found multiple shardkey");
            Object obj = pjp.getArgs()[i];
            if (StringUtils.isEmpty(a.property()))
                key = obj.toString();
            else {
                BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj);
                key = bw.getPropertyValue(a.property()).toString();
            }
        }
        i++;
    }
    if (key == null)
        throw new RuntimeException("can not find shardkey");
    fabricShardKey.set(key, force);
    return pjp.proceed();
}

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

@AfterReturning(pointcut = "updateSingle()", returning = "retVal")
public Object cacheUpdateSingle(final JoinPoint jp, final Object retVal) throws Throwable {
    // For Update*Cache, an AfterReturning aspect is fine. We will only apply our caching
    // after the underlying method completes successfully, and we will have the same
    // access to the method params.
    try {/*from  w w  w. j a v  a 2  s  . c  o  m*/
        final Method methodToCache = getMethodToCache(jp);
        final UpdateSingleCache annotation = methodToCache.getAnnotation(UpdateSingleCache.class);
        final AnnotationData annotationData = AnnotationDataBuilder.buildAnnotationData(annotation,
                UpdateSingleCache.class, methodToCache);
        final String objectId = getObjectId(annotationData.getKeyIndex(), retVal, jp, methodToCache);
        final String cacheKey = buildCacheKey(objectId, annotationData);
        final Object dataObject = annotationData.getDataIndex() == -1 ? retVal
                : getIndexObject(annotationData.getDataIndex(), jp, methodToCache);
        final Object submission = (dataObject == null) ? new PertinentNegativeNull() : dataObject;
        cache.set(cacheKey, annotationData.getExpiration(), submission);
    } catch (Exception ex) {
        LOG.warn("Updating caching via " + jp.toShortString() + " aborted due to an error.", ex);
    }
    return retVal;
}

From source file:jp.gr.java_conf.ka_ka_xyz.processor.AnnotationProcessor.java

private void registerMethodAnnotation(Method method, Class<?> clazz) {
    Column column = method.getAnnotation(Column.class);
    String fieldName = method.getName().substring(3);
    fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
    if (column != null) {
        String colName = column.name();
        fieldColMap.put(fieldName, colName);
    }/*  w ww .  jav  a 2  s .co  m*/
}

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

@Around("invalidateAssign()")
public Object cacheInvalidateAssign(final ProceedingJoinPoint pjp) throws Throwable {
    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 {/* ww  w.  java2 s. com*/
        final Method methodToCache = getMethodToCache(pjp);
        final InvalidateAssignCache annotation = methodToCache.getAnnotation(InvalidateAssignCache.class);
        final AnnotationData annotationData = AnnotationDataBuilder.buildAnnotationData(annotation,
                InvalidateAssignCache.class, methodToCache);

        final String cacheKey = buildCacheKey(annotationData.getAssignedKey(), annotationData);
        if (cacheKey == null || cacheKey.trim().length() == 0) {
            throw new InvalidParameterException("Unable to find a cache key");
        }
        cache.delete(cacheKey);
    } catch (Throwable ex) {
        LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
    }
    return result;
}

From source file:com.linkedin.pinot.common.restlet.PinotRestletApplication.java

protected void attachRoutesForClass(Router router, Class<? extends ServerResource> clazz) {
    TreeSet<String> pathsOrderedByLength = new TreeSet<String>(
            ComparatorUtils.chainedComparator(new Comparator<String>() {

                @Override//from  w  w w.j  a  v  a  2  s .c  o  m
                public int compare(String left, String right) {
                    int leftLength = left.length();
                    int rightLength = right.length();
                    return leftLength < rightLength ? -1 : (leftLength == rightLength ? 0 : 1);
                }
            }, ComparatorUtils.NATURAL_COMPARATOR));

    for (Method method : clazz.getDeclaredMethods()) {
        Annotation annotationInstance = method.getAnnotation(Paths.class);
        if (annotationInstance != null) {
            pathsOrderedByLength.addAll(Arrays.asList(((Paths) annotationInstance).value()));
        }
    }

    for (String routePath : pathsOrderedByLength) {
        LOGGER.info("Attaching route {} -> {}", routePath, clazz.getSimpleName());
        attachRoute(router, routePath, clazz);
    }
}

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

@Around("getSingle()")
public Object cacheGetSingle(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 ReadThroughSingleCache annotation;
    try {//  w w w  .  ja va 2  s.co  m
        final Method methodToCache = getMethodToCache(pjp);
        annotation = methodToCache.getAnnotation(ReadThroughSingleCache.class);
        final AnnotationData annotationData = AnnotationDataBuilder.buildAnnotationData(annotation,
                ReadThroughSingleCache.class, methodToCache);
        final String objectId = getObjectId(annotationData.getKeyIndex(), pjp, methodToCache);
        cacheKey = buildCacheKey(objectId, 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, annotation.expiration(), submission);
    } catch (Throwable ex) {
        LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
    }
    return result;
}

From source file:com.m3.methodcache.interceptor.AbstractCacheResultInterceptor.java

/**
 * Returns {@link CacheResult} annotation if exists
 *
 * @param invocation method invocation/* w w w.  j  a  v  a 2  s  . co m*/
 * @return annotation instance
 */
protected CacheResult getCacheResultAnnotation(MethodInvocation invocation) {
    Method invokedMethod = invocation.getMethod();
    return invokedMethod.getAnnotation(CacheResult.class);
}

From source file:com.fortuityframework.spring.broker.SpringEventListenerLocator.java

private void registerMethodAsListener(ApplicationContext context, String beanDefinitionName, Method m) {
    OnFortuityEvent eventRef = m.getAnnotation(OnFortuityEvent.class);
    if (eventRef != null) {
        Class<?>[] paramTypes = m.getParameterTypes();
        if (paramTypes.length == 1 && EventContext.class.isAssignableFrom(paramTypes[0])) {
            Class<? extends Event<?>>[] events = getEvents(eventRef);

            for (Class<? extends Event<?>> eventClass : events) {
                registerListener(eventClass, beanDefinitionName, m, context);
            }//  w  w  w . ja  va 2 s.c o m
        }
    }
}