Search in sources :

Example 11 with HttpMessageNotWritableException

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

the class AbstractMessageWriterResultHandler method writeBody.

/**
 * Write a given body to the response with {@link HttpMessageWriter}.
 * @param body the object to write
 * @param bodyParameter the {@link MethodParameter} of the body to write
 * @param actualParam the actual return type of the method that returned the value;
 * could be different from {@code bodyParameter} when processing {@code HttpEntity}
 * for example
 * @param exchange the current exchange
 * @return indicates completion or error
 * @since 5.0.2
 */
@SuppressWarnings({ "unchecked", "rawtypes", "ConstantConditions" })
protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParameter, @Nullable MethodParameter actualParam, ServerWebExchange exchange) {
    ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
    ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyType.resolve(), body);
    Publisher<?> publisher;
    ResolvableType elementType;
    ResolvableType actualElementType;
    if (adapter != null) {
        publisher = adapter.toPublisher(body);
        boolean isUnwrapped = KotlinDetector.isSuspendingFunction(bodyParameter.getMethod()) && !COROUTINES_FLOW_CLASS_NAME.equals(bodyType.toClass().getName());
        ResolvableType genericType = isUnwrapped ? bodyType : bodyType.getGeneric();
        elementType = getElementType(adapter, genericType);
        actualElementType = elementType;
    } else {
        publisher = Mono.justOrEmpty(body);
        actualElementType = body != null ? ResolvableType.forInstance(body) : bodyType;
        elementType = (bodyType.toClass() == Object.class && body != null ? actualElementType : bodyType);
    }
    if (elementType.resolve() == void.class || elementType.resolve() == Void.class) {
        return Mono.from((Publisher<Void>) publisher);
    }
    MediaType bestMediaType;
    try {
        bestMediaType = selectMediaType(exchange, () -> getMediaTypesFor(elementType));
    } catch (NotAcceptableStatusException ex) {
        HttpStatus statusCode = exchange.getResponse().getStatusCode();
        if (statusCode != null && statusCode.isError()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignoring error response content (if any). " + ex.getReason());
            }
            return Mono.empty();
        }
        throw ex;
    }
    if (bestMediaType != null) {
        String logPrefix = exchange.getLogPrefix();
        if (logger.isDebugEnabled()) {
            logger.debug(logPrefix + (publisher instanceof Mono ? "0..1" : "0..N") + " [" + elementType + "]");
        }
        for (HttpMessageWriter<?> writer : getMessageWriters()) {
            if (writer.canWrite(actualElementType, bestMediaType)) {
                return writer.write((Publisher) publisher, actualType, elementType, bestMediaType, exchange.getRequest(), exchange.getResponse(), Hints.from(Hints.LOG_PREFIX_HINT, logPrefix));
            }
        }
    }
    MediaType contentType = exchange.getResponse().getHeaders().getContentType();
    boolean isPresentMediaType = (contentType != null && contentType.equals(bestMediaType));
    Set<MediaType> producibleTypes = exchange.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    if (isPresentMediaType || !CollectionUtils.isEmpty(producibleTypes)) {
        return Mono.error(new HttpMessageNotWritableException("No Encoder for [" + elementType + "] with preset Content-Type '" + contentType + "'"));
    }
    List<MediaType> mediaTypes = getMediaTypesFor(elementType);
    if (bestMediaType == null && mediaTypes.isEmpty()) {
        return Mono.error(new IllegalStateException("No HttpMessageWriter for " + elementType));
    }
    return Mono.error(new NotAcceptableStatusException(mediaTypes));
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) HttpStatus(org.springframework.http.HttpStatus) Mono(reactor.core.publisher.Mono) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 12 with HttpMessageNotWritableException

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

the class ResponseEntityExceptionHandlerTests method httpMessageNotWritable.

