Search in sources :

Example 6 with Annotation

use of java.lang.annotation.Annotation in project morphia by mongodb.

the class MappedField method discoverConstructor.

private Constructor discoverConstructor() {
    Class<?> type = null;
    // get the first annotation with a concreteClass that isn't Object.class
    for (final Annotation an : foundAnnotations.values()) {
        try {
            final Method m = an.getClass().getMethod("concreteClass");
            m.setAccessible(true);
            final Object o = m.invoke(an);
            //noinspection EqualsBetweenInconvertibleTypes
            if (o != null && !(o.equals(Object.class))) {
                type = (Class) o;
                break;
            }
        } catch (NoSuchMethodException e) {
        // do nothing
        } catch (IllegalArgumentException e) {
            if (LOG.isWarningEnabled()) {
                LOG.warning("There should not be an argument", e);
            }
        } catch (Exception e) {
            if (LOG.isWarningEnabled()) {
                LOG.warning("", e);
            }
        }
    }
    if (type != null) {
        try {
            constructor = type.getDeclaredConstructor();
            constructor.setAccessible(true);
        } catch (NoSuchMethodException e) {
            if (!hasAnnotation(ConstructorArgs.class)) {
                if (LOG.isWarningEnabled()) {
                    LOG.warning("No usable constructor for " + type.getName(), e);
                }
            }
        }
    } else {
        // see if we can create instances of the type used for declaration
        type = getType();
        // short circuit to avoid wasting time throwing an exception trying to get a constructor we know doesnt exist
        if (type == List.class || type == Map.class) {
            return null;
        }
        if (type != null) {
            try {
                constructor = type.getDeclaredConstructor();
                constructor.setAccessible(true);
            } catch (NoSuchMethodException e) {
            // never mind.
            } catch (SecurityException e) {
            // never mind.
            }
        }
    }
    return constructor;
}
Also used : DBObject(com.mongodb.DBObject) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) List(java.util.List) Method(java.lang.reflect.Method) HashMap(java.util.HashMap) Map(java.util.Map) Annotation(java.lang.annotation.Annotation)

Example 7 with Annotation

use of java.lang.annotation.Annotation in project feign by OpenFeign.

the class JAXRSContract method processAnnotationsOnParameter.

@Override
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex) {
    boolean isHttpParam = false;
    for (Annotation parameterAnnotation : annotations) {
        Class<? extends Annotation> annotationType = parameterAnnotation.annotationType();
        if (annotationType == PathParam.class) {
            String name = PathParam.class.cast(parameterAnnotation).value();
            checkState(emptyToNull(name) != null, "PathParam.value() was empty on parameter %s", paramIndex);
            nameParam(data, name, paramIndex);
            isHttpParam = true;
        } else if (annotationType == QueryParam.class) {
            String name = QueryParam.class.cast(parameterAnnotation).value();
            checkState(emptyToNull(name) != null, "QueryParam.value() was empty on parameter %s", paramIndex);
            Collection<String> query = addTemplatedParam(data.template().queries().get(name), name);
            data.template().query(name, query);
            nameParam(data, name, paramIndex);
            isHttpParam = true;
        } else if (annotationType == HeaderParam.class) {
            String name = HeaderParam.class.cast(parameterAnnotation).value();
            checkState(emptyToNull(name) != null, "HeaderParam.value() was empty on parameter %s", paramIndex);
            Collection<String> header = addTemplatedParam(data.template().headers().get(name), name);
            data.template().header(name, header);
            nameParam(data, name, paramIndex);
            isHttpParam = true;
        } else if (annotationType == FormParam.class) {
            String name = FormParam.class.cast(parameterAnnotation).value();
            checkState(emptyToNull(name) != null, "FormParam.value() was empty on parameter %s", paramIndex);
            data.formParams().add(name);
            nameParam(data, name, paramIndex);
            isHttpParam = true;
        }
    }
    return isHttpParam;
}
Also used : HeaderParam(javax.ws.rs.HeaderParam) QueryParam(javax.ws.rs.QueryParam) Collection(java.util.Collection) PathParam(javax.ws.rs.PathParam) FormParam(javax.ws.rs.FormParam) Annotation(java.lang.annotation.Annotation)

