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.cloudera.nav.plugin.client.writer.registry.MPropertyRegistryFactory.java

private String getAttributeName(Method method) {
    // return attribute from MProperty annotation if explicitly specified
    // otherwise create the attribute from the method name
    // with first letter lowercased
    String attributeName = method.getAnnotation(MProperty.class).attribute();
    if (StringUtils.isEmpty(attributeName)) {
        String methodName = method.getName();
        for (String prefix : PREFIXES) {
            if (methodName.startsWith(prefix) && methodName.length() > prefix.length()) {
                methodName = String.valueOf(methodName.charAt(prefix.length())).toLowerCase()
                        + methodName.substring(prefix.length() + 1);
                break;
            }/*from  w w  w. j a v a  2s.  com*/
        }
        attributeName = methodName;
    }
    return attributeName;
}

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

@Around("@annotation(com.newtranx.util.mysql.fabric.QueryAllShards)")
public Object union(ProceedingJoinPoint pjp) throws Throwable {
    Method method = AspectJUtils.getMethod(pjp);
    QueryAllShards annotation = method.getAnnotation(QueryAllShards.class);
    String table = annotation.table();
    log.debug("Table=" + table);
    Set<String> groups = groupsCache.get(cacheKey);
    log.debug("ServerGroups=" + groups);
    List<Object> list;
    boolean readOnly = annotation.readOnly();
    Pattern excludePattern;//ww  w  . j a  v  a2  s. com
    String excludeRegex = annotation.excludeShardsPatternRegex();
    if (!StringUtils.isEmpty(excludeRegex)) {
        excludePattern = Pattern.compile(excludeRegex);
    } else {
        excludePattern = null;
    }

    Function<Boolean, List<Object>> computeFunction = (par) -> {
        Stream<String> stream = groups.stream();
        if (par)
            stream = stream.parallel();
        return stream.filter(gp -> {
            boolean exclude = excludePattern != null && excludePattern.matcher(gp).matches();
            if (exclude) {
                log.debug("Skipping group:" + gp);
            }
            return !exclude;
        }).map(gp -> {
            log.debug("Querying group: " + gp);
            ds.whenNewConnection().doInit(conn -> conn.setServerGroupName(gp))
                    .doInit(conn -> conn.setReadOnly(readOnly));
            try {
                return pjp.proceed();
            } catch (Throwable t) {
                throw Exceptions.propagate(t);
            } finally {
                ds.clearInitOps();
            }
        }).collect(Collectors.toList());
    };

    if (StringUtils.isEmpty(annotation.parallelPool())) {
        list = computeFunction.apply(false);
    } else {
        ForkJoinPool pool;
        if ("!jdkCommon".equals(annotation.parallelPool()))
            pool = ForkJoinPool.commonPool();
        else
            pool = applicationContext.getBean(annotation.parallelPool(), ForkJoinPool.class);
        log.debug("Executing queries in parallel, pool=" + pool);
        list = pool.submit(() -> {
            return computeFunction.apply(true);
        }).get();
    }
    Aggregator aggregator;
    try {
        aggregator = (Aggregator) annotation.aggregator().getDeclaredMethod("getInstance", EMPTY_PARAM)
                .invoke(null, EMPTY_ARGS);
    } catch (Exception e) {
        log.warn("Can not get singleton for class " + annotation.aggregator().getName()
                + ", creating new instance");
        aggregator = annotation.aggregator().newInstance();
    }
    return aggregator.apply(list);
}

From source file:com.feilong.commons.core.lang.annotation.AnnotationTest.java

/**
 * TestAnnotationTest.// w w  w .j  a va2  s.c o  m
 */
