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.hengyi.japp.sap.convert.impl.SapConverts.java

private String getSapFieldName(PropertyDescriptor descriptor) {
    Method readMethod = descriptor.getReadMethod();
    SapConvertField scf = readMethod.getAnnotation(SapConvertField.class);
    if (scf != null) {
        return StringUtils.upperCase(scf.value());
    }/*from   ww  w  . j  a v  a 2s . c  om*/
    if (readMethod.getAnnotation(SapTransient.class) != null) {
        return null;
    }

    String beanPropertyName = descriptor.getName();
    for (Field field : beanClass.getDeclaredFields()) {
        if (!field.getName().equals(beanPropertyName)) {
            continue;
        }

        if (field.getAnnotation(SapTransient.class) != null) {
            return null;
        }
        scf = field.getAnnotation(SapConvertField.class);
        if (scf != null) {
            return StringUtils.upperCase(scf.value());
        }
    }
    return StringUtils.upperCase(beanPropertyName);
}

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

@Override
public List<Constraint> generate(Method readMethod, String property, Map<String, String> params) {
    List<Constraint> constraints = null;
    Annotation annotation = readMethod.getAnnotation(Length.class);
    if (annotation != null) {
        Length length = (Length) annotation;

        boolean generateConstraint;
        if (params != null && StringUtils.isNotBlank(params.get("id"))) {
            generateConstraint = ArrayUtils.contains(length.modes(), ValidationMode.UPDATE);
        } else {//w w w . jav  a2  s  .  co m
            generateConstraint = ArrayUtils.contains(length.modes(), ValidationMode.CREATE);
        }
        if (generateConstraint) {
            String parameterName = StringUtils.isNotBlank(length.parameterName()) ? length.parameterName()
                    : property;
            Constraint constraint = new Constraint(length.annotationType().getSimpleName());
            List<RuleParameter> ruleParameters = new ArrayList<RuleParameter>();
            RuleParameter minParam = new RuleParameter("min", length.minLength());
            ruleParameters.add(minParam);
            String minLengthMsg = MessageResolver.messageFormatting(length.minLengthMsgKey(), Locale.ENGLISH,
                    parameterName, length.minLength()); //TODO need to set real locale
            RuleParameter minMsgParam = new RuleParameter("minMsg", minLengthMsg);
            ruleParameters.add(minMsgParam);
            RuleParameter maxParam = new RuleParameter("max", length.maxLength());
            ruleParameters.add(maxParam);
            String maxLengthMsg = MessageResolver.messageFormatting(length.maxLengthMsgKey(), Locale.ENGLISH,
                    parameterName, length.maxLength()); //TODO need to set real locale
            RuleParameter maxMsgParam = new RuleParameter("maxMsg", maxLengthMsg);
            ruleParameters.add(maxMsgParam);
            constraint.setParams(ruleParameters);
            constraints = new ArrayList<Constraint>();
            constraints.add(constraint);
        }
    }
    return constraints;
}

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

@Test
public void testUpdateCache() throws Exception {
    final Method method = AnnotationTest.class.getMethod("cacheMe01", String.class);
    final UpdateMultiCache annotation = method.getAnnotation(UpdateMultiCache.class);
    final AnnotationData data = AnnotationDataBuilder.buildAnnotationData(annotation, UpdateMultiCache.class,
            method);//from w  w  w. ja v  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);
        fail("Expected Exception.");
    } catch (InvalidAnnotationException ex) {
        assertTrue(ex.getMessage().contains("do not match in size"));
    }

    final MemcachedClientIF cache = EasyMock.createMock(MemcachedClientIF.class);
    cut.setCache(cache);

    for (final String key : keys) {
        final String value = "ValueFor-" + key;
        objs.add(value);
        EasyMock.expect(cache.set(key, data.getExpiration(), value)).andReturn(null);
    }
    keys.add("BigFatNull");
    objs.add(null);
    EasyMock.expect(cache.set(keys.get(2), data.getExpiration(), new PertinentNegativeNull())).andReturn(null);

    EasyMock.replay(cache);

    cut.updateCache(keys, objs, method, data);

    EasyMock.verify(cache);

}

