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));
}
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);
}
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);
}
}
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);
}
}
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);
}
}
Aggregations