Java Code Examples for org.apache.cxf.jaxrs.utils.InjectionUtils#getActualType()

The following examples show how to use org.apache.cxf.jaxrs.utils.InjectionUtils#getActualType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AtomPojoProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void setFeedFromCollection(Factory factory,
                                     Feed feed,
                                     Object wrapper,
                                     Class<?> wrapperCls,
                                     Object collection,
                                     Class<?> collectionCls,
                                     Type collectionType,
                                     boolean writerUsed) throws Exception {
//CHECKSTYLE:ON
    Object[] arr = collectionCls.isArray() ? (Object[])collection : ((Collection<?>)collection).toArray();
    Class<?> memberClass = InjectionUtils.getActualType(collectionType);

    for (Object o : arr) {
        Entry entry = createEntryFromObject(factory, o, memberClass);
        feed.addEntry(entry);
    }
    if (!writerUsed) {
        setFeedProperties(factory, feed, wrapper, wrapperCls, collection, collectionCls, collectionType);
    }
}
 
Example 2
Source File: ProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> ContextProvider<T> createContextProvider(Type contextType,
                                                    Message m) {
    Class<?> contextCls = InjectionUtils.getActualType(contextType);
    if (contextCls == null) {
        return null;
    }
    for (ProviderInfo<ContextProvider<?>> cr : contextProviders) {
        Type[] types = cr.getProvider().getClass().getGenericInterfaces();
        for (Type t : types) {
            if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType)t;
                Type[] args = pt.getActualTypeArguments();
                if (args.length > 0) {
                    Class<?> argCls = InjectionUtils.getActualType(args[0]);

                    if (argCls != null && argCls.isAssignableFrom(contextCls)) {
                        return (ContextProvider<T>)cr.getProvider();
                    }
                }
            }
        }
    }
    return null;
}
 
Example 3
Source File: ProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected static int compareClasses(Class<?> expectedCls, Object o1, Object o2) {
    Class<?> cl1 = ClassHelper.getRealClass(o1);
    Class<?> cl2 = ClassHelper.getRealClass(o2);
    Type[] types1 = getGenericInterfaces(cl1, expectedCls);
    Type[] types2 = getGenericInterfaces(cl2, expectedCls);
    if (types1.length == 0 && types2.length == 0) {
        return 0;
    } else if (types1.length == 0 && types2.length > 0) {
        return 1;
    } else if (types1.length > 0 && types2.length == 0) {
        return -1;
    }

    Class<?> realClass1 = InjectionUtils.getActualType(types1[0]);
    Class<?> realClass2 = InjectionUtils.getActualType(types2[0]);
    if (realClass1 == realClass2) {
        return 0;
    }
    if (realClass1.isAssignableFrom(realClass2)) {
        // subclass should go first
        return 1;
    }
    return -1;
}
 
Example 4
Source File: ProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static Type[] getGenericInterfaces(Class<?> cls, Class<?> expectedClass,
                                           Class<?> commonBaseCls) {
    if (Object.class == cls) {
        return new Type[]{};
    }
    if (expectedClass != null) {
        Type genericSuperType = cls.getGenericSuperclass();
        if (genericSuperType instanceof ParameterizedType) {
            Class<?> actualType = InjectionUtils.getActualType(genericSuperType);
            if (actualType != null && actualType.isAssignableFrom(expectedClass)) {
                return new Type[]{genericSuperType};
            } else if (commonBaseCls != null && commonBaseCls != Object.class
                       && commonBaseCls.isAssignableFrom(expectedClass)
                       && commonBaseCls.isAssignableFrom(actualType)
                       || expectedClass.isAssignableFrom(actualType)) {
                return new Type[]{};
            }
        }
    }
    Type[] types = cls.getGenericInterfaces();
    if (types.length > 0) {
        return types;
    }
    return getGenericInterfaces(cls.getSuperclass(), expectedClass, commonBaseCls);
}
 