From source file:com.vsct.supervision.notification.log.LoggingAspect.java

@Around(value = "@within(com.vsct.supervision.notification.log.Loggable) || @annotation(com.vsct.supervision.notification.log.Loggable)")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

    final MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
    final Method method = signature.getMethod();
    final Class clazz = signature.getClass();
    final Loggable loggableMethod = method.getAnnotation(Loggable.class);

    final Loggable loggableClass = proceedingJoinPoint.getTarget().getClass().getAnnotation(Loggable.class);

    //get current log level
    final LogLevel logLevel = loggableMethod != null ? loggableMethod.value() : loggableClass.value();

    final String service = StringUtils.isNotBlank(loggableClass.service()) ? loggableClass.service()
            : clazz.getName();/*from ww w  . j  a  v a2  s  .  c  o  m*/
    final String methodName = StringUtils.isNotBlank(loggableClass.method()) ? loggableClass.method()
            : method.getName();

    final String star = "**********";
    //before
    LogWriter.write(proceedingJoinPoint.getTarget().getClass(), logLevel,
            star + service + "." + methodName + "() start execution" + star);

    //show traceParams
    final boolean showParams = loggableMethod != null ? loggableMethod.traceParams()
            : loggableClass.traceParams();
    if (showParams) {

        if (proceedingJoinPoint.getArgs() != null && proceedingJoinPoint.getArgs().length > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < proceedingJoinPoint.getArgs().length; i++) {
                sb.append(method.getParameterTypes()[i].getName() + ":" + proceedingJoinPoint.getArgs()[i]);
                if (i < proceedingJoinPoint.getArgs().length - 1)
                    sb.append(", ");
            }

            LogWriter.write(proceedingJoinPoint.getTarget().getClass(), logLevel,
                    service + "." + methodName + "() args " + sb);
        }

    }

    final long startTime = System.currentTimeMillis();
    //start method execution
    final Object result = proceedingJoinPoint.proceed();

    final long endTime = System.currentTimeMillis();

    //show results
    if (result != null) {
        boolean showResults = loggableMethod != null ? loggableMethod.traceResult()
                : loggableClass.traceResult();
        if (showResults) {
            LogWriter.write(proceedingJoinPoint.getTarget().getClass(), logLevel,
                    service + "." + methodName + "() Result : " + result);
        }
    }

    //show after
    LogWriter.write(proceedingJoinPoint.getTarget().getClass(), logLevel, star + service + "." + methodName
            + "() finished execution and takes " + (endTime - startTime) + " millis time to execute " + star);

    return result;
}

From source file:de.anhquan.config4j.internal.ConfigHandler.java

@SuppressWarnings("unchecked")
private Object findDefaultValue(Method getter, Class returnType) {
    System.out.println("Find default");
    ConfigParam annotation = getter.getAnnotation(ConfigParam.class);
    Object defaultValue = null;//from ww w  .  j a  v a  2  s .  c o  m
    if (annotation != null) {
        if (returnType.equals(Integer.class) || returnType.equals(int.class))
            defaultValue = annotation.DefaultInteger();
        else if (returnType.equals(Double.class) || returnType.equals(double.class))
            defaultValue = annotation.DefaultDouble();
        else if (returnType.equals(Float.class) || returnType.equals(float.class))
            defaultValue = annotation.DefaultFloat();
        else if (returnType.equals(Byte.class) || returnType.equals(byte.class))
            defaultValue = annotation.DefaultFloat();
        else if (returnType.equals(Character.class) || returnType.equals(char.class))
            defaultValue = annotation.DefaultChar();
        else if (returnType.equals(String.class))
            defaultValue = annotation.DefaultString();
        else if (returnType.equals(Boolean.class))
            defaultValue = annotation.DefaultBoolean();
        else if (returnType.equals(Class.class))
            defaultValue = annotation.DefaultClass();
    }
    return defaultValue;
}

From source file:grails.plugin.springsecurity.acl.access.method.SecuredAnnotationSecurityMetadataSource.java

