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:candr.yoclip.option.OptionPropertiesSetterTest.java

@Test(expected = IllegalArgumentException.class)
public void initWithBadKeyArg() throws NoSuchMethodException {
    final Method setter = TestCase.class.getDeclaredMethod("setWithBadKeyArg", Integer.class, String.class);
    final OptionProperties optionProperties = setter.getAnnotation(OptionProperties.class);
    new OptionPropertiesSetter<TestCase>(optionProperties, setter);
}

From source file:org.flite.cach3.aop.InvalidateSingleCacheAdvice.java

private void doInvalidate(final JoinPoint jp, final Object retVal) throws Throwable {
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return;/* w w  w .  java 2s  . co  m*/
    }

    final MemcachedClientIF cache = getMemcachedClient();
    final Method methodToCache = getMethodToCache(jp);
    List<InvalidateSingleCache> lAnnotations;

    if (methodToCache.getAnnotation(InvalidateSingleCache.class) != null) {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(InvalidateSingleCache.class));
    } else {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(InvalidateSingleCaches.class).value());
    }

    for (int i = 0; i < lAnnotations.size(); i++) {
        // 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 AnnotationInfo info = getAnnotationInfo(lAnnotations.get(i), methodToCache.getName());
            final String baseKey = getBaseKey(info.getAsString(AType.KEY_TEMPLATE),
                    info.getAsInteger(AType.KEY_INDEX, null), retVal, jp.getArgs(), methodToCache.toString(),
                    factory, methodStore);
            final String cacheKey = buildCacheKey(baseKey, info.getAsString(AType.NAMESPACE),
                    info.getAsString(AType.KEY_PREFIX));

            LOG.debug("Invalidating cache for key " + cacheKey);
            cache.delete(cacheKey);

            // Notify the observers that a cache interaction happened.
            final List<InvalidateSingleCacheListener> listeners = getPertinentListeners(
                    InvalidateSingleCacheListener.class, info.getAsString(AType.NAMESPACE));
            if (listeners != null && !listeners.isEmpty()) {
                for (final InvalidateSingleCacheListener listener : listeners) {
                    try {
                        listener.triggeredInvalidateSingleCache(info.getAsString(AType.NAMESPACE),
                                info.getAsString(AType.KEY_PREFIX, null), baseKey, retVal, jp.getArgs());
                    } catch (Exception ex) {
                        LOG.warn("Problem when triggering a listener.", ex);
                    }
                }
            }
        } catch (Throwable ex) {
            if (LOG.isDebugEnabled()) {
                LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error.", ex);
            } else {
                LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error: " + ex.getMessage());
            }
        }
    }
}

From source file:candr.yoclip.option.OptionPropertiesSetterTest.java

@Test
public void testSetOption() throws NoSuchMethodException {
    final Method setter = TestCase.class.getDeclaredMethod("setProperty", String.class, String.class);
    final OptionProperties optionProperties = setter.getAnnotation(OptionProperties.class);
    final OptionPropertiesSetter<TestCase> test = new OptionPropertiesSetter<TestCase>(optionProperties,
            setter);//  www. ja  v a2  s.c  o m
    final TestCase bean = mock(TestCase.class);

    final String key = "key";
    final String value = "value";
    test.setOption(bean, key + OptionProperties.KEY_VALUE_SEPARATOR + value);
    verify(bean).setProperty(key, value);
}

From source file:com.netflix.hystrix.contrib.javanica.command.HystrixCommandBuilderFactory.java

