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.eu.evaluation.server.service.impl.DictionaryServiceImpl.java

private void initField(EntityEnum ee, ObjectDictionary od) {
    Field[] fields = BeanUtils.getDeclaredFields(ee.getEntityClass(), EvaluatedData.class);
    List<FieldDictionary> fdList = new ArrayList<FieldDictionary>();
    List<ObjectRelation> foreignList = new ArrayList<ObjectRelation>();
    for (Field f : fields) {
        try {/*from  w w  w  . ja va 2 s .  com*/
            Method method = BeanUtils.getReadMethod(ee.getEntityClass(), f);
            Transient t = method.getAnnotation(Transient.class);
            if (t != null) {//????
                logger.warn("??\n " + ee.getName()
                        + "  " + f.getName() + "  Transient ");
                continue;
            }
            Dictinary dictinary = method.getAnnotation(Dictinary.class);
            if (dictinary == null) {//???
                logger.warn("??\n " + ee.getName()
                        + "  " + f.getName() + "  Dictinary ");
                continue;
            }

            FieldDictionary fd = fieldDictionaryDAO.findByObjectAndProperty(od.getId(), f.getName());
            fd = fd == null ? new FieldDictionary() : fd;

            fd.setObjectDictionary(od);//
            fd.setPropertyName(f.getName());//??
            fd.setValid(true);//?
            fd.setDisplayname(dictinary.displayname());//??
            fd.setVisible(dictinary.visible());//???
            fd.setSimpleProperty(BeanUtils.isSimpleTypeField(f));//??

            Column column = method.getAnnotation(Column.class);
            fd.setFieldName(column != null ? column.name() : fd.getPropertyName());//???

            //?
            if (dictinary.foreignKey() != null && dictinary.foreignKey().foreignClass() != Object.class) {
                ForeignKey foreignKey = dictinary.foreignKey();
                ObjectRelation or = new ObjectRelation();
                or.setSelfClass(od.getInstanceClass());
                or.setPropertyName(fd.getPropertyName());
                or.setRelationClass(foreignKey.foreignClass().getName());
                or.setSimpleProperty(fd.isSimpleProperty());
                foreignList.add(or);
            }
            fdList.add(fd);
        } catch (NoSuchMethodException ex) {
            logger.warn("??\n " + ee.getName() + "  "
                    + f.getName() + " read " + ex.getMessage());

        }

    }
    fieldDictionaryDAO.save(fdList);
    objectRelationDAO.save(foreignList);
}

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

public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    List<ValidationMessage> validationMessages = new ArrayList<ValidationMessage>();
    NotNull validateNull = readMethod.getAnnotation(NotNull.class);
    if (validateNull != null && value == null
            && !(mode == ValidationMode.CREATE && validateNull.autoGeneratedField())) {
        String parameterName = StringUtils.isNotBlank(validateNull.parameterName())
                ? validateNull.parameterName()
                : property;/*  w  w  w .j a va 2  s . co m*/
        validationMessages.add(new ValidationMessage(property, validateNull.msgKey(), parameterName));
    }
    return validationMessages;
}

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

protected SerializationType getSerializationType(final Method method) {
    Serialization serialization = method.getAnnotation(Serialization.class);
    if (serialization != null) {
        return serialization.value();
    }/*w w  w  .j  a va2s. c o m*/

    serialization = method.getDeclaringClass().getAnnotation(Serialization.class);
    if (serialization != null) {
        return serialization.value();
    }

    return null;
}

From source file:net.sf.jasperreports.export.PropertiesNoDefaultsConfigurationFactory.java

/**
 * /* w  w  w  .j  a v a2 s .c o m*/
 */
protected Object getPropertyValue(Method method, JRPropertiesHolder propertiesHolder) {
    Object value = null;
    ExporterProperty exporterProperty = method.getAnnotation(ExporterProperty.class);
    if (exporterProperty != null) {
        value = getPropertyValue(jasperReportsContext, propertiesHolder, exporterProperty,
                method.getReturnType());
    }
    return value;
}