/**
 * {@inheritDoc}//from  ww w  .  j  av  a2  s. c  o  m
 * @see org.springframework.security.access.method.AbstractFallbackMethodSecurityMetadataSource#findAttributes(
 *    java.lang.reflect.Method, java.lang.Class)
 */
@Override
protected Collection<ConfigAttribute> findAttributes(final Method method, final Class<?> targetClass) {
    Method actualMethod = ProxyUtils.unproxy(method);

    if (!isService(actualMethod.getDeclaringClass())) {
        return null;
    }

    return processAnnotation(actualMethod.getAnnotation(Secured.class));
}

From source file:de.xaniox.heavyspleef.core.event.EventListenerMethod.java

@SuppressWarnings("unchecked")
public EventListenerMethod(Object instance, Method method) {
    this.instance = instance;
    this.method = method;

    if (!method.isAccessible()) {
        method.setAccessible(true);/*from w  ww.  j a  v  a2s .  co  m*/
    }

    subscribe = method.getAnnotation(Subscribe.class);

    Class<?>[] parameters = method.getParameterTypes();
    Validate.isTrue(parameters.length == 1,
            "method must have only one parameter which must be a subtype of Event");

    Class<?> eventClass = parameters[0];
    Validate.isTrue(Event.class.isAssignableFrom(eventClass),
            "First parameter of method must be a subtype of Event");

    this.eventClass = (Class<? extends Event>) eventClass;
}

From source file:modelos.Aluno.java

@Override
public String toString() {
    List<String> str = new ArrayList<>();
    for (Method m : this.getClass().getDeclaredMethods()) {
        if (m.isAnnotationPresent(Printable.class)) {
            try {
                str.add(m.getAnnotation(Printable.class).posicao(),
                        (m.invoke(this, new Object[] {})).toString());
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                continue;
            }/* w  ww . j  a v a 2s . co  m*/
        }
    }
    String result = "";
    for (String piece : str) {
        result += piece + " ";
    }
    return result.trim();
}

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

@Override
public List<Constraint> generate(Method readMethod, String property, Map<String, String> params) {
    List<Constraint> constraints = null;
    NotMatch notMatch = readMethod.getAnnotation(NotMatch.class);
    if (notMatch != null) {
        Constraint constraint = new Constraint(notMatch.annotationType().getSimpleName());
        String errorMessage = MessageResolver.messageFormatting(notMatch.msgKey(), Locale.ENGLISH, property,
                notMatch.example()); //TODO need to set real locale
        constraint.setErrorMessage(errorMessage);
        List<RuleParameter> ruleParameters = new ArrayList<RuleParameter>();

        String expression = notMatch.expression();
        if (StringUtils.isNotBlank(expression)) {
            RuleParameter expressionParam = new RuleParameter("expression", expression);
            ruleParameters.add(expressionParam);
        }//from   w ww.jav  a2  s.  c  o m

        if (!notMatch.javaWords()) {
            RuleParameter ruleParameter = new RuleParameter("words", words);
            ruleParameters.add(ruleParameter);
        }

        if (!ruleParameters.isEmpty()) {
            constraints = new ArrayList<Constraint>();
            constraint.setParams(ruleParameters);
            constraints.add(constraint);
        }
    }
    return constraints;
}

From source file:com.epam.ta.reportportal.database.fixture.SpringFixtureRule.java

/**
 * Looking for {@link SpringFixture} annotation on test method and test
 * class/* w ww .j  ava 2 s  .  c o  m*/
 * 
 * @param description
 * @return
 */
private SpringFixture getFixtureAnnotation(Description description) {
    SpringFixture fixture = null;
    try {
        Class<?> testClass = description.getTestClass();

        Method method = testClass.getDeclaredMethod(description.getMethodName());

        /* Try to find fixture on method */
        fixture = method.getAnnotation(SpringFixture.class);

        /*
         * if method is not annotated tries to find annotation on test class
         */
        if (!isTestAnnotated(fixture)) {
            fixture = AnnotationUtils.findAnnotation(testClass, SpringFixture.class);

        }

    } catch (Exception e) {
        Throwables.propagate(e);
    }

    if (null == fixture) {
        throw new RuntimeException("You should put 'Fixture' annotation on test class or test method");
    }
    return fixture;

}