Example 5
Source File: BookServer20.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    if (responseContext.getMediaType() != null) {
        String ct = responseContext.getMediaType().toString();
        if (requestContext.getProperty("filterexception") != null) {
            if (!"text/plain".equals(ct)) {
                throw new RuntimeException();
            }
            responseContext.getHeaders().putSingle("FilterException",
                                                   requestContext.getProperty("filterexception"));
        }
    
        Object entity = responseContext.getEntity();
        Type entityType = responseContext.getEntityType();
        if (entity instanceof GenericHandler && InjectionUtils.getActualType(entityType) == Book.class) {
            ct += ";charset=ISO-8859-1";
            if ("getGenericBook2".equals(rInfo.getResourceMethod().getName())) {
                Annotation[] anns = responseContext.getEntityAnnotations();
                if (anns.length == 4 && anns[3].annotationType() == Context.class) {
                    responseContext.getHeaders().addFirst("Annotations", "OK");
                }
            } else {
                responseContext.setEntity(new Book("book", 124L));
            }
        } else {
            ct += ";charset=";
        }
        responseContext.getHeaders().putSingle("Content-Type", ct);
        responseContext.getHeaders().add("Response", "OK");
    }
}
 
Example 6
Source File: AtomPojoProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Object readFromFeedOrEntry(Class<Object> cls, MediaType mt,
                       MultivaluedMap<String, String> headers, InputStream is)
    throws IOException {

    AtomFeedProvider p = new AtomFeedProvider();
    p.setAutodetectCharset(autodetectCharset);
    Object atomObject = p.readFrom(Feed.class, Feed.class, new Annotation[]{}, mt, headers, is);
    if (atomObject instanceof Entry) {
        return this.readFromEntry((Entry)atomObject, cls);
    }

    Feed feed = (Feed)atomObject;
    AtomElementReader<?, ?> reader = getAtomReader(cls);
    if (reader != null) {
        return ((AtomElementReader<Feed, Object>)reader).readFrom(feed);
    }
    Object instance = null;
    try {
        String methodName = getCollectionMethod(cls, false);
        Method m = cls.getMethod(methodName, new Class[]{List.class});
        Class<Object> realCls
            = (Class<Object>)InjectionUtils.getActualType(m.getGenericParameterTypes()[0]);
        List<Object> objects = new ArrayList<>();
        for (Entry e : feed.getEntries()) {
            objects.add(readFromEntry(e, realCls));
        }
        instance = cls.newInstance();
        m.invoke(instance, new Object[]{objects});

    } catch (Exception ex) {
        reportError("Object of type " + cls.getName() + " can not be deserialized from Feed", ex, 400);
    }
    return instance;
}
 
Example 7
Source File: MicroProfileClientProxyImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected Class<?> getReturnType(Method method, Message outMessage) {
    Class<?> returnType = super.getReturnType(method, outMessage);
    if (CompletionStage.class.isAssignableFrom(returnType)) {
        Type t = method.getGenericReturnType();
        returnType = InjectionUtils.getActualType(t);
    }
    return returnType;
}
 
Example 8
Source File: StreamingResponseProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(StreamingResponse<T> p, Class<?> cls, Type t, Annotation[] anns,
                    MediaType mt, MultivaluedMap<String, Object> headers, OutputStream os)
    throws IOException, WebApplicationException {
    Class<?> actualCls = InjectionUtils.getActualType(t);
    if (cls == actualCls) {
        actualCls = Object.class;
    }
    //TODO: review the possibility of caching the providers
    StreamingResponseWriter thewriter = new StreamingResponseWriter(actualCls, anns, mt, headers, os);
    p.writeTo(thewriter);
}
 
Example 9
Source File: MultipartProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Class<?> getActualType(Type type, int pos) {
    Class<?> actual = null;
    try {
        actual = InjectionUtils.getActualType(type, pos);
    } catch (Exception ex) {
        // ignore;
    }
    return actual != null && actual != Object.class ? actual : Attachment.class;
}
 
Example 10
Source File: AbstractJAXBProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Class<?> getActualType(Class<?> type, Type genericType, Annotation[] anns) {
    Class<?> theType = null;
    if (JAXBElement.class.isAssignableFrom(type)) {
        theType = InjectionUtils.getActualType(genericType);
    } else {
        theType = type;
    }
    XmlJavaTypeAdapter adapter = org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(theType, anns);
    theType = org.apache.cxf.jaxrs.utils.JAXBUtils.getTypeFromAdapter(adapter, theType, false);

    return theType;
}
 
Example 11
Source File: AbstractJAXBProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public boolean isReadable(Class<?> type, Type genericType, Annotation[] anns, MediaType mt) {
    if (InjectionUtils.isSupportedCollectionOrArray(type)) {
        type = InjectionUtils.getActualType(genericType);
        if (type == null) {
            return false;
        }
    }
    return canBeReadAsJaxbElement(type) || isSupported(type, genericType, anns);
}
 