private CommandAction createFallbackAction(MetaHolder metaHolder) {

    FallbackMethod fallbackMethod = MethodProvider.getInstance().getFallbackMethod(
            metaHolder.getObj().getClass(), metaHolder.getMethod(), metaHolder.isExtendedFallback());
    fallbackMethod.validateReturnType(metaHolder.getMethod());
    CommandAction fallbackAction = null;
    if (fallbackMethod.isPresent()) {

        Method fMethod = fallbackMethod.getMethod();
        if (fallbackMethod.isCommand()) {
            fMethod.setAccessible(true);
            HystrixCommand hystrixCommand = fMethod.getAnnotation(HystrixCommand.class);
            MetaHolder fmMetaHolder = MetaHolder.builder().obj(metaHolder.getObj()).method(fMethod)
                    .ajcMethod(getAjcMethod(metaHolder.getObj(), fMethod)).args(metaHolder.getArgs())
                    .fallback(true).defaultCollapserKey(metaHolder.getDefaultCollapserKey())
                    .fallbackMethod(fMethod).extendedFallback(fallbackMethod.isExtended())
                    .fallbackExecutionType(fallbackMethod.getExecutionType())
                    .extendedParentFallback(metaHolder.isExtendedFallback())
                    .observable(ExecutionType.OBSERVABLE == fallbackMethod.getExecutionType())
                    .defaultCommandKey(fMethod.getName()).defaultGroupKey(metaHolder.getDefaultGroupKey())
                    .defaultThreadPoolKey(metaHolder.getDefaultThreadPoolKey())
                    .defaultProperties(metaHolder.getDefaultProperties().orNull())
                    .hystrixCollapser(metaHolder.getHystrixCollapser())
                    .observableExecutionMode(hystrixCommand.observableExecutionMode())
                    .hystrixCommand(hystrixCommand).build();
            fallbackAction = new LazyCommandExecutionAction(fmMetaHolder);
        } else {/*from   w  w  w .  j  a va2s .co m*/
            MetaHolder fmMetaHolder = MetaHolder.builder().obj(metaHolder.getObj()).method(fMethod)
                    .fallbackExecutionType(ExecutionType.SYNCHRONOUS)
                    .extendedFallback(fallbackMethod.isExtended())
                    .extendedParentFallback(metaHolder.isExtendedFallback()).ajcMethod(null) // if fallback method isn't annotated with command annotation then we don't need to get ajc method for this
                    .args(metaHolder.getArgs()).build();

            fallbackAction = new MethodExecutionAction(fmMetaHolder.getObj(), fMethod, fmMetaHolder.getArgs(),
                    fmMetaHolder);
        }

    }
    return fallbackAction;
}

From source file:candr.yoclip.option.OptionPropertiesSetterTest.java

@Test(expected = IllegalArgumentException.class)
public void initWithBadValueArg() throws NoSuchMethodException {
    final Method setter = TestCase.class.getDeclaredMethod("setWithBadValueArg", String.class, Integer.class);
    final OptionProperties optionProperties = setter.getAnnotation(OptionProperties.class);
    new OptionPropertiesSetter<TestCase>(optionProperties, setter);
}

From source file:com.ryantenney.metrics.spring.CachedGaugeAnnotationBeanPostProcessor.java

@Override
protected void withMethod(final Object bean, String beanName, Class<?> targetClass, final Method method) {
    if (method.getParameterTypes().length > 0) {
        throw new IllegalStateException(
                "Method " + method.getName() + " is annotated with @CachedGauge but requires parameters.");
    }// ww w  .jav a2  s.  c o m

    final CachedGauge annotation = method.getAnnotation(CachedGauge.class);
    final String metricName = Util.forCachedGauge(targetClass, method, annotation);

    metrics.register(metricName,
            new com.codahale.metrics.CachedGauge<Object>(annotation.timeout(), annotation.timeoutUnit()) {
                @Override
                protected Object loadValue() {
                    return ReflectionUtils.invokeMethod(method, bean);
                }
            });

    LOG.debug("Created cached gauge {} for method {}.{}", metricName, targetClass.getCanonicalName(),
            method.getName());
}

From source file:com.jayway.jaxrs.hateoas.DefaultHateoasContext.java

private String getPath(String rootPath, Method method) {
    if (method.isAnnotationPresent(Path.class)) {
        Path pathAnnotation = method.getAnnotation(Path.class);
        return rootPath + pathAnnotation.value();
    }//from  ww  w.j  a  v a  2s. co m

    return rootPath.isEmpty() ? "/" : rootPath;
}

From source file:mp.platform.cyclone.webservices.AuthInterceptor.java

/**
 * Resolve the possible operations for the current request
 *//*from w w  w . j ava  2s .  c  o m*/
private ServiceOperation[] resolveOperations(final SoapMessage message) {
    final MessageInfo messageInfo = message.get(MessageInfo.class);
    final OperationInfo operation = messageInfo.getOperation();
    final QName operationQName = operation.getName();
    // Try to find the operations in the cache
    ServiceOperation[] operations = cachedOperations.get(operationQName);
    if (operations == null) {
        // Cache miss... find the interface method
        final String operationName = operationQName.getLocalPart();
        final String serviceName = operation.getInterface().getService().getName().getLocalPart();
        final Class<?> serviceInterface = CyclosWebServicesClientFactory.serviceInterfaceForName(serviceName);
        for (final Method m : serviceInterface.getMethods()) {
            if (m.getName().equals(operationName)) {
                final Permission permission = m.getAnnotation(Permission.class);
                operations = permission == null ? new ServiceOperation[0] : permission.value();
                break;
            }
        }
        // Store the operations on the cache for further access
        cachedOperations.put(operationQName, operations);
    }
    return operations;
}