Example 8 with Annotation

use of java.lang.annotation.Annotation in project jersey by jersey.

the class WebResourceFactory method invoke.

@Override
@SuppressWarnings("unchecked")
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (args == null && method.getName().equals("toString")) {
        return toString();
    }
    if (args == null && method.getName().equals("hashCode")) {
        //unique instance in the JVM, and no need to override
        return hashCode();
    }
    if (args != null && args.length == 1 && method.getName().equals("equals")) {
        //unique instance in the JVM, and no need to override
        return equals(args[0]);
    }
    // get the interface describing the resource
    final Class<?> proxyIfc = proxy.getClass().getInterfaces()[0];
    // response type
    final Class<?> responseType = method.getReturnType();
    // determine method name
    String httpMethod = getHttpMethodName(method);
    if (httpMethod == null) {
        for (final Annotation ann : method.getAnnotations()) {
            httpMethod = getHttpMethodName(ann.annotationType());
            if (httpMethod != null) {
                break;
            }
        }
    }
    // create a new UriBuilder appending the @Path attached to the method
    WebTarget newTarget = addPathFromAnnotation(method, target);
    if (httpMethod == null) {
        if (newTarget == target) {
            // no path annotation on the method -> fail
            throw new UnsupportedOperationException("Not a resource method.");
        } else if (!responseType.isInterface()) {
            // not interface - can't help here
            throw new UnsupportedOperationException("Return type not an interface");
        }
    }
    // process method params (build maps of (Path|Form|Cookie|Matrix|Header..)Params
    // and extract entity type
    final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<String, Object>(this.headers);
    final LinkedList<Cookie> cookies = new LinkedList<>(this.cookies);
    final Form form = new Form();
    form.asMap().putAll(this.form.asMap());
    final Annotation[][] paramAnns = method.getParameterAnnotations();
    Object entity = null;
    Type entityType = null;
    for (int i = 0; i < paramAnns.length; i++) {
        final Map<Class, Annotation> anns = new HashMap<>();
        for (final Annotation ann : paramAnns[i]) {
            anns.put(ann.annotationType(), ann);
        }
        Annotation ann;
        Object value = args[i];
        if (!hasAnyParamAnnotation(anns)) {
            entityType = method.getGenericParameterTypes()[i];
            entity = value;
        } else {
            if (value == null && (ann = anns.get(DefaultValue.class)) != null) {
                value = ((DefaultValue) ann).value();
            }
            if (value != null) {
                if ((ann = anns.get(PathParam.class)) != null) {
                    newTarget = newTarget.resolveTemplate(((PathParam) ann).value(), value);
                } else if ((ann = anns.get((QueryParam.class))) != null) {
                    if (value instanceof Collection) {
                        newTarget = newTarget.queryParam(((QueryParam) ann).value(), convert((Collection) value));
                    } else {
                        newTarget = newTarget.queryParam(((QueryParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((HeaderParam.class))) != null) {
                    if (value instanceof Collection) {
                        headers.addAll(((HeaderParam) ann).value(), convert((Collection) value));
                    } else {
                        headers.addAll(((HeaderParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((CookieParam.class))) != null) {
                    final String name = ((CookieParam) ann).value();
                    Cookie c;
                    if (value instanceof Collection) {
                        for (final Object v : ((Collection) value)) {
                            if (!(v instanceof Cookie)) {
                                c = new Cookie(name, v.toString());
                            } else {
                                c = (Cookie) v;
                                if (!name.equals(((Cookie) v).getName())) {
                                    // is this the right thing to do? or should I fail? or ignore the difference?
                                    c = new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion());
                                }
                            }
                            cookies.add(c);
                        }
                    } else {
                        if (!(value instanceof Cookie)) {
                            cookies.add(new Cookie(name, value.toString()));
                        } else {
                            c = (Cookie) value;
                            if (!name.equals(((Cookie) value).getName())) {
                                // is this the right thing to do? or should I fail? or ignore the difference?
                                cookies.add(new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion()));
                            }
                        }
                    }
                } else if ((ann = anns.get((MatrixParam.class))) != null) {
                    if (value instanceof Collection) {
                        newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), convert((Collection) value));
                    } else {
                        newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((FormParam.class))) != null) {
                    if (value instanceof Collection) {
                        for (final Object v : ((Collection) value)) {
                            form.param(((FormParam) ann).value(), v.toString());
                        }
                    } else {
                        form.param(((FormParam) ann).value(), value.toString());
                    }
                }
            }
        }
    }
    if (httpMethod == null) {
        // the method is a subresource locator
        return WebResourceFactory.newResource(responseType, newTarget, true, headers, cookies, form);
    }
    // accepted media types
    Produces produces = method.getAnnotation(Produces.class);
    if (produces == null) {
        produces = proxyIfc.getAnnotation(Produces.class);
    }
    final String[] accepts = (produces == null) ? EMPTY : produces.value();
    // determine content type
    String contentType = null;
    if (entity != null) {
        final List<Object> contentTypeEntries = headers.get(HttpHeaders.CONTENT_TYPE);
        if ((contentTypeEntries != null) && (!contentTypeEntries.isEmpty())) {
            contentType = contentTypeEntries.get(0).toString();
        } else {
            Consumes consumes = method.getAnnotation(Consumes.class);
            if (consumes == null) {
                consumes = proxyIfc.getAnnotation(Consumes.class);
            }
            if (consumes != null && consumes.value().length > 0) {
                contentType = consumes.value()[0];
            }
        }
    }
    Invocation.Builder builder = newTarget.request().headers(// this resets all headers so do this first
    headers).accept(// if @Produces is defined, propagate values into Accept header; empty array is NO-OP
    accepts);
    for (final Cookie c : cookies) {
        builder = builder.cookie(c);
    }
    final Object result;
    if (entity == null && !form.asMap().isEmpty()) {
        entity = form;
        contentType = MediaType.APPLICATION_FORM_URLENCODED;
    } else {
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }
        if (!form.asMap().isEmpty()) {
            if (entity instanceof Form) {
                ((Form) entity).asMap().putAll(form.asMap());
            } else {
            // TODO: should at least log some warning here
            }
        }
    }
    final GenericType responseGenericType = new GenericType(method.getGenericReturnType());
    if (entity != null) {
        if (entityType instanceof ParameterizedType) {
            entity = new GenericEntity(entity, entityType);
        }
        result = builder.method(httpMethod, Entity.entity(entity, contentType), responseGenericType);
    } else {
        result = builder.method(httpMethod, responseGenericType);
    }
    return result;
}
Also used : MatrixParam(javax.ws.rs.MatrixParam) Invocation(javax.ws.rs.client.Invocation) Form(javax.ws.rs.core.Form) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ParameterizedType(java.lang.reflect.ParameterizedType) Consumes(javax.ws.rs.Consumes) PathParam(javax.ws.rs.PathParam) Cookie(javax.ws.rs.core.Cookie) GenericType(javax.ws.rs.core.GenericType) Annotation(java.lang.annotation.Annotation) LinkedList(java.util.LinkedList) CookieParam(javax.ws.rs.CookieParam) MediaType(javax.ws.rs.core.MediaType) GenericType(javax.ws.rs.core.GenericType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) QueryParam(javax.ws.rs.QueryParam) Produces(javax.ws.rs.Produces) GenericEntity(javax.ws.rs.core.GenericEntity) Collection(java.util.Collection) WebTarget(javax.ws.rs.client.WebTarget) FormParam(javax.ws.rs.FormParam)