Example 12
Source File: AbstractJAXBProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] anns, MediaType mt) {

        if (InjectionUtils.isSupportedCollectionOrArray(type)) {
            type = InjectionUtils.getActualType(genericType);
            if (type == null) {
                return false;
            }
        }
        return marshalAsJaxbElement && (!xmlTypeAsJaxbElementOnly || isXmlType(type))
            || isSupported(type, genericType, anns);
    }
 
Example 13
Source File: JAXBElementProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void marshalCollection(Class<?> originalCls, Object collection,
                                 Type genericType, String enc, OutputStream os,
                                 MediaType m, Annotation[] anns)
    throws Exception {

    Class<?> actualClass = InjectionUtils.getActualType(genericType);
    actualClass = getActualType(actualClass, genericType, anns);

    Collection<?> c = originalCls.isArray() ? Arrays.asList((Object[]) collection)
                                         : (Collection<?>) collection;

    Iterator<?> it = c.iterator();

    Object firstObj = it.hasNext() ? it.next() : null;

    QName qname = null;
    if (firstObj instanceof JAXBElement) {
        JAXBElement<?> el = (JAXBElement<?>)firstObj;
        qname = el.getName();
        actualClass = el.getDeclaredType();
    } else {
        qname = getCollectionWrapperQName(actualClass, genericType, firstObj, true);
    }
    if (qname == null) {
        String message = new org.apache.cxf.common.i18n.Message("NO_COLLECTION_ROOT",
                                                                BUNDLE).toString();
        throw new WebApplicationException(Response.serverError()
                                          .entity(message).build());
    }

    StringBuilder pi = new StringBuilder();
    pi.append(XML_PI_START + (enc == null ? StandardCharsets.UTF_8.name() : enc) + "\"?>");
    os.write(pi.toString().getBytes());
    String startTag = null;
    String endTag = null;

    if (qname.getNamespaceURI().length() > 0) {
        String prefix = nsPrefixes.get(qname.getNamespaceURI());
        if (prefix == null) {
            prefix = "ns1";
        }
        startTag = "<" + prefix + ":" + qname.getLocalPart() + " xmlns:" + prefix + "=\""
            + qname.getNamespaceURI() + "\">";
        endTag = "</" + prefix + ":" + qname.getLocalPart() + ">";
    } else {
        startTag = "<" + qname.getLocalPart() + ">";
        endTag = "</" + qname.getLocalPart() + ">";
    }
    os.write(startTag.getBytes());
    if (firstObj != null) {
        XmlJavaTypeAdapter adapter =
            org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(firstObj.getClass(), anns);
        marshalCollectionMember(JAXBUtils.useAdapter(firstObj, adapter, true),
                                actualClass, genericType, enc, os, anns, m,
                                qname.getNamespaceURI());
        while (it.hasNext()) {
            marshalCollectionMember(JAXBUtils.useAdapter(it.next(), adapter, true), actualClass,
                                    genericType, enc, os, anns, m,
                                    qname.getNamespaceURI());
        }
    }
    os.write(endTag.getBytes());
}
 
