Search in sources :

Example 21 with HttpMessageNotWritableException

use of org.springframework.http.converter.HttpMessageNotWritableException in project xm-ms-entity by xm-online.

the class MultipartMixedConverter method writePart.

@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
    Object partBody = partEntity.getBody();
    Class<?> partType = partBody.getClass();
    HttpHeaders partHeaders = partEntity.getHeaders();
    MediaType partContentType = partHeaders.getContentType();
    for (HttpMessageConverter<?> messageConverter : this.partConverters) {
        if (messageConverter.canWrite(partType, partContentType)) {
            HttpOutputMessage multipartMessage = new MultipartMixedConverter.MultipartHttpOutputMessage(os);
            multipartMessage.getHeaders().setContentDispositionFormData(name, null);
            if (!partHeaders.isEmpty()) {
                multipartMessage.getHeaders().putAll(partHeaders);
            }
            ((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
            return;
        }
    }
    throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter found for request type [" + partType.getName() + "]");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) StreamingHttpOutputMessage(org.springframework.http.StreamingHttpOutputMessage) HttpOutputMessage(org.springframework.http.HttpOutputMessage) ResourceHttpMessageConverter(org.springframework.http.converter.ResourceHttpMessageConverter) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) MediaType(org.springframework.http.MediaType)

Example 22 with HttpMessageNotWritableException

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

the class AbstractJsonHttpMessageConverter method writeInternal.

@Override
protected final void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    Writer writer = getWriter(outputMessage);
    if (this.jsonPrefix != null) {
        writer.append(this.jsonPrefix);
    }
    try {
        writeInternal(object, type, writer);
    } catch (Exception ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
    writer.flush();
}
Also used : HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException)

Example 23 with HttpMessageNotWritableException

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

the class AbstractMessageConverterMethodProcessor method writeWithMessageConverters.

/**
 * Writes the given return type to the given output message.
 * @param value the value to write to the output message
 * @param returnType the type of the value
 * @param inputMessage the input messages. Used to inspect the {@code Accept} header.
 * @param outputMessage the output message to write to
 * @throws IOException thrown in case of I/O errors
 * @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated
 * by the {@code Accept} header on the request cannot be met by the message converters
 * @throws HttpMessageNotWritableException thrown if a given message cannot
 * be written by a converter, or if the content-type chosen by the server
 * has no compatible converter.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected <T> void writeWithMessageConverters(@Nullable T value, MethodParameter returnType, ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
    Object body;
    Class<?> valueType;
    Type targetType;
    if (value instanceof CharSequence) {
        body = value.toString();
        valueType = String.class;
        targetType = String.class;
    } else {
        body = value;
        valueType = getReturnValueType(body, returnType);
        targetType = GenericTypeResolver.resolveType(getGenericType(returnType), returnType.getContainingClass());
    }
    if (isResourceType(value, returnType)) {
        outputMessage.getHeaders().set(HttpHeaders.ACCEPT_RANGES, "bytes");
        if (value != null && inputMessage.getHeaders().getFirst(HttpHeaders.RANGE) != null && outputMessage.getServletResponse().getStatus() == 200) {
            Resource resource = (Resource) value;
            try {
                List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
                outputMessage.getServletResponse().setStatus(HttpStatus.PARTIAL_CONTENT.value());
                body = HttpRange.toResourceRegions(httpRanges, resource);
                valueType = body.getClass();
                targetType = RESOURCE_REGION_LIST_TYPE;
            } catch (IllegalArgumentException ex) {
                outputMessage.getHeaders().set(HttpHeaders.CONTENT_RANGE, "bytes */" + resource.contentLength());
                outputMessage.getServletResponse().setStatus(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE.value());
            }
        }
    }
    MediaType selectedMediaType = null;
    MediaType contentType = outputMessage.getHeaders().getContentType();
    boolean isContentTypePreset = contentType != null && contentType.isConcrete();
    if (isContentTypePreset) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found 'Content-Type:" + contentType + "' in response");
        }
        selectedMediaType = contentType;
    } else {
        HttpServletRequest request = inputMessage.getServletRequest();
        List<MediaType> acceptableTypes;
        try {
            acceptableTypes = getAcceptableMediaTypes(request);
        } catch (HttpMediaTypeNotAcceptableException ex) {
            int series = outputMessage.getServletResponse().getStatus() / 100;
            if (body == null || series == 4 || series == 5) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Ignoring error response content (if any). " + ex);
                }
                return;
            }
            throw ex;
        }
        List<MediaType> producibleTypes = getProducibleMediaTypes(request, valueType, targetType);
        if (body != null && producibleTypes.isEmpty()) {
            throw new HttpMessageNotWritableException("No converter found for return value of type: " + valueType);
        }
        List<MediaType> mediaTypesToUse = new ArrayList<>();
        for (MediaType requestedType : acceptableTypes) {
            for (MediaType producibleType : producibleTypes) {
                if (requestedType.isCompatibleWith(producibleType)) {
                    mediaTypesToUse.add(getMostSpecificMediaType(requestedType, producibleType));
                }
            }
        }
        if (mediaTypesToUse.isEmpty()) {
            if (body != null) {
                throw new HttpMediaTypeNotAcceptableException(producibleTypes);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("No match for " + acceptableTypes + ", supported: " + producibleTypes);
            }
            return;
        }
        MimeTypeUtils.sortBySpecificity(mediaTypesToUse);
        for (MediaType mediaType : mediaTypesToUse) {
            if (mediaType.isConcrete()) {
                selectedMediaType = mediaType;
                break;
            } else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) {
                selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
                break;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using '" + selectedMediaType + "', given " + acceptableTypes + " and supported " + producibleTypes);
        }
    }
    if (selectedMediaType != null) {
        selectedMediaType = selectedMediaType.removeQualityValue();
        for (HttpMessageConverter<?> converter : this.messageConverters) {
            GenericHttpMessageConverter genericConverter = (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
            if (genericConverter != null ? ((GenericHttpMessageConverter) converter).canWrite(targetType, valueType, selectedMediaType) : converter.canWrite(valueType, selectedMediaType)) {
                body = getAdvice().beforeBodyWrite(body, returnType, selectedMediaType, (Class<? extends HttpMessageConverter<?>>) converter.getClass(), inputMessage, outputMessage);
                if (body != null) {
                    Object theBody = body;
                    LogFormatUtils.traceDebug(logger, traceOn -> "Writing [" + LogFormatUtils.formatValue(theBody, !traceOn) + "]");
                    addContentDispositionHeader(inputMessage, outputMessage);
                    if (genericConverter != null) {
                        genericConverter.write(body, targetType, selectedMediaType, outputMessage);
                    } else {
                        ((HttpMessageConverter) converter).write(body, selectedMediaType, outputMessage);
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Nothing to write: null body");
                    }
                }
                return;
            }
        }
    }
    if (body != null) {
        Set<MediaType> producibleMediaTypes = (Set<MediaType>) inputMessage.getServletRequest().getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
        if (isContentTypePreset || !CollectionUtils.isEmpty(producibleMediaTypes)) {
            throw new HttpMessageNotWritableException("No converter for [" + valueType + "] with preset Content-Type '" + contentType + "'");
        }
        throw new HttpMediaTypeNotAcceptableException(getSupportedMediaTypes(body.getClass()));
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) InputStreamResource(org.springframework.core.io.InputStreamResource) Resource(org.springframework.core.io.Resource) ArrayList(java.util.ArrayList) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ResolvableType(org.springframework.core.ResolvableType) MediaType(org.springframework.http.MediaType) Type(java.lang.reflect.Type) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter) MediaType(org.springframework.http.MediaType) HttpRange(org.springframework.http.HttpRange) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter)