@Test
public void testAnnotationTest() {
    log.info("" + AnnotationTest.class.isAnnotationPresent(MyAnnotation.class));

    MyAnnotation myAnnotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
    log.info(myAnnotation.name());

    // *************************************************************
    Method[] methods = AnnotationTest.class.getDeclaredMethods();
    for (Method method : methods) {
        if (method.isAnnotationPresent(MyAnnotation.class)) {
            log.info("[Test." + method.getName() + "].annotation:");
            MyAnnotation fieldAnnotation = method.getAnnotation(MyAnnotation.class);
            log.info(ArrayUtils.toString(fieldAnnotation.loveStrings()));
        }
    }
}

From source file:com.google.code.ssm.aop.UpdateMultiCacheAdviceTest.java

@Test
public void testUpdateCache() throws Exception {
    final Method method = AnnotationTest.class.getMethod("cacheMe01", List.class);
    final UpdateMultiCache annotation = method.getAnnotation(UpdateMultiCache.class);
    final AnnotationData data = AnnotationDataBuilder.buildAnnotationData(annotation, UpdateMultiCache.class,
            method);//from   w w  w. jav a 2  s  .  c  o  m

    final List<String> keys = new ArrayList<String>();
    final List<Object> objs = new ArrayList<Object>();
    keys.add("Key1-" + System.currentTimeMillis());
    keys.add("Key2-" + System.currentTimeMillis());

    try {
        cut.updateCache(keys, objs, method, data, null);
        fail("Expected Exception.");
    } catch (InvalidAnnotationException ex) {
        assertTrue(ex.getMessage().contains("do not match in size"));
    }

    final Cache cache = EasyMock.createMock(Cache.class);
    EasyMock.expect(cache.getName()).andReturn(AnnotationConstants.DEFAULT_CACHE_NAME);
    EasyMock.expect(cache.getAliases()).andReturn(Collections.<String>emptyList()).anyTimes();
    EasyMock.expect(cache.getProperties()).andReturn(new CacheProperties()).anyTimes();
    for (final String key : keys) {
        final String value = "ValueFor-" + key;
        objs.add(value);
        cache.setSilently(key, data.getExpiration(), value, null);
        EasyMock.expectLastCall();
    }
    keys.add("BigFatNull");
    objs.add(null);
    cache.setSilently(keys.get(2), data.getExpiration(), new PertinentNegativeNull(), null);
    EasyMock.expectLastCall();

    EasyMock.replay(cache);

    cut.getCacheBase().addCache(cache);
    cut.updateCache(keys, objs, method, data, null);

    EasyMock.verify(cache);
}

From source file:com.shigengyu.hyperion.cache.WorkflowTransitionCacheLoader.java

@Override
public ImmutableList<WorkflowTransition> load(WorkflowDefinition workflowDefinition) throws Exception {

    List<WorkflowTransition> workflowTransitions = Lists.newArrayList();

    for (Method method : ReflectionUtils
            .getAllDeclaredMethods(workflowDefinition.getWorkflowDefinitionType())) {
        if (method.isAnnotationPresent(Transition.class)) {
            Transition transition = method.getAnnotation(Transition.class);
            TransitionShared transitionShared = method.getAnnotation(TransitionShared.class);
            workflowTransitions.add(new WorkflowTransition(method, transition, transitionShared));
        } else if (method.isAnnotationPresent(Transitions.class)) {
            Transitions transitions = method.getAnnotation(Transitions.class);
            for (Transition transition : transitions.value()) {
                TransitionShared transitionShared = method.getAnnotation(TransitionShared.class);
                workflowTransitions.add(new WorkflowTransition(method, transition, transitionShared));
            }/*ww  w .  j av a2  s .c  om*/
        }
    }

    return ImmutableList.copyOf(workflowTransitions);
}

From source file:com.evanzeimet.queryinfo.jpa.attribute.DefaultEntityAnnotationsAttributeInfoResolver.java

