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.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer.java

/**
 * Retrieves an annotation for the specified field of setter.
 *
 * @param parentClass     the Class which contains as a property the Map or Collection we are finding the key for.
 * @param property        the property of the Map or Collection for the given parent class
 * @param annotationClass The annotation
 * @return concrete Annotation instance or <tt>null</tt> if none could be retrieved.
 */// w ww  . j a va  2s. c o m
private <T extends Annotation> T getAnnotationFromSetter(Class parentClass, String property,
        Class<T> annotationClass) {
    try {
        Method setter = reflectionProvider.getSetMethod(parentClass, property);

        if (setter != null) {
            return setter.getAnnotation(annotationClass);
        }
    } catch (ReflectionException | IntrospectionException e) {
        // ignore
    }
    return null;
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ResultSetConverterBlockServiceImpl.java

private List<EntityPropertySetter> createEntityPropertySetters(ParameterConverterService converterService,
        Class type, StoredProcedureInfo procedureInfo, String tablePrefix) {
    List<EntityPropertySetter> list = new LinkedList<EntityPropertySetter>();
    for (Method getterMethod : type.getMethods()) {
        Column columnAnnotation = getterMethod.getAnnotation(Column.class);
        if (columnAnnotation != null) {
            Method setterMethod = BlockFactoryUtils.findSetterMethod(type, getterMethod);
            String columnName = tablePrefix + columnAnnotation.name();
            if (LOG.isDebugEnabled()) {
                LOG.debug("         Mapping result set for {}.{}() to {} ...",
                        new String[] { type.getSimpleName(), getterMethod.getName(), columnName });
            }/*from   w  w  w .  j  a  v  a 2s.  c o m*/
            ResultSetColumnInfo resultSetColumnInfo = procedureInfo.getResultSetColumn(columnName);
            if (resultSetColumnInfo == null) {
                throw new IllegalStateException(String.format(
                        "For method %s.%s() column '%s' was not found in result set for procedure %s() ",
                        type.getSimpleName(), getterMethod.getName(), columnName,
                        procedureInfo.getProcedureName()));
            }
            try {
                IParameterConverter paramConverter = converterService
                        .getConverter(resultSetColumnInfo.getDataType(), getterMethod.getReturnType());
                list.add(new EntityPropertySetter(setterMethod, paramConverter,
                        resultSetColumnInfo.getColumnName(), null, resultSetColumnInfo.getDataType()));
            } catch (IllegalStateException e) {
                throw new IllegalStateException(String.format(
                        "Converter was not found for method %s.%s() [ column '%s' in procedure %s()]",
                        type.getSimpleName(), getterMethod.getName(), columnName,
                        procedureInfo.getProcedureName()), e);
            }
        }
    }
    return list;
}

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

private void doUpdate(final JoinPoint jp, final Object retVal) throws Throwable {
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return;//from  w ww . j av  a 2  s . c om
    }

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

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

    for (int i = 0; i < lAnnotations.size(); i++) {
        try {
            // 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 AnnotationInfo info = getAnnotationInfo(lAnnotations.get(i), methodToCache.getName(),
                    getJitterDefault());
            List<Object> dataList = (List<Object>) getIndexObject(info.getAsInteger(AType.DATA_INDEX), retVal,
                    jp.getArgs(), methodToCache.toString());
            dataList = UpdateMultiCacheAdvice.getMergedDataList(dataList,
                    info.getAsString(AType.DATA_TEMPLATE, null), retVal, jp.getArgs(), factory);
            final List<Object> keyObjects = getKeyObjects(info.getAsInteger(AType.KEY_INDEX), retVal, jp,
                    methodToCache);
            final List<String> baseKeys = UpdateMultiCacheAdvice.getBaseKeys(keyObjects,
                    info.getAsString(AType.KEY_TEMPLATE, null), retVal, jp.getArgs(), factory, methodStore);
            final List<String> cacheKeys = new ArrayList<String>(baseKeys.size());
            for (final String base : baseKeys) {
                cacheKeys.add(buildCacheKey(base, info.getAsString(AType.NAMESPACE, null),
                        info.getAsString(AType.KEY_PREFIX, null)));
            }
            updateCache(cacheKeys, dataList, methodToCache, info.getAsInteger(AType.JITTER),
                    info.getAsInteger(AType.EXPIRATION), cache,
                    (Class) info.getAsType(AType.DATA_TEMPLATE_TYPE, String.class));

            // Notify the observers that a cache interaction happened.
            final List<UpdateMultiCacheListener> listeners = getPertinentListeners(
                    UpdateMultiCacheListener.class, info.getAsString(AType.NAMESPACE));
            if (listeners != null && !listeners.isEmpty()) {
                for (final UpdateMultiCacheListener listener : listeners) {
                    try {
                        listener.triggeredUpdateMultiCache(info.getAsString(AType.NAMESPACE),
                                info.getAsString(AType.KEY_PREFIX, null), baseKeys, dataList, retVal,
                                jp.getArgs());
                    } catch (Exception ex) {
                        LOG.warn("Problem when triggering a listener.", ex);
                    }
                }
            }
        } catch (Exception 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:gobblin.runtime.cli.PublicMethodsCliObjectFactory.java

private Options inferOptionsFromMethods() {
    Options options = new Options();

    for (Method method : klazz.getMethods()) {
        if (canUseMethod(method)) {
            CliObjectOption annotation = method.isAnnotationPresent(CliObjectOption.class)
                    ? method.getAnnotation(CliObjectOption.class)
                    : null;//from w w  w  .  j  a v a  2s .  co m
            String optionName = annotation == null || Strings.isNullOrEmpty(annotation.name())
                    ? method.getName()
                    : annotation.name();
            String description = annotation == null ? "" : annotation.description();
            Option.Builder builder = Option.builder(optionName).desc(description);
            boolean hasArg = method.getParameterTypes().length > 0;
            if (hasArg) {
                builder.hasArg();
            }
            Option option = builder.build();
            options.addOption(option);
            this.methodsMap.put(option.getOpt(), method);
        }
    }

    return options;
}

From source file:com.mac.halendpoint.endpoints.ProtocolRouter.java

public Protocol router(Protocol protocol)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {

    log.info("incoming protocol: " + protocol);
    if (Objects.nonNull(protocol)) {
        Method[] methods = this.getClass().getDeclaredMethods();
        log.info("protocol NOT null");
        for (Method method : methods) {
            if (!method.getName().equals("router")) {
                log.info("current method: " + method.getName());
                method.setAccessible(true);
                ProtocolMapping protoMapping = method.getAnnotation(ProtocolMapping.class);
                log.info("ProtocolMapping: " + protoMapping);
                if (Objects.nonNull(protoMapping)) {
                    log.info("ProtocolMapping not null");
                    if (protoMapping.routeTo().equalsIgnoreCase(protocol.getRoutedTo())) {
                        log.info("routing to: " + protoMapping.routeTo());
                        int numParams = protoMapping.numParams();
                        String[] parameters = protocol.getParameters();
                        if (Objects.nonNull(parameters) && parameters.length == numParams) {
                            log.info("parameter lengths match");
                            Object response = method.invoke(this, (Object[]) parameters);
                            log.info("response after invocation");
                            protocol.setRespondTo(protoMapping.respondTo());
                            if (!(response instanceof String)) {
                                protocol.setResponse(JsonConverter.toJsonString(response));
                            } else {
                                protocol.setResponse((String) response);
                            }/*from   w w  w.  j  a va  2  s  .  co m*/
                            protocol.setIsModified(true);
                            log.info(response.toString());
                            log.info("final protocol: " + protocol);
                            log.info("final protocol: " + protocol.getRespondTo());
                            log.info("final protocol: " + protocol.getResponse());
                            log.info("final protocol: " + protocol.getRoutedTo());
                            log.info("final protocol: " + Arrays.toString(protocol.getParameters()));
                        }
                    }
                }
                method.setAccessible(false);
            }
        }
        return protocol;
    }
    return new FailedProtocol();
}

From source file:org.flywaydb.test.junit.FlywayTestExecutionListener.java

/**
 * Called from spring before a test method will be invoked.
 *
 * @param testContext//from w w  w.j  a v  a  2  s. c o  m
 *            default test context filled from spring
 *
 * @throws Exception
 *             if any error occurred
 */
public void beforeTestMethod(final TestContext testContext) throws Exception {
    final Method testMethod = testContext.getTestMethod();

    final Annotation annotation = testMethod.getAnnotation(FlywayTest.class);

    dbResetWithAnotation(testContext, (FlywayTest) annotation);
}

From source file:com.github.wnameless.spring.routing.RoutingPathResolver.java

/**
   * Creates a {@link RoutingPathResolver}.
   * //from www  .j  ava  2  s  . co  m
   * @param appCtx
   *          the Spring {@link ApplicationContext}
   * @param basePackages
   *          packages to be searched
   */
  public RoutingPathResolver(ApplicationContext appCtx, String... basePackages) {
      env = appCtx.getEnvironment();
      Map<String, Object> beans = appCtx.getBeansWithAnnotation(Controller.class);
      beans.putAll(appCtx.getBeansWithAnnotation(RestController.class));
      retainBeansByPackageNames(beans, basePackages);

      for (Object bean : beans.values()) {
          List<Method> mappingMethods = getMethodsListWithAnnotation(bean.getClass(), RequestMapping.class);
          RequestMapping classRM = bean.getClass().getAnnotation(RequestMapping.class);
          for (Method method : mappingMethods) {
              RequestMapping methodRM = method.getAnnotation(RequestMapping.class);
              for (Entry<String, RequestMethod> rawPathAndMethod : computeRawPaths(classRM, methodRM)) {
                  String rawPath = rawPathAndMethod.getKey();
                  String path = computePath(rawPath);
                  String regexPath = computeRegexPath(path);
                  routingPaths.add(new RoutingPath(rawPathAndMethod.getValue(), rawPath, path,
                          Pattern.compile(regexPath), bean.getClass().getAnnotations(), method.getAnnotations()));
              }
          }
      }
  }

From source file:org.jsonschema2pojo.integration.config.CustomAnnotatorIT.java

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void customAnnotatorIsAbleToAddCustomAnnotations()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "none", // turn off core annotations
                    "customAnnotator", DeprecatingAnnotator.class.getName()));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Method getter = generatedType.getMethod("getA");

    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue()));
}

