Search in sources :

Example 41 with MediaType

use of org.springframework.http.MediaType in project spring-framework by spring-projects.

the class ProtobufHttpMessageConverter method writeInternal.

@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    MediaType contentType = outputMessage.getHeaders().getContentType();
    if (contentType == null) {
        contentType = getDefaultContentType(message);
    }
    Charset charset = contentType.getCharset();
    if (charset == null) {
        charset = DEFAULT_CHARSET;
    }
    if (PROTOBUF.isCompatibleWith(contentType)) {
        setProtoHeader(outputMessage, message);
        CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputMessage.getBody());
        message.writeTo(codedOutputStream);
        codedOutputStream.flush();
    } else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) {
        final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
        TextFormat.print(message, outputStreamWriter);
        outputStreamWriter.flush();
        outputMessage.getBody().flush();
    } else if (isProtobufJavaUtilPresent || isProtobufJavaFormatPresent) {
        this.protobufFormatsSupport.print(message, outputMessage.getBody(), contentType, charset);
        outputMessage.getBody().flush();
    }
}
Also used : CodedOutputStream(com.google.protobuf.CodedOutputStream) MediaType(org.springframework.http.MediaType) Charset(java.nio.charset.Charset) OutputStreamWriter(java.io.OutputStreamWriter)

Example 42 with MediaType

use of org.springframework.http.MediaType in project spring-framework by spring-projects.

the class Jaxb2CollectionHttpMessageConverter method canRead.

/**
	 * {@inheritDoc}
	 * <p>Jaxb2CollectionHttpMessageConverter can read a generic
	 * {@link Collection} where the generic type is a JAXB type annotated with
	 * {@link XmlRootElement} or {@link XmlType}.
	 */
@Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
    if (!(type instanceof ParameterizedType)) {
        return false;
    }
    ParameterizedType parameterizedType = (ParameterizedType) type;
    if (!(parameterizedType.getRawType() instanceof Class)) {
        return false;
    }
    Class<?> rawType = (Class<?>) parameterizedType.getRawType();
    if (!(Collection.class.isAssignableFrom(rawType))) {
        return false;
    }
    if (parameterizedType.getActualTypeArguments().length != 1) {
        return false;
    }
    Type typeArgument = parameterizedType.getActualTypeArguments()[0];
    if (!(typeArgument instanceof Class)) {
        return false;
    }
    Class<?> typeArgumentClass = (Class<?>) typeArgument;
    return (typeArgumentClass.isAnnotationPresent(XmlRootElement.class) || typeArgumentClass.isAnnotationPresent(XmlType.class)) && canRead(mediaType);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) XmlType(javax.xml.bind.annotation.XmlType) MediaType(org.springframework.http.MediaType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) XmlType(javax.xml.bind.annotation.XmlType)

Example 43 with MediaType

use of org.springframework.http.MediaType in project spring-framework by spring-projects.

the class DefaultResponseErrorHandler method getCharset.

/**
	 * Determine the charset of the response (for inclusion in a status exception).
	 * @param response the response to inspect
	 * @return the associated charset, or {@code null} if none
	 * @since 4.3.8
	 */
protected Charset getCharset(ClientHttpResponse response) {
    HttpHeaders headers = response.getHeaders();
    MediaType contentType = headers.getContentType();
    return (contentType != null ? contentType.getCharset() : null);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType)

Example 44 with MediaType

use of org.springframework.http.MediaType in project spring-framework by spring-projects.

the class HttpMessageConverterExtractor method extractData.

@Override
@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
public T extractData(ClientHttpResponse response) throws IOException {
    MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
    if (!responseWrapper.hasMessageBody() || responseWrapper.hasEmptyMessageBody()) {
        return null;
    }
    MediaType contentType = getContentType(responseWrapper);
    try {
        for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
            if (messageConverter instanceof GenericHttpMessageConverter) {
                GenericHttpMessageConverter<?> genericMessageConverter = (GenericHttpMessageConverter<?>) messageConverter;
                if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Reading [" + this.responseType + "] as \"" + contentType + "\" using [" + messageConverter + "]");
                    }
                    return (T) genericMessageConverter.read(this.responseType, null, responseWrapper);
                }
            }
            if (this.responseClass != null) {
                if (messageConverter.canRead(this.responseClass, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Reading [" + this.responseClass.getName() + "] as \"" + contentType + "\" using [" + messageConverter + "]");
                    }
                    return (T) messageConverter.read((Class) this.responseClass, responseWrapper);
                }
            }
        }
    } catch (IOException | HttpMessageNotReadableException exc) {
        throw new RestClientException("Error while extracting response for type [" + this.responseType + "] and content type [" + contentType + "]", exc);
    }
    throw new RestClientException("Could not extract response: no suitable HttpMessageConverter found " + "for response type [" + this.responseType + "] and content type [" + contentType + "]");
}
Also used : HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) MediaType(org.springframework.http.MediaType) IOException(java.io.IOException) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter)

Example 45 with MediaType

use of org.springframework.http.MediaType in project spring-framework by spring-projects.

the class AbstractMappingContentNegotiationStrategy method resolveMediaTypeKey.

/**
	 * An alternative to {@link #resolveMediaTypes(NativeWebRequest)} that accepts
	 * an already extracted key.
	 * @since 3.2.16
	 */
public List<MediaType> resolveMediaTypeKey(NativeWebRequest webRequest, String key) throws HttpMediaTypeNotAcceptableException {
    if (StringUtils.hasText(key)) {
        MediaType mediaType = lookupMediaType(key);
        if (mediaType != null) {
            handleMatch(key, mediaType);
            return Collections.singletonList(mediaType);
        }
        mediaType = handleNoMatch(webRequest, key);
        if (mediaType != null) {
            addMapping(key, mediaType);
            return Collections.singletonList(mediaType);
        }
    }
    return Collections.emptyList();
}
Also used : MediaType(org.springframework.http.MediaType)

Aggregations

MediaType (org.springframework.http.MediaType)254 Test (org.junit.Test)157 HttpHeaders (org.springframework.http.HttpHeaders)49 MockHttpInputMessage (org.springframework.http.MockHttpInputMessage)31 MockHttpOutputMessage (org.springframework.http.MockHttpOutputMessage)24 Charset (java.nio.charset.Charset)21 ArrayList (java.util.ArrayList)21 URI (java.net.URI)20 ByteArrayInputStream (java.io.ByteArrayInputStream)15 IOException (java.io.IOException)15 ServerWebExchange (org.springframework.web.server.ServerWebExchange)15 List (java.util.List)14 HttpInputMessage (org.springframework.http.HttpInputMessage)14 HttpStatus (org.springframework.http.HttpStatus)11 Resource (org.springframework.core.io.Resource)10 HttpEntity (org.springframework.http.HttpEntity)10 HttpMessageNotReadableException (org.springframework.http.converter.HttpMessageNotReadableException)10 HttpMediaTypeNotAcceptableException (org.springframework.web.HttpMediaTypeNotAcceptableException)9 InputStream (java.io.InputStream)8 InputStreamReader (java.io.InputStreamReader)8