@Test
public void httpMessageNotWritable() {
    Exception ex = new HttpMessageNotWritableException("");
    testException(ex);
}
Also used : HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) MissingPathVariableException(org.springframework.web.bind.MissingPathVariableException) ServletException(jakarta.servlet.ServletException) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) NoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException) MissingServletRequestPartException(org.springframework.web.multipart.support.MissingServletRequestPartException) BindException(org.springframework.validation.BindException) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException) AsyncRequestTimeoutException(org.springframework.web.context.request.async.AsyncRequestTimeoutException) MissingServletRequestParameterException(org.springframework.web.bind.MissingServletRequestParameterException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ServletRequestBindingException(org.springframework.web.bind.ServletRequestBindingException) TypeMismatchException(org.springframework.beans.TypeMismatchException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) Test(org.junit.jupiter.api.Test)

Example 13 with HttpMessageNotWritableException

use of org.springframework.http.converter.HttpMessageNotWritableException in project spring-data-document-examples by spring-projects.

the class CouchDbMappingJacksonHttpMessageConverter method writeInternal.

@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    JsonEncoding encoding = getEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
    try {
        if (this.prefixJson) {
            jsonGenerator.writeRaw("{} && ");
        }
        this.objectMapper.writeValue(jsonGenerator, o);
    } catch (JsonGenerationException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
Also used : HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) JsonEncoding(org.codehaus.jackson.JsonEncoding) JsonGenerator(org.codehaus.jackson.JsonGenerator) JsonGenerationException(org.codehaus.jackson.JsonGenerationException)

Example 14 with HttpMessageNotWritableException

use of org.springframework.http.converter.HttpMessageNotWritableException in project spring-data-document-examples by spring-projects.

the class CouchDbMappingJacksonHttpMessageConverter method writeInternal.

@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    JsonEncoding encoding = getEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
    try {
        if (this.prefixJson) {
            jsonGenerator.writeRaw("{} && ");
        }
        this.objectMapper.writeValue(jsonGenerator, o);
    } catch (JsonGenerationException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}
Also used : HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) JsonEncoding(org.codehaus.jackson.JsonEncoding) JsonGenerator(org.codehaus.jackson.JsonGenerator) JsonGenerationException(org.codehaus.jackson.JsonGenerationException)

Example 15 with HttpMessageNotWritableException

use of org.springframework.http.converter.HttpMessageNotWritableException in project midpoint by Evolveum.

the class MidpointAbstractHttpMessageConverter method writeInternal.

@Override
protected void writeInternal(@NotNull T object, @NotNull HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    // TODO implement in the standard serializer; also change root name
    QName fakeQName = new QName(PrismConstants.NS_TYPES, "object");
    String serializedForm;
    PrismSerializer<String> serializer = getSerializer().options(SerializationOptions.createSerializeReferenceNames());
    try {
        if (object instanceof ObjectType) {
            ObjectType ot = (ObjectType) object;
            serializedForm = serializer.serialize(ot.asPrismObject());
        } else if (object instanceof PrismObject) {
            serializedForm = serializer.serialize((PrismObject<?>) object);
        } else if (object instanceof OperationResult) {
            Function<LocalizableMessage, String> resolveKeys = msg -> localizationService.translate(msg, Locale.US);
            OperationResultType operationResultType = ((OperationResult) object).createOperationResultType(resolveKeys);
            serializedForm = serializer.serializeAnyData(operationResultType, fakeQName);
        } else {
            serializedForm = serializer.serializeAnyData(object, fakeQName);
        }
        outputMessage.getBody().write(serializedForm.getBytes(StandardCharsets.UTF_8));
    } catch (SchemaException | RuntimeException e) {
        LoggingUtils.logException(LOGGER, "Couldn't marshal element to string: {}", e, object);
    }
}
Also used : ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Trace(com.evolveum.midpoint.util.logging.Trace) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) LocalizationService(com.evolveum.midpoint.common.LocalizationService) Function(java.util.function.Function) ScriptingBeansUtil(com.evolveum.midpoint.schema.util.ScriptingBeansUtil) OperationResultType(com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType) Locale(java.util.Locale) LocalizableMessage(com.evolveum.midpoint.util.LocalizableMessage) com.evolveum.midpoint.prism(com.evolveum.midpoint.prism) AbstractHttpMessageConverter(org.springframework.http.converter.AbstractHttpMessageConverter) MediaType(org.springframework.http.MediaType) IOException(java.io.IOException) StandardCharsets(java.nio.charset.StandardCharsets) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) HttpInputMessage(org.springframework.http.HttpInputMessage) ScriptingExpressionType(com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingExpressionType) ExecuteScriptType(com.evolveum.midpoint.xml.ns._public.model.scripting_3.ExecuteScriptType) QName(javax.xml.namespace.QName) NotNull(org.jetbrains.annotations.NotNull) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) InputStream(java.io.InputStream) HttpOutputMessage(org.springframework.http.HttpOutputMessage) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) QName(javax.xml.namespace.QName) LocalizableMessage(com.evolveum.midpoint.util.LocalizableMessage) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) OperationResultType(com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType)

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