Example 24 with HttpMessageNotWritableException

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

the class SourceHttpMessageConverter method writeInternal.

@Override
protected void writeInternal(T t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    try {
        Result result = new StreamResult(outputMessage.getBody());
        transform(t, result);
    } catch (TransformerException ex) {
        throw new HttpMessageNotWritableException("Could not transform [" + t + "] to output message", ex);
    }
}
Also used : HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) StreamResult(javax.xml.transform.stream.StreamResult) TransformerException(javax.xml.transform.TransformerException) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result)

Example 25 with HttpMessageNotWritableException

use of org.springframework.http.converter.HttpMessageNotWritableException in project spring-security by spring-projects.

the class OAuth2AccessTokenResponseHttpMessageConverter method writeInternal.

@Override
protected void writeInternal(OAuth2AccessTokenResponse tokenResponse, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException {
    try {
        Map<String, Object> tokenResponseParameters;
        // Only use deprecated converter if it has been set directly
        if (this.tokenResponseParametersConverter.getClass() != OAuth2AccessTokenResponseMapConverter.class) {
            tokenResponseParameters = new LinkedHashMap<>(this.tokenResponseParametersConverter.convert(tokenResponse));
        } else {
            tokenResponseParameters = this.accessTokenResponseParametersConverter.convert(tokenResponse);
        }
        this.jsonMessageConverter.write(tokenResponseParameters, STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON, outputMessage);
    } catch (Exception ex) {
        throw new HttpMessageNotWritableException("An error occurred writing the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex);
    }
}
Also used : HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException)

Aggregations

HttpMessageNotWritableException (org.springframework.http.converter.HttpMessageNotWritableException)27 MediaType (org.springframework.http.MediaType)9 HttpMessageNotReadableException (org.springframework.http.converter.HttpMessageNotReadableException)8 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)5 IOException (java.io.IOException)5 JsonEncoding (com.fasterxml.jackson.core.JsonEncoding)4 JsonEncoding (org.codehaus.jackson.JsonEncoding)4 JsonGenerator (org.codehaus.jackson.JsonGenerator)4 HttpOutputMessage (org.springframework.http.HttpOutputMessage)4 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)3 OutputStreamWriter (java.io.OutputStreamWriter)3 JsonGenerationException (org.codehaus.jackson.JsonGenerationException)3 CsvSchema (com.fasterxml.jackson.dataformat.csv.CsvSchema)2 JsonIOException (com.google.gson.JsonIOException)2 Charset (java.nio.charset.Charset)2 ArrayList (java.util.ArrayList)2 Test (org.junit.jupiter.api.Test)2 HttpHeaders (org.springframework.http.HttpHeaders)2 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)2