Example usage for java.lang.reflect Method getAnnotations

List of usage examples for java.lang.reflect Method getAnnotations

Introduction

In this page you can find the example usage for java.lang.reflect Method getAnnotations.

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:com.nominanuda.hyperapi.HyperApiHttpInvocationHandler.java

@Nullable
private Object decode(Class<?> hyperApi2, Method method, HttpResponse resp)
        throws UnsupportedEncodingException, IllegalStateException, IOException, ParseException, SAXException {
    if (resp.getEntity() == null || resp.getEntity().getContent() == null) {
        return null;
    }//from  w  w  w  .  j a v  a 2 s . c om
    return entityCodec.decode(resp.getEntity(),
            new AnnotatedType(method.getReturnType(), method.getAnnotations()));
}

From source file:com.expressui.core.util.BeanPropertyType.java

private void initPropertyAnnotations() {
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(containerType, id);
    if (descriptor != null) {
        Method method = descriptor.getReadMethod();
        if (method != null) {
            Annotation[] readMethodAnnotations = method.getAnnotations();
            Collections.addAll(annotations, readMethodAnnotations);
        }//from www  .  j a  va 2  s.  c  o m
    }
}

From source file:org.cruxframework.crux.core.server.rest.core.registry.ResourceRegistry.java

/**
 * /* ww  w . j  a  v  a  2s  . c  om*/
 * @param base
 * @param clazz
 * @param method
 * @param restMethodNames 
 */
protected RestMethodRegistrationInfo processMethod(String base, Class<?> clazz, Method method,
        Set<String> restMethodNames) {
    if (method != null) {
        Path path = method.getAnnotation(Path.class);
        String httpMethod = null;
        try {
            httpMethod = HttpMethodHelper.getHttpMethod(method.getAnnotations());
        } catch (InvalidRestMethod e) {
            logger.error(
                    "Invalid Method: " + method.getDeclaringClass().getName() + "." + method.getName() + "().",
                    e);
        }

        boolean pathPresent = path != null;
        boolean restAnnotationPresent = pathPresent || (httpMethod != null);

        UriBuilder builder = new UriBuilder();
        if (base != null)
            builder.path(base);
        if (clazz.isAnnotationPresent(Path.class)) {
            builder.path(clazz);
        }
        if (path != null) {
            builder.path(method);
        }
        String pathExpression = builder.getPath();
        if (pathExpression == null) {
            pathExpression = "";
        }
        if (restAnnotationPresent && !Modifier.isPublic(method.getModifiers())) {
            logger.error("Rest annotations found at non-public method: " + method.getDeclaringClass().getName()
                    + "." + method.getName() + "(); Only public methods may be exposed as resource methods.");
        } else if (httpMethod != null) {
            if (restMethodNames.contains(method.getName())) {
                logger.error("Overloaded rest method: " + method.getDeclaringClass().getName() + "."
                        + method.getName() + " found. It is not supported for Crux REST services.");
            } else {
                ResourceMethod invoker = new ResourceMethod(clazz, method, httpMethod);
                rootSegment.addPath(pathExpression, invoker);
                restMethodNames.add(method.getName());
                size++;
                return new RestMethodRegistrationInfo(pathExpression, invoker);
            }
        } else {
            if (restAnnotationPresent) {
                logger.error("Method: " + method.getDeclaringClass().getName() + "." + method.getName()
                        + "() declares rest annotations, but it does not inform the methods it must handle. Use one of @PUT, @POST, @GET or @DELETE.");
            } else if (logger.isDebugEnabled()) {
                logger.debug("Method: " + method.getDeclaringClass().getName() + "." + method.getName()
                        + "() ignored. It is not a rest method.");
            }
        }
    }
    return null;
}

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.operation.def.DefaultOperationResolverStrategy.java

/**
 * Process the operation./*w  w w.ja  v  a2  s. co  m*/
 * 
 * @param entityType
 *            The entity type.
 * @param names
 *            The names set.
 * @param process
 *            The process collection.
 * @param method
 *            The method.
 * @param originalName
 *            The original name
 * @return The operation.
 */
