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

The following examples show how to use org.apache.cxf.jaxrs.utils.InjectionUtils#isPrimitive() . 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: JAXRSServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void createMessagePartInfo(OperationInfo oi, Class<?> type, QName qname, Method m,
                                   boolean input) {
    if (type == void.class || Source.class.isAssignableFrom(type)) {
        return;
    }
    if (InjectionUtils.isPrimitive(type) || Response.class == type) {
        return;
    }
    QName mName = new QName(qname.getNamespaceURI(),
                            (input ? "in" : "out") + m.getName());
    MessageInfo ms = oi.createMessage(mName,
                                       input ? MessageInfo.Type.INPUT : MessageInfo.Type.OUTPUT);
    if (input) {
        oi.setInput("in", ms);
    } else {
        oi.setOutput("out", ms);
    }
    QName mpQName = JAXRSUtils.getClassQName(type);
    MessagePartInfo mpi = ms.addMessagePart(mpQName);
    mpi.setConcreteName(mpQName);
    mpi.setTypeQName(mpQName);
    mpi.setTypeClass(type);
}
 
Example 2
Source File: XMLSource.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Find the list of matching XML nodes and convert them into
 * an array of instances of the provided class.
 * The default JAXB MessageBodyReader is currently used  in case of non-primitive types.
 *
 * @param expression XPath expression
 * @param namespaces the namespaces map, prefixes which are used in the XPath expression
 *        are the keys, namespace URIs are the values; note, the prefixes do not have to match
 *        the actual ones used in the XML instance.
 * @param cls class of the node
 * @return the array of instances representing the matching nodes
 */
@SuppressWarnings("unchecked")
public <T> T[] getNodes(String expression, Map<String, String> namespaces, Class<T> cls) {

    NodeList nodes = (NodeList)evaluate(expression, namespaces, XPathConstants.NODESET);
    if (nodes == null || nodes.getLength() == 0) {
        return null;
    }
    T[] values = (T[])Array.newInstance(cls, nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (InjectionUtils.isPrimitive(cls)) {
            values[i] = (T)readPrimitiveValue(node, cls);
        } else {
            values[i] = readNode(node, cls);
        }
    }
    return values;
}
 
Example 3
Source File: SimpleTypeJsonProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                    MultivaluedMap<String, Object> headers, OutputStream os)
    throws IOException, WebApplicationException {
    if (!supportSimpleTypesOnly && !InjectionUtils.isPrimitive(type)) {
        @SuppressWarnings("unchecked")
        MessageBodyWriter<T> next =
            (MessageBodyWriter<T>)providers.getMessageBodyWriter(type, genericType, annotations, mediaType);
        JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);
        try {
            next.writeTo(t, type, genericType, annotations, mediaType, headers, os);
        } finally {
            JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
        }
    } else {
        os.write(StringUtils.toBytesASCII("{\"" + type.getSimpleName().toLowerCase() + "\":"));
        writeQuote(os, type);
        primitiveHelper.writeTo(t, type, genericType, annotations, mediaType, headers, os);
        writeQuote(os, type);
        os.write(StringUtils.toBytesASCII("}"));
    }
}
 
Example 4
Source File: SimpleTypeJsonProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                  MultivaluedMap<String, String> headers, InputStream is)
    throws IOException, WebApplicationException {
    if (!supportSimpleTypesOnly && !InjectionUtils.isPrimitive(type)) {
        MessageBodyReader<T> next =
            providers.getMessageBodyReader(type, genericType, annotations, mediaType);
        JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);
        try {
            return next.readFrom(type, genericType, annotations, mediaType, headers, is);
        } finally {
            JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
        }
    }
    String data = IOUtils.toString(is).trim();
    int index = data.indexOf(':');
    data = data.substring(index + 1, data.length() - 1).trim();
    if (data.startsWith("\"")) {
        data = data.substring(1, data.length() - 1);
    }
    return primitiveHelper.readFrom(type, genericType, annotations, mediaType, headers,
                                    new ByteArrayInputStream(StringUtils.toBytesUTF8(data)));
}
 
Example 5
Source File: PrimitiveSearchCondition.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected static Object getPrimitiveValue(String name, Object value) {

        int index = name.indexOf('.');
        if (index != -1) {
            String[] names = name.split("\\.");
            name = name.substring(index + 1);
            if (value != null && !InjectionUtils.isPrimitive(value.getClass())) {
                try {
                    String nextPart = StringUtils.capitalize(names[1]);
                    Method m = value.getClass().getMethod("get" + nextPart, new Class[]{});
                    value = m.invoke(value, new Object[]{});
                } catch (Throwable ex) {
                    throw new RuntimeException();
                }
            }
            return getPrimitiveValue(name, value);
        }
        return value;

    }
 
Example 6
Source File: AbstractSearchConditionParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
private CollectionCheck getCollectionCheck(String propName, boolean isCollection, Class<?> actualCls) {
    if (isCollection) {
        if (InjectionUtils.isPrimitive(actualCls)) {
            if (isCount(propName)) {
                return CollectionCheck.SIZE;
            }
        } else {
            return CollectionCheck.SIZE;
        }
    }
    return null;
}
 