From source file:com.googlecode.jdbcproc.daofactory.DaoMethodInfoFactory.java

/**
 * Creates method info for bets performance
 * @param daoMethod method/*from w  w  w. ja v  a 2  s. co  m*/
 * @return method info
 */
public DaoMethodInvoker createDaoMethodInvoker(Method daoMethod) {
    AStoredProcedure procedureAnnotation = daoMethod.getAnnotation(AStoredProcedure.class);
    Assert.notNull(procedureAnnotation, "Method must have @AStoredProcedure annotation");

    String procedureName = procedureAnnotation.name();
    Assert.hasText(procedureName,
            "Method " + daoMethod.toString() + " has empty name() parameter in @AStoredProcedure annotation");

    StoredProcedureInfo procedureInfo = storedProcedureInfoManager.getProcedureInfo(procedureName);
    if (LOG.isDebugEnabled()) {
        LOG.debug("      Found procedure info: " + procedureInfo);
    }
    Assert.notNull(procedureInfo, "There is no procedure '" + procedureName + "' in database");

    String callString = createCallString(procedureInfo);

    boolean isReturnIterator = BlockFactoryUtils.isReturnIterator(daoMethod);

    return new DaoMethodInvoker(procedureInfo.getProcedureName(), callString,
            registerOutParametersBlockService.create(procedureInfo),
            parametersSetterBlockService.create(jdbcTemplate, parameterConverterService, daoMethod,
                    procedureInfo, theMetaLoginInfoService),
            callableStatementExecutorBlockService.create(daoMethod, procedureInfo),
            outputParametersGetterBlockService.create(parameterConverterService, daoMethod, procedureInfo),
            resultSetConverterBlockService.create(daoMethod, procedureInfo, parameterConverterService),
            isReturnIterator, theSetStrategyFactory, theGetStrategyFactory);
}

From source file:ch.systemsx.cisd.openbis.generic.shared.RegressionTestCase.java