From source file:com.katsu.springframework.web.servlet.menu.MenuServiceImpl.java

private void createMenuEntry(Method m, Object bean) {
    //Group// ww w  .j  ava2s  .  c o  m
    MenuEntry me = m.getAnnotation(MenuEntry.class);
    String[] groups = SEPARATOR.split(me.menuGroup());
    MenuEntryBean group = this.getCreateGroup(groups, 0, this.getMenus(), me);
    //Entry
    RequestMapping rm = m.getAnnotation(RequestMapping.class);
    RequestMapping rc = AnnotationUtils.findAnnotation(bean.getClass(), RequestMapping.class);
    MenuEntryBean aux = new MenuEntryBean();
    aux.setIcon(me.icon());
    //FIXME Add ContextPath                
    aux.setUrl((rc != null && rc.value().length > 0
            ? (rc.value()[0].endsWith("/") ? rc.value()[0] : rc.value()[0] + "/")
            : "/")
            + (rm.value().length > 0
                    ? (rm.value()[0].startsWith("/") ? rm.value()[0].substring(1) : rm.value()[0])
                    : ""));
    aux.setOrder(me.order());
    aux.setText(me.text());
    aux.setDevices(Arrays.asList(me.devices()));
    RolesAllowed sec = m.getAnnotation(RolesAllowed.class);
    if (sec != null) {
        aux.setRoles(Arrays.asList(sec.value()));
    }
    group.addChild(aux);
}

From source file:org.flite.cach3.aop.ReadThroughSingleCacheAdvice.java

@Around("getSingle()")
public Object cacheSingle(final ProceedingJoinPoint pjp) throws Throwable {
    // If we've disabled the caching programmatically (or via properties file) just flow through.
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return pjp.proceed();
    }/*from w  ww  .  j a  va  2  s.co  m*/

    final MemcachedClientIF cache = getMemcachedClient();
    // 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 baseKey;
    final String cacheKey;
    final ReadThroughSingleCache annotation;
    final AnnotationInfo info;
    final Object[] args = pjp.getArgs();
    try {
        final Method methodToCache = getMethodToCache(pjp);
        annotation = methodToCache.getAnnotation(ReadThroughSingleCache.class);
        info = getAnnotationInfo(annotation, methodToCache.getName(), getJitterDefault());
        baseKey = generateBaseKeySingle(args, info, methodToCache.toString());
        cacheKey = buildCacheKey(baseKey, info.getAsString(AType.NAMESPACE, null),
                info.getAsString(AType.KEY_PREFIX, null));

        final Object result = cache.get(cacheKey);
        if (result != null) {
            return (result instanceof PertinentNegativeNull) ? null : result;
        }
    } catch (Throwable ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
        } else {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error: " + ex.getMessage());
        }
        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;
        boolean cacheable = true;
        if (submission instanceof CacheConditionally) {
            cacheable = ((CacheConditionally) submission).isCacheable();
        }
        if (cacheable) {
            cache.set(cacheKey, calculateJitteredExpiration(info.getAsInteger(AType.EXPIRATION),
                    info.getAsInteger(AType.JITTER)), submission);
        }

        // Notify the observers that a cache interaction happened.
        final List<ReadThroughSingleCacheListener> listeners = getPertinentListeners(
                ReadThroughSingleCacheListener.class, info.getAsString(AType.NAMESPACE));
        if (listeners != null && !listeners.isEmpty()) {
            for (final ReadThroughSingleCacheListener listener : listeners) {
                try {
                    listener.triggeredReadThroughSingleCache(info.getAsString(AType.NAMESPACE),
                            info.getAsString(AType.KEY_PREFIX, null), baseKey, result, args);
                } catch (Exception ex) {
                    LOG.warn("Problem when triggering a listener.", ex);
                }
            }
        }
    } catch (Throwable ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
        } else {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error: " + ex.getMessage());
        }
    }
    return result;
}