protected QueryInfoJoinInfo createJoinInfo(Method annotatedMethod) {
    QueryInfoJoin annotation = annotatedMethod.getAnnotation(QueryInfoJoin.class);

    String jpaAttributeName = createJpaAttributeName(annotatedMethod);
    String name = annotation.name();

    if (StringUtils.isBlank(name)) {
        name = jpaAttributeName;//from w  w  w .j av a  2s . co  m
    }

    return QueryInfoJoinInfoBuilder.create().annotation(annotation).jpaAttributeName(jpaAttributeName)
            .name(name).build();
}

From source file:net.mindengine.oculus.frontend.web.controllers.api.ApiController.java

private String findRequestMethod(Method method) {
    if (method.getAnnotation(GET.class) != null) {
        return "GET";
    } else if (method.getAnnotation(POST.class) != null) {
        return "POST";
    } else if (method.getAnnotation(DELETE.class) != null) {
        return "DELETE";
    } else if (method.getAnnotation(PUT.class) != null) {
        return "PUT";
    }/*from  ww  w  . j  av  a  2  s.c  o m*/
    return null;
}

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

protected Method getKeyMethod(final Object keyObject) throws NoSuchMethodException {
    final Method storedMethod = methodStore.find(keyObject.getClass());
    if (storedMethod != null) {
        return storedMethod;
    }//from w  w  w.j  ava2s  . c  o m
    final Method[] methods = keyObject.getClass().getDeclaredMethods();
    Method targetMethod = null;
    for (final Method method : methods) {
        if (method != null && method.getAnnotation(CacheKeyMethod.class) != null) {
            if (method.getParameterTypes().length > 0) {
                throw new InvalidAnnotationException(
                        String.format("Method [%s] must have 0 arguments to be annotated with [%s]",
                                method.toString(), CacheKeyMethod.class.getName()));
            }
            if (!String.class.equals(method.getReturnType())) {
                throw new InvalidAnnotationException(
                        String.format("Method [%s] must return a String to be annotated with [%s]",
                                method.toString(), CacheKeyMethod.class.getName()));
            }
            if (targetMethod != null) {
                throw new InvalidAnnotationException(String.format(
                        "Class [%s] should have only one method annotated with [%s]. See [%s] and [%s]",
                        keyObject.getClass().getName(), CacheKeyMethod.class.getName(), targetMethod.getName(),
                        method.getName()));
            }
            targetMethod = method;
        }
    }

    if (targetMethod == null) {
        targetMethod = keyObject.getClass().getMethod("toString", null);
    }

    methodStore.add(keyObject.getClass(), targetMethod);

    return targetMethod;
}

From source file:com.bstek.dorado.data.config.DataObjectAnnotationEngineStartupListener.java

@SuppressWarnings("rawtypes")
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType,
        String beanName) {/*from w w  w  .  ja  va 2s. c  om*/
    for (Method method : beanType.getMethods()) {
        DataProvider dataProviderAnnotation = method.getAnnotation(DataProvider.class);
        if (dataProviderAnnotation != null) {
            pendingDataObjects.add(new PendingDataObject(DataObjectType.dataProvider, dataProviderAnnotation,
                    beanName, method.getName()));
        }

        DataResolver dataResolverAnnotation = method.getAnnotation(DataResolver.class);
        if (dataResolverAnnotation != null) {
            pendingDataObjects.add(new PendingDataObject(DataObjectType.dataResolver, dataResolverAnnotation,
                    beanName, method.getName()));
        }
    }
}

From source file:com.evanzeimet.queryinfo.jpa.attribute.DefaultEntityAnnotationsAttributeInfoResolver.java

protected QueryInfoFieldInfo createFieldInfo(Method annotatedMethod) {
    QueryInfoField annotation = annotatedMethod.getAnnotation(QueryInfoField.class);

    String jpaAttributeName = createJpaAttributeName(annotatedMethod);
    String name = annotation.name();

    if (StringUtils.isBlank(name)) {
        name = jpaAttributeName;/*from w  w w .j  a va 2s . co m*/
    }

    return QueryInfoFieldInfoBuilder.create().annotation(annotation).jpaAttributeName(jpaAttributeName)
            .name(name).build();
}