protected void assertMandatoryMethodAnnotations(Class<?> clazz, String exceptions) {
    List<Class<? extends Annotation>> mandatoryAnnotations = new ArrayList<Class<? extends Annotation>>();
    mandatoryAnnotations.add(RolesAllowed.class);
    mandatoryAnnotations.add(Transactional.class);

    final String noMissingAnnotationsMsg = "Missing annotations in class " + clazz.getCanonicalName() + ":\n";
    StringBuilder problems = new StringBuilder(noMissingAnnotationsMsg);
    for (Method m : clazz.getDeclaredMethods()) {
        List<String> missingAnnotations = new ArrayList<String>();
        for (Class<? extends Annotation> c : mandatoryAnnotations) {
            if (m.getAnnotation(c) == null) {
                missingAnnotations.add(c.getSimpleName());
            }/*from   ww  w.ja va2s. co m*/
        }
        if (missingAnnotations.size() > 0) {
            problems.append(String.format("%s: %s\n", m.getName(), StringUtils.join(missingAnnotations, ", ")));
        }
    }
    assertEquals(noMissingAnnotationsMsg + exceptions, problems.toString());
}

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

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

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

    if (methodToCache.getAnnotation(InvalidateAssignCache.class) != null) {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(InvalidateAssignCache.class));
    } else {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(InvalidateAssignCaches.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 cacheKey = buildCacheKey(info.getAsString(AType.ASSIGN_KEY),
                    info.getAsString(AType.NAMESPACE), info.getAsString(AType.KEY_PREFIX));
            if (cacheKey == null || cacheKey.trim().length() == 0) {
                throw new InvalidParameterException("Unable to find a cache key");
            }
            cache.delete(cacheKey);

            // Notify the observers that a cache interaction happened.
            final List<InvalidateAssignCacheListener> listeners = getPertinentListeners(
                    InvalidateAssignCacheListener.class, info.getAsString(AType.NAMESPACE));
            if (listeners != null && !listeners.isEmpty()) {
                for (final InvalidateAssignCacheListener listener : listeners) {
                    try {
                        listener.triggeredInvalidateAssignCache(info.getAsString(AType.NAMESPACE),
                                info.getAsString(AType.ASSIGN_KEY), 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:grails.plugin.cache.web.ProxyAwareMixedGrailsControllerHelper.java

@Override
protected Object retrieveAction(GroovyObject controller, String actionName, HttpServletResponse response) {

    Method method = ReflectionUtils.findMethod(AopProxyUtils.ultimateTargetClass(controller), actionName,
            MethodGrailsControllerHelper.NOARGS);

    if (method != null) {
        ReflectionUtils.makeAccessible(method);
        if (method.getAnnotation(Action.class) != null) {
            return method;
        }//  w ww.j  av a2s  . co m
    }

    return super.retrieveAction(controller, actionName, response);
}

From source file:com.qmetry.qaf.automation.testng.pro.QAFTestNGListener2.java

@SuppressWarnings("rawtypes")
public void transform(ITestAnnotation testAnnotation, Class clazz, Constructor arg2, Method method) {
    try {//  w  ww.  j  a va2  s.c  o  m
        if ((method.getAnnotation(QAFDataProvider.class) != null) && (null != method.getParameterTypes())
                && (null != method) && (method.getParameterTypes().length > 0)) {
            String dp = getDataProvider(method);
            if (StringUtil.isNotBlank(dp)) {
                testAnnotation.setDataProvider(dp);
                testAnnotation.setDataProviderClass(DataProviderUtil.class);
            }
        }

        if (null != method) {

            String tmtURL = getBundle().getString(method.getName() + ".testspec.url");
            if (StringUtil.isNotBlank(tmtURL)) {
                String desc = String.format("%s<br/><a href=\"%s\">[test-spec]</a>",
                        testAnnotation.getDescription(), tmtURL);
                testAnnotation.setDescription(desc);
            }
            if (getBundle().getBoolean("report.javadoc.link", false)) {
                String linkRelPath = String.format("%s%s.html#%s",
                        getBundle().getString("javadoc.folderpath", "../../../docs/tests/"),
                        method.getDeclaringClass().getCanonicalName().replaceAll("\\.", "/"),
                        ClassUtil.getMethodSignture(method, false));

                String desc = String.format(
                        "%s " + getBundle().getString("report.javadoc.link.format",
                                "<a href=\"%s\" target=\"_blank\">[View-doc]</a>"),
                        testAnnotation.getDescription(), linkRelPath);
                testAnnotation.setDescription(desc);
            }
            testAnnotation
                    .setDescription(getBundle().getSubstitutor().replace(testAnnotation.getDescription()));

            testAnnotation.setRetryAnalyzer(Class
                    .forName(ApplicationProperties.RETRY_ANALYZER.getStringVal(RetryAnalyzer.class.getName())));

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    List<ValidationMessage> validationMessages = new ArrayList<ValidationMessage>();
    Annotation annotation = readMethod.getAnnotation(NonEmptyCollection.class);
    if (annotation != null) {
        NonEmptyCollection notEmptyCollection = (NonEmptyCollection) annotation;
        String parameterName = StringUtils.isNotBlank(notEmptyCollection.parameterName())
                ? notEmptyCollection.parameterName()
                : property;/*from   ww w . j  av  a  2 s .c o  m*/
        if (value == null) {
            validationMessages.add(new ValidationMessage(property, notEmptyCollection.msgKey(), parameterName));
        }
        if (!(value instanceof Collection)) {
            throw new ImproperValidationArgumentException("Argument should be of type java.util.Collection");
        }
        if (((Collection) value).size() == 0) {
            validationMessages.add(new ValidationMessage(property, notEmptyCollection.msgKey(), parameterName));
        }
    }
    return validationMessages;
}