From source file:com.expressui.core.view.field.DisplayField.java

private String getLabelTextFromAnnotation() {
    Class propertyContainerType = beanPropertyType.getContainerType();
    String propertyIdRelativeToContainerType = beanPropertyType.getId();
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(propertyContainerType,
            propertyIdRelativeToContainerType);
    Method method = descriptor.getReadMethod();
    Label labelAnnotation = method.getAnnotation(Label.class);
    if (labelAnnotation == null) {
        return null;
    } else {/*from w  w w .  j a v a2s  . c  o  m*/
        return labelAnnotation.value();
    }
}

From source file:org.bigtester.ate.model.casestep.StepDataLogger.java

private RefreshDataType getDataType(JoinPoint thisJoinPoint) {

    MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();
    String methodName = methodSignature.getMethod().getName();
    Class<?>[] parameterTypes = methodSignature.getMethod().getParameterTypes();
    Method targetMethod;
    try {//from  w  w w .j  av  a  2 s  .c o m
        targetMethod = thisJoinPoint.getTarget().getClass().getMethod(methodName, parameterTypes);
        return ((RepeatStepRefreshable) targetMethod.getAnnotation(RepeatStepRefreshable.class)).dataType();
    } catch (NoSuchMethodException | SecurityException e) {
        throw GlobalUtils.createInternalError("jvm class method error", e);
    }
    // targetMethod = methodSignature.getMethod();

}