Example 14
Source File: WadlGenerator.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void handleRepresentation(StringBuilder sb, Set<Class<?>> jaxbTypes,
                                    ElementQNameResolver qnameResolver, Map<Class<?>, QName> clsMap,
                                    OperationResourceInfo ori, Class<?> type, boolean isJson,
                                    boolean inbound) {
    // CHECKSTYLE:ON
    List<MediaType> types = inbound ? ori.getConsumeTypes() : ori.getProduceTypes();
    if (MultivaluedMap.class.isAssignableFrom(type)) {
        types = Collections.singletonList(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    } else if (isWildcard(types)) {
        types = Collections.singletonList(defaultRepMediaType);
    }

    Method opMethod = getMethod(ori);
    boolean isPrimitive = InjectionUtils.isPrimitive(type) && !ori.isAsync();
    for (MediaType mt : types) {

        sb.append("<representation");
        sb.append(" mediaType=\"").append(JAXRSUtils.mediaTypeToString(mt)).append('"');
        if (isJson && !mt.getSubtype().contains("json")) {
            sb.append("/>");
            continue;
        }

        boolean allowDefault = true;
        String docCategory;
        Annotation[] anns;
        int inParamIndex = -1;
        Type genericType;
        if (inbound) {
            inParamIndex = getRequestBodyParam(ori).getIndex();
            anns = opMethod.getParameterAnnotations()[inParamIndex];
            if (!isDocAvailable(anns)) {
                anns = opMethod.getAnnotations();
            }
            docCategory = DocTarget.PARAM;
            genericType = opMethod.getGenericParameterTypes()[inParamIndex];
        } else {
            anns = opMethod.getAnnotations();
            docCategory = DocTarget.RETURN;
            allowDefault = false;
            genericType = opMethod.getGenericReturnType();
        }
        if (isPrimitive) {
            sb.append('>');
            Parameter p = inbound ? getRequestBodyParam(ori) : new Parameter(ParameterType.REQUEST_BODY,
                                                                             0, "result");
            doWriteParam(ori, sb, p, type, type, p.getName() == null ? "request" : p.getName(), anns, isJson);
            sb.append("</representation>");
        } else {
            boolean isCollection = InjectionUtils.isSupportedCollectionOrArray(type);
            Class<?> theActualType;
            if (isCollection) {
                theActualType = InjectionUtils.getActualType(genericType);
            } else {
                theActualType = ResourceUtils.getActualJaxbType(type, opMethod, inbound);
            }
            if (theActualType == Object.class && !(genericType instanceof Class)
                || genericType instanceof TypeVariable) {
                Type theType = InjectionUtils.processGenericTypeIfNeeded(
                    ori.getClassResourceInfo().getServiceClass(), Object.class, genericType);
                theActualType = InjectionUtils.getActualType(theType);
            }
            if (isJson) {
                sb.append(" element=\"").append(theActualType.getSimpleName()).append('"');
            } else if (qnameResolver != null
                       && (linkAnyMediaTypeToXmlSchema || mt.getSubtype().contains("xml"))
                       && jaxbTypes.contains(theActualType)) {
                generateQName(sb, qnameResolver, clsMap, theActualType, isCollection,
                              getBodyAnnotations(ori, inbound));
            }
            addDocsAndCloseElement(ori, inParamIndex, sb, anns, "representation",
                                   docCategory, allowDefault, isJson);
        }
    }

}
 
Example 15
Source File: GenericHandlerWriter.java    From cxf with Apache License 2.0 4 votes vote down vote up
public boolean isWriteable(Class<?> type, Type genericType,
                           Annotation[] annotations, MediaType mediaType) {
    return type == GenericHandler.class && InjectionUtils.getActualType(genericType) == Book.class;
}
 
Example 16
Source File: BookStore.java    From cxf with Apache License 2.0 4 votes vote down vote up
public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
    return List.class.isAssignableFrom(arg0)
        && String.class == InjectionUtils.getActualType(arg1);
}
 
Example 17
Source File: JSONProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void marshalCollection(Class<?> originalCls, Object collection,
                                 Type genericType, String encoding,
                                 OutputStream os, MediaType m, Annotation[] anns)
    throws Exception {

    Class<?> actualClass = InjectionUtils.getActualType(genericType);
    actualClass = getActualType(actualClass, genericType, anns);

    Collection<?> c = originalCls.isArray() ? Arrays.asList((Object[]) collection)
                                         : (Collection<?>) collection;

    Iterator<?> it = c.iterator();

    Object firstObj = it.hasNext() ? it.next() : null;

    String startTag = null;
    String endTag = null;
    if (!dropCollectionWrapperElement) {
        QName qname = null;
        if (firstObj instanceof JAXBElement) {
            JAXBElement<?> el = (JAXBElement<?>)firstObj;
            qname = el.getName();
            actualClass = el.getDeclaredType();
        } else {
            qname = getCollectionWrapperQName(actualClass, genericType, firstObj, false);
        }
        String prefix = "";
        if (!ignoreNamespaces) {
            prefix = namespaceMap.get(qname.getNamespaceURI());
            if (prefix != null) {
                if (prefix.length() > 0) {
                    prefix += ".";
                }
            } else if (qname.getNamespaceURI().length() > 0) {
                prefix = "ns1.";
            }
        }
        prefix = (prefix == null) ? "" : prefix;
        startTag = "{\"" + prefix + qname.getLocalPart() + "\":[";
        endTag = "]}";
    } else if (serializeAsArray) {
        startTag = "[";
        endTag = "]";
    } else {
        startTag = "{";
        endTag = "}";
    }

    os.write(startTag.getBytes());
    if (firstObj != null) {
        XmlJavaTypeAdapter adapter =
            org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(firstObj.getClass(), anns);
        marshalCollectionMember(JAXBUtils.useAdapter(firstObj, adapter, true),
                                actualClass, genericType, encoding, os);
        while (it.hasNext()) {
            os.write(",".getBytes());
            marshalCollectionMember(JAXBUtils.useAdapter(it.next(), adapter, true),
                                    actualClass, genericType, encoding, os);
        }
    }
    os.write(endTag.getBytes());
}
 