Example 9 with Annotation

use of java.lang.annotation.Annotation in project jersey by jersey.

the class SecurityHelperTest method testFilteringScopesWithContext.

@Test
public void testFilteringScopesWithContext() throws Exception {
    final SecurityContext context = new TestSecurityContext();
    Annotation[] annotations;
    Set<String> expected;
    // Empty annotations.
    annotations = new Annotation[0];
    assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(Collections.<String>emptySet()));
    // Not security annotations.
    annotations = new Annotation[] { CustomAnnotationLiteral.INSTANCE, CustomAnnotationLiteral.INSTANCE };
    assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(Collections.<String>emptySet()));
    // Mixed.
    annotations = new Annotation[] { CustomAnnotationLiteral.INSTANCE, SecurityAnnotations.rolesAllowed("manager"), CustomAnnotationLiteral.INSTANCE };
    expected = Collections.singleton(RolesAllowed.class.getName() + "_manager");
    assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(expected));
    // Multiple.
    annotations = new Annotation[] { SecurityAnnotations.rolesAllowed("client", "user") };
    expected = Collections.singleton(RolesAllowed.class.getName() + "_user");
    assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(expected));
    // PermitAll weirdo.
    annotations = new Annotation[] { SecurityAnnotations.permitAll() };
    assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(FilteringHelper.getDefaultFilteringScope()));
    // DenyAll weirdo.
    annotations = new Annotation[] { SecurityAnnotations.denyAll() };
    assertThat(SecurityHelper.getFilteringScopes(context, annotations), equalTo(null));
}
Also used : RolesAllowed(javax.annotation.security.RolesAllowed) SecurityContext(javax.ws.rs.core.SecurityContext) Annotation(java.lang.annotation.Annotation) Test(org.junit.Test)