Example 7
Source File: SearchContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public <T> SearchCondition<T> getCondition(String expression,
                                           Class<T> cls,
                                           Map<String, String> beanProperties,
                                           Map<String, String> parserProperties) {
    if (InjectionUtils.isPrimitive(cls)) {
        String errorMessage = "Primitive condition types are not supported";
        LOG.warning(errorMessage);
        throw new IllegalArgumentException(errorMessage);
    }

    SearchConditionParser<T> parser = getParser(cls, beanProperties, parserProperties);

    String theExpression = expression == null
        ? getSearchExpression() : expression;
    if (theExpression != null) {
        try {
            return parser.parse(theExpression);
        } catch (SearchParseException ex) {
            if (PropertyUtils.isTrue(message.getContextualProperty(BLOCK_SEARCH_EXCEPTION))) {
                return null;
            }
            throw ex;
        }
    }
    return null;

}
 
Example 8
Source File: WadlGenerator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doWriteBeanParam(OperationResourceInfo ori,
                              StringBuilder sb,
                              Class<?> type,
                              Parameter pm,
                              String parentName,
                              List<Class<?>> parentBeanClasses,
                              boolean isJson) {
    Map<Parameter, Class<?>> pms = InjectionUtils.getParametersFromBeanClass(type, pm.getType(), true);
    for (Map.Entry<Parameter, Class<?>> entry : pms.entrySet()) {
        String name = entry.getKey().getName();
        if (parentName != null) {
            name = parentName + "." + name;
        }
        Class<?> paramCls = entry.getValue();
        boolean isPrimitive = InjectionUtils.isPrimitive(paramCls) || paramCls.isEnum();
        if (isPrimitive
            || Date.class.isAssignableFrom(paramCls)
            || XMLGregorianCalendar.class.isAssignableFrom(paramCls)
            || InjectionUtils.isSupportedCollectionOrArray(paramCls)) {
            doWriteParam(ori, sb, entry.getKey(), paramCls, paramCls, name, new Annotation[] {}, isJson);
        } else if (!parentBeanClasses.contains(paramCls)) {
            parentBeanClasses.add(paramCls);
            doWriteBeanParam(ori, sb, paramCls, entry.getKey(), name, parentBeanClasses, isJson);
            parentBeanClasses.remove(paramCls);
        }
    }
}
 
Example 9
Source File: ClientProxyImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected MultivaluedMap<String, String> setRequestHeaders(MultivaluedMap<String, String> headers,
                                                         OperationResourceInfo ori,
                                                         boolean formParams,
                                                         Class<?> bodyClass,
                                                         Class<?> responseClass) {
    if (headers.getFirst(HttpHeaders.CONTENT_TYPE) == null) {
        if (formParams || bodyClass != null && MultivaluedMap.class.isAssignableFrom(bodyClass)) {
            headers.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
        } else {
            String ctType = null;
            List<MediaType> consumeTypes = ori.getConsumeTypes();
            if (!consumeTypes.isEmpty() && !consumeTypes.get(0).equals(MediaType.WILDCARD_TYPE)) {
                ctType = JAXRSUtils.mediaTypeToString(ori.getConsumeTypes().get(0));
            }
            if (ctType != null) {
                headers.putSingle(HttpHeaders.CONTENT_TYPE, ctType);
            }
        }
    }

    List<MediaType> accepts = getAccept(headers);
    if (accepts == null) {
        if (responseClass == Void.class || responseClass == Void.TYPE) {
            accepts = Collections.singletonList(MediaType.WILDCARD_TYPE);
        } else {
            List<MediaType> produceTypes = ori.getProduceTypes();
            boolean produceWildcard = produceTypes.isEmpty()
                || produceTypes.get(0).equals(MediaType.WILDCARD_TYPE);
            if (produceWildcard) {
                accepts = InjectionUtils.isPrimitive(responseClass)
                    ? Collections.singletonList(MediaType.TEXT_PLAIN_TYPE)
                    : Collections.singletonList(MediaType.APPLICATION_XML_TYPE);
            } else {
                accepts = produceTypes;
            }
        }

        for (MediaType mt : accepts) {
            headers.add(HttpHeaders.ACCEPT, JAXRSUtils.mediaTypeToString(mt));
        }
    }

    return headers;
}
 
Example 10
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);
}
 
Example 11
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 12
Source File: WadlGenerator.java    From cxf with Apache License 2.0 4 votes vote down vote up
private boolean isFormParameter(Parameter pm, Class<?> type, Annotation[] anns) {
    return ParameterType.FORM == pm.getType() || ParameterType.REQUEST_BODY == pm.getType()
           && AnnotationUtils.getAnnotation(anns, Multipart.class) != null
           && (InjectionUtils.isPrimitive(type) || type == InputStream.class);
}