private DescribedOperation processOperation(final DescribedEntity<?> entityType, final Set<String> names,
        final Set<Method> process, final Method method, final String originalName) {
    int counter = 1;
    String name = originalName;
    while (names.contains(name)) {
        name = originalName + Integer.toString(counter);
        counter = counter + 1;
    }
    final OperationBuilder builder = AbstractOperation.createBuilder();
    builder.name(name).entity(entityType).operation(method);
    for (final Annotation a : method.getAnnotations()) {
        builder.addAnnotation(a);
    }
    final List<Method> matches = new LinkedList<Method>();
    for (final Method others : process) {
        if (this.match(method, others)) {
            matches.add(others);
            builder.addMatch(others);
        }
    }
    process.removeAll(matches);
    for (final Method others : matches) {
        for (final Annotation a : others.getAnnotations()) {
            builder.addAnnotation(a);
        }
    }
    return builder.buildDescribed();
}

From source file:com.google.gdt.eclipse.designer.uibinder.model.util.UiChildSupport.java

/**
 * @return the {@link Description}s for methods of given {@link WidgetInfo}.
 *//*from  w  w  w  .ja  v a 2  s . c  om*/
private List<Description> getDescriptions(WidgetInfo widget) throws Exception {
    Class<?> componentClass = widget.getDescription().getComponentClass();
    List<Description> descriptions = m_descriptions.get(componentClass);
    if (descriptions == null) {
        descriptions = Lists.newArrayList();
        for (Method method : componentClass.getMethods()) {
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                if (ReflectionUtils.isSuccessorOf(annotation, UI_CHILD)) {
                    descriptions.add(new Description(method, annotation));
                }
            }
        }
        m_descriptions.put(componentClass, descriptions);
    }
    return descriptions;
}

From source file:org.dcm4che3.conf.core.util.ConfigIterators.java

private static List<AnnotatedSetter> processAnnotatedSetters(Class clazz) {
    List<AnnotatedSetter> list;
    list = new ArrayList<AnnotatedSetter>();

    // scan all methods including superclasses, assume each is a config-setter
    for (Method m : clazz.getMethods()) {
        AnnotatedSetter annotatedSetter = new AnnotatedSetter();
        annotatedSetter.setParameters(new ArrayList<AnnotatedConfigurableProperty>());

        Annotation[][] parameterAnnotations = m.getParameterAnnotations();
        Type[] genericParameterTypes = m.getGenericParameterTypes();

        // if method is no-arg, then it is not a setter
        boolean thisMethodIsNotASetter = true;

        for (int i = 0; i < parameterAnnotations.length; i++) {

            thisMethodIsNotASetter = false;

            AnnotatedConfigurableProperty property = new AnnotatedConfigurableProperty();
            property.setAnnotations(annotationsArrayToMap(parameterAnnotations[i]));
            property.setType(genericParameterTypes[i]);

            annotatedSetter.getParameters().add(property);

            // make sure all the parameters of this setter-wannabe are annotated
            if (property.getAnnotation(ConfigurableProperty.class) == null) {
                thisMethodIsNotASetter = true;
                break;
            }// w w  w  .  ja  v a  2  s  . c om
        }

        // filter out non-setters
        if (thisMethodIsNotASetter)
            continue;

        list.add(annotatedSetter);
        annotatedSetter.setAnnotations(annotationsArrayToMap(m.getAnnotations()));
        annotatedSetter.setMethod(m);
    }

    configurableSettersCache.put(clazz, list);
    return list;
}

From source file:com.github.reinert.jjschema.HyperSchemaGeneratorV4.java

