use of org.eclipse.ditto.messages.model.signals.commands.MessageCommandResponse in project ditto by eclipse.
the class AbstractHttpRequestActor method handleMessageResponseMessage.
private HttpResponse handleMessageResponseMessage(final MessageCommandResponse<?, ?> messageCommandResponse) {
HttpResponse httpResponse;
final Message<?> message = messageCommandResponse.getMessage();
final Optional<?> optionalPayload = message.getPayload();
final Optional<ByteBuffer> optionalRawPayload = message.getRawPayload();
final var responseStatus = Optional.of(messageCommandResponse.getHttpStatus()).filter(httpStatus -> StatusCodes.lookup(httpStatus.getCode()).isPresent()).filter(httpStatus -> !HttpStatus.BAD_GATEWAY.equals(httpStatus));
// if statusCode is != NO_CONTENT
if (responseStatus.map(status -> !HttpStatus.NO_CONTENT.equals(status)).orElse(true)) {
// this is on purpose not .map(ContentTypes:parse) as this would throw an exception:
final Optional<akka.http.scaladsl.model.ContentType> optionalContentType = message.getContentType().map(ContentType$.MODULE$::parse).filter(Either::isRight).map(Either::toOption).map(Option::get);
final boolean isBinary = optionalContentType.map(akka.http.scaladsl.model.ContentType::value).map(ContentType::of).filter(ContentType::isBinary).isPresent();
httpResponse = createHttpResponse(responseStatus.orElse(HttpStatus.OK));
if (optionalPayload.isPresent() && optionalContentType.isPresent() && !isBinary) {
final akka.http.scaladsl.model.ContentType contentType = optionalContentType.get();
final Object payload = optionalPayload.get();
final ByteString responsePayload = ByteString.fromString(payload.toString());
httpResponse = httpResponse.withEntity(HttpEntities.create(contentType, responsePayload));
} else if (optionalRawPayload.isPresent() && optionalContentType.isPresent() && isBinary) {
final akka.http.scaladsl.model.ContentType contentType = optionalContentType.get();
final ByteBuffer rawPayload = optionalRawPayload.get();
httpResponse = httpResponse.withEntity(HttpEntities.create(contentType, rawPayload.array()));
} else if (optionalRawPayload.isPresent()) {
final ByteBuffer rawPayload = optionalRawPayload.get();
httpResponse = httpResponse.withEntity(HttpEntities.create(rawPayload.array()));
}
} else {
// if payload was missing OR HTTP status was NO_CONTENT:
optionalRawPayload.ifPresent(byteBuffer -> logger.withCorrelationId(messageCommandResponse).info("Response payload was set but response status code was also set to <{}>." + " Ignoring the response payload. Command=<{}>", responseStatus, messageCommandResponse));
httpResponse = createHttpResponse(HttpStatus.NO_CONTENT);
}
return enhanceResponseWithExternalDittoHeaders(httpResponse, messageCommandResponse.getDittoHeaders());
}
Aggregations