Example 10 with Annotation

use of java.lang.annotation.Annotation in project jersey by jersey.

the class InjectLinkFieldDescriptor method extractQueryParams.

private static CharSequence extractQueryParams(AnnotatedMethod method) throws SecurityException {
    // append query parameters
    StringBuilder querySubString = new StringBuilder();
    int parameterIndex = 0;
    for (Annotation[] paramAnns : method.getParameterAnnotations()) {
        for (Annotation ann : paramAnns) {
            if (ann.annotationType() == QueryParam.class) {
                querySubString.append(((QueryParam) ann).value());
                querySubString.append(',');
            }
            if (ann.annotationType() == BeanParam.class) {
                Class<?> beanParamType = method.getParameterTypes()[parameterIndex];
                Field[] fields = beanParamType.getFields();
                for (Field field : fields) {
                    QueryParam queryParam = field.getAnnotation(QueryParam.class);
                    if (queryParam != null) {
                        querySubString.append(queryParam.value());
                        querySubString.append(',');
                    }
                }
                Method[] beanMethods = beanParamType.getMethods();
                for (Method beanMethod : beanMethods) {
                    QueryParam queryParam = beanMethod.getAnnotation(QueryParam.class);
                    if (queryParam != null) {
                        querySubString.append(queryParam.value());
                        querySubString.append(',');
                    }
                }
            }
        }
        parameterIndex++;
    }
    CharSequence result = "";
    if (querySubString.length() > 0) {
        result = querySubString.subSequence(0, querySubString.length() - 1);
    }
    return result;
}
Also used : Field(java.lang.reflect.Field) QueryParam(javax.ws.rs.QueryParam) AnnotatedMethod(org.glassfish.jersey.server.model.AnnotatedMethod) HttpMethod(javax.ws.rs.HttpMethod) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation)

Aggregations

Annotation (java.lang.annotation.Annotation)1784 Method (java.lang.reflect.Method)412 ArrayList (java.util.ArrayList)245 Field (java.lang.reflect.Field)172 Test (org.junit.Test)164 Type (java.lang.reflect.Type)149 HashMap (java.util.HashMap)146 HashSet (java.util.HashSet)129 Map (java.util.Map)95 List (java.util.List)92 IOException (java.io.IOException)71 Set (java.util.Set)71 ParameterizedType (java.lang.reflect.ParameterizedType)62 InvocationTargetException (java.lang.reflect.InvocationTargetException)53 Collection (java.util.Collection)52 LinkedHashMap (java.util.LinkedHashMap)36 Collectors (java.util.stream.Collectors)36 Constructor (java.lang.reflect.Constructor)33 LinkedHashSet (java.util.LinkedHashSet)32 Optional (java.util.Optional)32