Search in sources :

Example 31 with Type

use of java.lang.reflect.Type in project morphia by mongodb.

the class ReflectionUtils method getParameterizedClass.

/**
     * Get the class that parameterizes the Field supplied, at the index supplied (field can be parameterized with multiple param classes).
     *
     * @param field the field
     * @param index the index of the parameterizing class
     * @return the class that parameterizes the field, or null if field is not parameterized
     */
public static Class getParameterizedClass(final Field field, final int index) {
    if (field.getGenericType() instanceof ParameterizedType) {
        final ParameterizedType type = (ParameterizedType) field.getGenericType();
        if ((type.getActualTypeArguments() != null) && (type.getActualTypeArguments().length <= index)) {
            return null;
        }
        final Type paramType = type.getActualTypeArguments()[index];
        if (paramType instanceof GenericArrayType) {
            final Class arrayType = (Class) ((GenericArrayType) paramType).getGenericComponentType();
            return Array.newInstance(arrayType, 0).getClass();
        } else {
            if (paramType instanceof ParameterizedType) {
                final ParameterizedType paramPType = (ParameterizedType) paramType;
                return (Class) paramPType.getRawType();
            } else {
                if (paramType instanceof TypeVariable) {
                    // from the T/V/X
                    throw new MappingException("Generic Typed Class not supported:  <" + ((TypeVariable) paramType).getName() + "> = " + ((TypeVariable) paramType).getBounds()[0]);
                } else if (paramType instanceof Class) {
                    return (Class) paramType;
                } else {
                    throw new MappingException("Unknown type... pretty bad... call for help, wave your hands... yeah!");
                }
            }
        }
    }
    return getParameterizedClass(field.getType());
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) TypeVariable(java.lang.reflect.TypeVariable) GenericArrayType(java.lang.reflect.GenericArrayType) MappingException(org.mongodb.morphia.mapping.MappingException)

Example 32 with Type

use of java.lang.reflect.Type in project morphia by mongodb.

the class ReflectionUtils method getClass.

/**
     * Get the underlying class for a type, or null if the type is a variable type.
     *
     * @param type the type
     * @return the underlying class
     */
public static Class<?> getClass(final Type type) {
    if (type instanceof Class) {
        return (Class) type;
    } else if (type instanceof ParameterizedType) {
        return getClass(((ParameterizedType) type).getRawType());
    } else if (type instanceof GenericArrayType) {
        final Type componentType = ((GenericArrayType) type).getGenericComponentType();
        final Class<?> componentClass = getClass(componentType);
        if (componentClass != null) {
            return Array.newInstance(componentClass, 0).getClass();
        } else {
            LOG.debug("************ ReflectionUtils.getClass 1st else");
            LOG.debug("************ type = " + type);
            return null;
        }
    } else {
        LOG.debug("************ ReflectionUtils.getClass final else");
        LOG.debug("************ type = " + type);
        return null;
    }
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) GenericArrayType(java.lang.reflect.GenericArrayType)

Example 33 with Type

use of java.lang.reflect.Type in project jersey by jersey.

the class GenericMethodListTest method testGeneriInterfaceClasses.

@Test
public void testGeneriInterfaceClasses() {
    MethodList ml = new MethodList(IResource.class);
    Iterator<AnnotatedMethod> i = ml.iterator();
    assertTrue(i.hasNext());
    AnnotatedMethod am = i.next();
    Method m = am.getMethod();
    Type[] types = m.getGenericParameterTypes();
    assertTrue(types[0] instanceof TypeVariable);
    assertTrue(types[1] instanceof Class);
    assertTrue(types[2] instanceof TypeVariable);
}
Also used : Type(java.lang.reflect.Type) TypeVariable(java.lang.reflect.TypeVariable) Method(java.lang.reflect.Method) Test(org.junit.Test)

Example 34 with Type

use of java.lang.reflect.Type 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 35 with Type

use of java.lang.reflect.Type in project jersey by jersey.

the class NaiveResourceMappingContext method buildMappings.