Example 18
Source File: BookStore.java    From cxf with Apache License 2.0 4 votes vote down vote up
public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
    return List.class.isAssignableFrom(arg0)
        && String.class == InjectionUtils.getActualType(arg1);
}
 
Example 19
Source File: JSONProvider.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void marshalCollection(Class<?> originalCls, Object collection, 
                                    Type genericType, String encoding, 
                                    OutputStream os, MediaType m, Annotation[] anns) throws Exception {
       Class<?> actualClass = InjectionUtils.getActualType(genericType);
       actualClass = getActualType(actualClass, genericType, anns);
       Collection<?> c = originalCls.isArray() ? Arrays.asList((Object[]) collection) 
                                            : (Collection<?>) collection;
       Iterator<?> it = c.iterator();
       Object firstObj = it.hasNext() ? it.next() : null;
       String startTag = null;
       String endTag = null;
       if (!dropCollectionWrapperElement) {
           QName qname = null;
           if (firstObj instanceof JAXBElement) {
               JAXBElement<?> el = (JAXBElement<?>)firstObj;
               qname = el.getName();
               actualClass = el.getDeclaredType();
           } else {
               qname = getCollectionWrapperQName(actualClass, genericType, firstObj, false);
           }
           String prefix = "";
           if (!ignoreNamespaces) {
               prefix = namespaceMap.get(qname.getNamespaceURI());
               if (prefix != null) {
                   if (prefix.length() > 0) {
                       prefix += ".";
                   }
               } else if (qname.getNamespaceURI().length() > 0) {
                   prefix = "ns1.";
               }
           }
           prefix = (prefix == null) ? "" : prefix;
           startTag = "{\"" + prefix + qname.getLocalPart() + "\":[";
           endTag = "]}";
       } else if (serializeAsArray) {
           startTag = "[";
           endTag = "]";
       } else {
           startTag = "{";
           endTag = "}";
       }
       os.write(startTag.getBytes());
       if (firstObj != null) {
           XmlJavaTypeAdapter adapter = 
               org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(firstObj.getClass(), anns);
           marshalCollectionMember(JAXBUtils.useAdapter(firstObj, adapter, true),
                                   actualClass, genericType, encoding, os);
           while (it.hasNext()) {
               os.write(",".getBytes());
               marshalCollectionMember(JAXBUtils.useAdapter(it.next(), adapter, true), 
                                       actualClass, genericType, encoding, os);
           }
       }
       os.write(endTag.getBytes());
   }
 
Example 20
Source File: AbstractSearchConditionVisitor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
private ClassValue doGetPrimitiveFieldClass(PrimitiveStatement ps,
                                            String name, Class<?> valueCls, Type type, Object value,
                                            Set<String> set) {
    boolean isCollection = InjectionUtils.isSupportedCollectionOrArray(valueCls);
    Class<?> actualCls = isCollection ? InjectionUtils.getActualType(type) : valueCls;
    CollectionCheckInfo collInfo = null;
    int index = name.indexOf('.');
    if (index != -1) {
        String[] names = name.split("\\.");
        name = name.substring(index + 1);
        if (value != null && !InjectionUtils.isPrimitive(actualCls)) {
            try {
                String nextPart = StringUtils.capitalize(names[1]);

                Method m = actualCls.getMethod("get" + nextPart, new Class[]{});
                if (isCollection) {
                    value = ((Collection)value).iterator().next();
                    set.add(names[0]);
                }
                value = m.invoke(value, new Object[]{});
                valueCls = value.getClass();
                type = m.getGenericReturnType();
            } catch (Throwable ex) {
                throw new RuntimeException(ex);
            }
            return doGetPrimitiveFieldClass(ps, name, valueCls, type, value, set);
        }
    } else if (isCollection) {
        set.add(name);
        Collection coll = (Collection)value;
        value = coll.isEmpty() ? null : coll.iterator().next();
        valueCls = actualCls;
        if (ps instanceof CollectionCheckStatement) {
            collInfo = ((CollectionCheckStatement)ps).getCollectionCheckInfo();
        }
    }

    Class<?> cls = null;
    if (primitiveFieldTypeMap != null) {
        cls = primitiveFieldTypeMap.get(name);
    }
    if (cls == null) {
        cls = valueCls;
    }
    return new ClassValue(cls, value, collInfo, set);
}