private ObjectNode generateLink(Method method) throws InvalidLinkMethod, TypeException {
    String href = null, rel = null, httpMethod = null;
    boolean isLink = false;

    Annotation[] ans = method.getAnnotations();
    for (Annotation a : ans) {
        if (a.annotationType().equals(GET.class)) {
            httpMethod = "GET";
            isLink = true;//from w w w  .ja v a 2 s  .  c om
        } else if (a.annotationType().equals(POST.class)) {
            httpMethod = "POST";
            isLink = true;
        } else if (a.annotationType().equals(PUT.class)) {
            httpMethod = "PUT";
            isLink = true;
        } else if (a.annotationType().equals(DELETE.class)) {
            httpMethod = "DELETE";
            isLink = true;
        } else if (a.annotationType().equals(HEAD.class)) {
            throw new RuntimeException("HEAD not yet supported.");
        } else if (a.annotationType().equals(Path.class)) {
            Path p = (Path) a;
            href = p.value();
        } else if (a.annotationType().equals(Rel.class)) {
            Rel l = (Rel) a;
            rel = l.value();
        }
    }

    // Check if the method is actually a link
    if (!isLink) {
        throw new InvalidLinkMethod(
                "Method " + method.getName() + " is not a link. Must use a HTTP METHOD annotation.");
    }

    // If the rel was not informed than assume the method name
    if (rel == null)
        rel = method.getName();

    // if the href was not informed than fill with default #
    if (href == null)
        href = "#";

    ObjectNode link = jsonSchemaGenerator.createInstance();
    link.put("href", href);
    link.put("method", httpMethod);
    link.put("rel", rel);

    // TODO: by default use a Prototype containing only the $id or $ref for the TargetSchema
    ObjectNode tgtSchema = generateSchema(method.getReturnType());
    if (tgtSchema != null)
        link.put("targetSchema", tgtSchema);

    // Check possible params and form schema attribute.
    // If it has QueryParam or FormParam than the schema must have these params as properties.
    // If it has none of the above and has some ordinary object than the schema must be this
    // object and it is passed by the body.
    Class<?>[] paramTypes = method.getParameterTypes();
    if (paramTypes.length > 0) {
        ObjectNode schema = null;
        boolean hasParam = false;
        boolean hasBodyParam = false;
        for (int i = 0; i < paramTypes.length; i++) {
            Annotation[] paramAns = method.getParameterAnnotations()[i];
            com.github.reinert.jjschema.Media media = null;
            String prop = null;
            boolean isBodyParam = true;
            boolean isParam = false;
            for (int j = 0; j < paramAns.length; j++) {
                Annotation a = paramAns[j];
                if (a instanceof QueryParam) {
                    if (schema == null) {
                        schema = jsonSchemaGenerator.createInstance();
                        schema.put("type", "object");
                    }
                    QueryParam q = (QueryParam) a;
                    schema.put(q.value(), jsonSchemaGenerator.generateSchema(paramTypes[i]));
                    prop = q.value();
                    hasParam = true;
                    isBodyParam = false;
                    isParam = true;
                } else if (a instanceof FormParam) {
                    if (schema == null) {
                        schema = jsonSchemaGenerator.createInstance();
                        schema.put("type", "object");
                    }
                    FormParam q = (FormParam) a;

                    schema.put(q.value(), jsonSchemaGenerator.generateSchema(paramTypes[i]));
                    prop = q.value();
                    hasParam = true;
                    isBodyParam = false;
                    isParam = true;
                } else if (a instanceof PathParam) {
                    if (media != null) {
                        throw new RuntimeException("Media cannot be declared along with PathParam.");
                    }
                    for (int k = j + 1; k < paramAns.length; k++) {
                        Annotation a2 = paramAns[k];
                        if (a2 instanceof com.github.reinert.jjschema.Media)
                            throw new RuntimeException("Media cannot be declared along with PathParam.");
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof CookieParam) {
                    if (media != null) {
                        media = null;
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof HeaderParam) {
                    if (media != null) {
                        media = null;
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof MatrixParam) {
                    if (media != null) {
                        throw new RuntimeException("Media cannot be declared along with MatrixParam.");
                    }
                    for (int k = j + 1; k < paramAns.length; k++) {
                        Annotation a2 = paramAns[k];
                        if (a2 instanceof com.github.reinert.jjschema.Media)
                            throw new RuntimeException("Media cannot be declared along with MatrixParam.");
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof Context) {
                    if (media != null) {
                        throw new RuntimeException("Media cannot be declared along with Context.");
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof com.github.reinert.jjschema.Media) {
                    media = (com.github.reinert.jjschema.Media) a;
                }
            }
            if (isBodyParam) {
                hasBodyParam = true;
                schema = generateSchema(paramTypes[i]);
                if (media != null) {
                    schema.put(MEDIA_TYPE, media.type());
                    schema.put(BINARY_ENCODING, media.binaryEncoding());
                }
            } else if (isParam) {
                hasParam = true;
                if (media != null) {
                    ObjectNode hs = (ObjectNode) schema.get(prop);
                    hs.put(MEDIA_TYPE, media.type());
                    hs.put(BINARY_ENCODING, media.binaryEncoding());
                    schema.put(prop, hs);
                }
            }
        }

        if (hasBodyParam && hasParam)
            throw new RuntimeException(
                    "JsonSchema does not support both FormParam or QueryParam and BodyParam at the same time.");

        link.put("schema", schema);
    }

    return link;
}

From source file:com.seleniumtests.core.aspects.LogAction.java

/**
 * Returns step with name depending on step type
 * In case of cucumber step, get the annotation value. 
 * /!\ THIS WORKS ONLY IF/*w  w  w .  j  a  va 2  s  .  c  om*/
 *    parameters of the annotated method are the Object version ones. Use 'Integer' instead of 'int' for example, when declaring 
 * a cucumber method which uses an integer as parameter. Else method discovery won't find it and step name will fall back to method name
 * 
 * Else, get method name
 * @param joinPoint
 * @param returnArgs   if true, returns method arguments
 * @return
 */
private TestStep buildRootStep(JoinPoint joinPoint, String stepNamePrefix, boolean returnArgs) {
    String stepName;
    List<String> pwdToReplace = new ArrayList<>();
    Map<String, String> arguments = new HashMap<>();
    String argumentString = buildArgString(joinPoint, pwdToReplace, arguments);
    if (returnArgs) {
        stepName = String.format("%s %s", joinPoint.getSignature().getName(), argumentString);
    } else {
        stepName = joinPoint.getSignature().getName();
    }

    // Get the method called by this joinPoint
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

    for (Annotation annotation : method.getAnnotations()) {
        if (annotation.annotationType().getCanonicalName().contains("cucumber.api.java.en")
                && SeleniumRobotTestPlan.isCucumberTest()) {
            stepName = getAnnotationValue(annotation);
            stepName += " " + argumentString;
            break;
        } else if (annotation instanceof StepName) {
            stepName = ((StepName) annotation).value();

            // replaces argument placeholders with values
            for (Entry<String, String> entry : arguments.entrySet()) {
                stepName = stepName.replaceAll(stepName.format("\\$\\{%s\\}", entry.getKey()),
                        entry.getValue().toString());
            }
            break;
        }
    }
    return new TestStep(stepNamePrefix + stepName, TestLogging.getCurrentTestResult(), pwdToReplace);
}

From source file:org.castor.jaxb.reflection.FieldAnnotationProcessingServiceTest.java

@Test
public void testProcessAnnotations() {
    Class<NotASingleField> clazz = NotASingleField.class;
    Assert.assertFalse(clazz.isEnum());//from   w w w  .jav a  2 s  .com
    Assert.assertNotNull(fieldAnnotationProcessingService);
    Field[] fields = clazz.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(field.getName()));
        fieldAnnotationProcessingService.processAnnotations(fi, field.getAnnotations());
    }
    Method[] methods = clazz.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(method.getName()));
        fieldAnnotationProcessingService.processAnnotations(fi, method.getAnnotations());
    }
}

From source file:org.seasar.struts.lessconfig.factory.TigerValidatorAnnotationHandler.java

@Override
protected String getDepends(BeanDesc beanDesc, PropertyDesc propDesc) {
    Method method = getMethodForValidation(propDesc);
    if (!hasAnnotation(method)) {
        return super.getDepends(beanDesc, propDesc);
    }/*from   w ww .jav  a  2s. co  m*/

    StringBuffer depends = new StringBuffer("");

    String autoTypeValidatorName = getAutoTypeValidatorName(propDesc);
    if (!StringUtil.isEmpty(autoTypeValidatorName)) {
        depends.append(autoTypeValidatorName).append(",");
    }

    for (Annotation annotation : method.getAnnotations()) {
        Class<?> type = annotation.annotationType();
        ValidatorTarget target = type.getAnnotation(ValidatorTarget.class);
        if (target != null) {
            String depend = "";
            if (annotation instanceof ValidatorField) {
                depend = createValidatorFieldDepends((ValidatorField) annotation);
            } else {
                depend = getValidatorName(type);
            }
            depends.append(depend);
            depends.append(",");
        }
    }
    if (depends.length() < 1) {
        return null;
    }
    depends.setLength(depends.length() - 1);
    return depends.toString();
}