private void buildMappings() {
    if (mappings != null) {
        return;
    }
    mappings = new HashMap<>();
    erc.getResourceModel().accept(new ResourceModelVisitor() {

        Deque<PathPattern> stack = new LinkedList<>();

        private void processComponents(final ResourceModelComponent component) {
            final List<? extends ResourceModelComponent> components = component.getComponents();
            if (components != null) {
                for (final ResourceModelComponent rc : components) {
                    rc.accept(this);
                }
            }
        }

        @Override
        public void visitInvocable(final Invocable invocable) {
            processComponents(invocable);
        }

        @Override
        public void visitRuntimeResource(final RuntimeResource runtimeResource) {
            processComponents(runtimeResource);
        }

        @Override
        public void visitResourceModel(final ResourceModel resourceModel) {
            processComponents(resourceModel);
        }

        @Override
        public void visitResourceHandlerConstructor(final HandlerConstructor handlerConstructor) {
            processComponents(handlerConstructor);
        }

        @Override
        public void visitMethodHandler(final MethodHandler methodHandler) {
            processComponents(methodHandler);
        }

        @Override
        public void visitChildResource(final Resource resource) {
            visitResourceIntl(resource, false);
        }

        @Override
        public void visitResource(final Resource resource) {
            visitResourceIntl(resource, true);
        }

        private void visitResourceIntl(final Resource resource, final boolean isRoot) {
            try {
                stack.addLast(resource.getPathPattern());
                processComponents(resource);
                if (isRoot) {
                    Class likelyToBeRoot = null;
                    for (final Class next : resource.getHandlerClasses()) {
                        if (!(Inflector.class.isAssignableFrom(next))) {
                            likelyToBeRoot = next;
                        }
                    }
                    if (likelyToBeRoot != null) {
                        mappings.put(likelyToBeRoot, getMapping(getTemplate()));
                    }
                }
            } finally {
                stack.removeLast();
            }
        }

        @Override
        public void visitResourceMethod(final ResourceMethod resourceMethod) {
            if (resourceMethod.isExtended()) {
                return;
            }
            if (ResourceMethod.JaxrsType.SUB_RESOURCE_LOCATOR.equals(resourceMethod.getType())) {
                if (resourceMethod.getInvocable() != null) {
                    final Invocable i = resourceMethod.getInvocable();
                    final Type type = i.getResponseType();
                    final StringBuilder template = getTemplate();
                    mappings.put((Class) type, getMapping(template));
                    // Process sub resources ?
                    Resource.Builder builder = Resource.builder(i.getRawResponseType());
                    if (builder == null) {
                        // for example in the case the return type of the sub resource locator is Object
                        builder = Resource.builder().path(resourceMethod.getParent().getPath());
                    }
                    final Resource subResource = builder.build();
                    visitChildResource(subResource);
                }
            }
            processComponents(resourceMethod);
        }

        private StringBuilder getTemplate() {
            final StringBuilder template = new StringBuilder();
            for (final PathPattern pp : stack) {
                final String ppTemplate = pp.getTemplate().getTemplate();
                final int tlength = template.length();
                if (tlength > 0) {
                    if (template.charAt(tlength - 1) == '/') {
                        if (ppTemplate.startsWith("/")) {
                            template.append(ppTemplate, 1, ppTemplate.length());
                        } else {
                            template.append(ppTemplate);
                        }
                    } else {
                        if (ppTemplate.startsWith("/")) {
                            template.append(ppTemplate);
                        } else {
                            template.append("/");
                            template.append(ppTemplate);
                        }
                    }
                } else {
                    template.append(ppTemplate);
                }
            }
            return template;
        }
    });
}
Also used : Inflector(org.glassfish.jersey.process.Inflector) Resource(org.glassfish.jersey.server.model.Resource) RuntimeResource(org.glassfish.jersey.server.model.RuntimeResource) ResourceModelComponent(org.glassfish.jersey.server.model.ResourceModelComponent) LinkedList(java.util.LinkedList) RuntimeResource(org.glassfish.jersey.server.model.RuntimeResource) Invocable(org.glassfish.jersey.server.model.Invocable) PathPattern(org.glassfish.jersey.uri.PathPattern) HandlerConstructor(org.glassfish.jersey.server.model.HandlerConstructor) MethodHandler(org.glassfish.jersey.server.model.MethodHandler) Type(java.lang.reflect.Type) ResourceModelVisitor(org.glassfish.jersey.server.model.ResourceModelVisitor) ResourceModel(org.glassfish.jersey.server.model.ResourceModel) List(java.util.List) LinkedList(java.util.LinkedList) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod)

Aggregations

Type (java.lang.reflect.Type)6477 ParameterizedType (java.lang.reflect.ParameterizedType)1798 ProgressRequestBody (io.kubernetes.client.ProgressRequestBody)722 ProgressResponseBody (io.kubernetes.client.ProgressResponseBody)722 GenericArrayType (java.lang.reflect.GenericArrayType)711 WildcardType (java.lang.reflect.WildcardType)580 Test (org.junit.Test)513 ArrayList (java.util.ArrayList)429 Method (java.lang.reflect.Method)424 TypeVariable (java.lang.reflect.TypeVariable)350 List (java.util.List)342 Map (java.util.Map)296 Gson (com.google.gson.Gson)230 V1Status (io.kubernetes.client.models.V1Status)228 V1Status (io.kubernetes.client.openapi.models.V1Status)224 HashMap (java.util.HashMap)211 Field (java.lang.reflect.Field)170 Annotation (java.lang.annotation.Annotation)161 IOException (java.io.IOException)146 Collection (java.util.Collection)116