private CompletionStage<HttpResponse> createOverallStatusResponse() { return statusHealthProvider.retrieveStatus() .thenApply(status -> HttpResponse.create() .withStatus(StatusCodes.OK) .withEntity(ContentTypes.APPLICATION_JSON, status.toString())); }
private HttpResponse completeHealthRequestForUnexpectedHealthResult(@Nullable final Object healthResult) { log.error( "Health check returned an unexpected result: '{}'", healthResult); return HttpResponse.create() .withStatus(HTTP_STATUS_SERVICE_UNAVAILABLE); } }
private Route handleSudoCountThingsPerRequest(final RequestContext ctx, final SudoCountThings command) { final CompletableFuture<HttpResponse> httpResponseFuture = new CompletableFuture<>(); Source.single(command) .to(Sink.actorRef(createHttpPerRequestActor(ctx, httpResponseFuture), HttpRequestActor.COMPLETE_MESSAGE)) .run(materializer); final CompletionStage<HttpResponse> allThingsCountHttpResponse = Source.fromCompletionStage(httpResponseFuture) .flatMapConcat(httpResponse -> httpResponse.entity().getDataBytes()) .fold(ByteString.empty(), ByteString::concat) .map(ByteString::utf8String) .map(Integer::valueOf) .map(count -> JsonObject.newBuilder().set("allThingsCount", count).build()) .map(jsonObject -> HttpResponse.create() .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(jsonObject.toString())) .withStatus(HttpStatusCode.OK.toInt())) .runWith(Sink.head(), materializer); return completeWithFuture(allThingsCountHttpResponse); }
return HttpResponse.create() .withStatus(statusCode) .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(cre.toJsonString())) .addHeaders(securityResponseHeaders);
/** * Enables CORS - Cross-Origin Resource Sharing - for the wrapped {@code inner} Route. * * @param inner the inner route to be wrapped with the CORS enabling * @return the new route wrapping {@code inner} with the CORS enabling */ public static Route enableCors(final Supplier<Route> inner) { return extractActorSystem(actorSystem -> { final boolean enableCors = actorSystem.settings().config().getBoolean(ConfigKeys.ENABLE_CORS); if (enableCors) { return Directives.optionalHeaderValueByType(AccessControlRequestHeaders.class, corsRequestHeaders -> { final ArrayList<HttpHeader> newHeaders = new ArrayList<>(CORS_HEADERS); corsRequestHeaders.ifPresent(toAdd -> newHeaders.add(AccessControlAllowHeaders.create( StreamSupport.stream(toAdd.getHeaders().spliterator(), false) .toArray(String[]::new)) ) ); return route( options(() -> complete(HttpResponse.create().withStatus(StatusCodes.OK).addHeaders(newHeaders)) ), respondWithHeaders(newHeaders, inner) ); }); } else { return inner.get(); } }); }
final boolean isSuccessfulResponse = response.status().isSuccess(); final boolean isEmptyResponse = response.entity().isKnownEmpty(); if (isSuccessfulResponse && !isEmptyResponse) { final InputStream inputStream = response.entity() .getDataBytes() .fold(ByteString.empty(), ByteString::concat) try { final JsonValue transformed = responseTransformFunction.apply(jsonValue); return response.withEntity(ContentTypes.APPLICATION_JSON, transformed.toString()); } catch (final Exception e) { throw JsonParseException.newBuilder()
private static HttpResponse addEntityAccordingToContentType(final HttpResponse response, final String entityPlain, final DittoHeaders dittoHeaders) { if (hasPlainTextContentType(dittoHeaders)) { return response.withEntity(CONTENT_TYPE_TEXT, ByteString.fromString(entityPlain)); } else { return response.withEntity(CONTENT_TYPE_JSON, ByteString.fromString(entityPlain)); } }
private void completeWithResult(final HttpResponse response) { final int statusCode = response.status().intValue(); if (logger.isDebugEnabled()) { logger.debug("Responding with HttpResponse code '{}'", statusCode); logger.debug("Responding with Entity: {}", response.entity()); } httpResponseFuture.complete(response); stop(); }
private static Function<HttpResponse, HttpResponse> createBodyAddingResponseMapper( final CommandResponse commandResponse, final WithOptionalEntity withOptionalEntity) { return response -> { if (StatusCodes.NO_CONTENT.equals(response.status())) { return response; } else { return withOptionalEntity.getEntity(commandResponse.getImplementedSchemaVersion()) .map(entity -> addEntityAccordingToContentType(response, entity, commandResponse.getDittoHeaders())) .orElse(response); } }; }
private CompletableFuture<JsonArray> mapResponseToJsonArray(final HttpResponse response) { final CompletionStage<JsonObject> body = response.entity().getDataBytes().fold(ByteString.empty(), ByteString::concat) .map(ByteString::utf8String) .map(JsonFactory::readFrom) .map(JsonValue::asObject) .runWith(Sink.head(), httpClient.getActorMaterializer()); final JsonPointer keysPointer = JsonPointer.of("keys"); return body.toCompletableFuture() .thenApply(jsonObject -> jsonObject.getValue(keysPointer).map(JsonValue::asArray) .orElseThrow(() -> new JsonMissingFieldException(keysPointer))) .exceptionally(t -> { throw new IllegalStateException("Failed to extract public keys from JSON response: " + body, t); }); }
private static Function<HttpResponse, HttpResponse> createModifiedLocationHeaderAddingResponseMapper( final HttpRequest request, final CommandResponse commandResponse) { return response -> { if (HttpStatusCode.CREATED == commandResponse.getStatusCode()) { Uri newUri = request.getUri(); if (!request.method().isIdempotent()) { // only for not idempotent requests (e.g.: POST), add the "createdId" to the path: final String uriStr = newUri.toString(); String createdLocation; final int uriIdIndex = uriStr.indexOf(commandResponse.getId()); // if the uri contains the id, but *not* at the beginning if (uriIdIndex > 0) { createdLocation = uriStr.substring(0, uriIdIndex) + commandResponse.getId() + commandResponse.getResourcePath().toString(); } else { createdLocation = uriStr + "/" + commandResponse.getId() + commandResponse.getResourcePath() .toString(); } if (createdLocation.endsWith("/")) { createdLocation = createdLocation.substring(0, createdLocation.length() - 1); } newUri = Uri.create(createdLocation); } return response.addHeader(Location.create(newUri)); } else { return response; } }; }
private HttpResponse completeHealthRequest(final Throwable failure) { log.error(failure, "Health check resulted in failure: '{}'", failure.getMessage()); return HttpResponse.create() .withStatus(HTTP_STATUS_SERVICE_UNAVAILABLE); }
private static HttpResponse addEntityAccordingToContentType(final HttpResponse response, final JsonValue entity, final DittoHeaders dittoHeaders) { if (hasPlainTextContentType(dittoHeaders)) { return response.withEntity(CONTENT_TYPE_TEXT, ByteString.fromString(entity.asString())); } else { return response.withEntity(CONTENT_TYPE_JSON, ByteString.fromString(entity.toString())); } }
final int statusCode = complete.getResponse().status().intValue(); LOGGER.info("StatusCode of request {} '{}' was: {}", requestMethod, requestUri, statusCode); final String rawRequestUri = HttpUtils.getRawRequestUri(request);
private CompletionStage<HttpResponse> createOverallHealthResponse() { return statusHealthProvider.retrieveHealth() .thenApply(overallHealth -> { if (overallHealth.isHealthy()) { return HttpResponse.create() .withStatus(StatusCodes.OK) .withEntity(ContentTypes.APPLICATION_JSON, overallHealth.toJsonString()); } else { return HttpResponse.create() .withStatus(StatusCodes.SERVICE_UNAVAILABLE) .withEntity(ContentTypes.APPLICATION_JSON, overallHealth.toJsonString()); } }); }
private HttpResponse completeHealthRequest(final Throwable failure) { log.error(failure, "Health check resulted in failure: '{}'", failure.getMessage()); return HttpResponse.create() .withStatus(HTTP_STATUS_SERVICE_UNAVAILABLE); }
final int statusCode = response.status().intValue(); if (timer.isRunning()) { final StoppedTimer stoppedTimer = timer
private HttpResponse completeHealthRequest(final StatusInfo statusInfo) { final int httpStatusCode = statusInfo.getStatus() == StatusInfo.Status.DOWN ? HTTP_STATUS_SERVICE_UNAVAILABLE : HTTP_STATUS_OK; if (statusInfo.getStatus() == StatusInfo.Status.DOWN) { log.warning("Own health check returned DOWN: {}", statusInfo); } return HttpResponse.create() .withEntity(ContentTypes.APPLICATION_JSON, statusInfo.toJsonString()) .withStatus(httpStatusCode); }
private HttpResponse completeHealthRequestForUnexpectedHealthResult(@Nullable final Object healthResult) { log.error( "Health check returned an unexpected result: '{}'", healthResult); return HttpResponse.create() .withStatus(HTTP_STATUS_SERVICE_UNAVAILABLE); } }
private HttpResponse completeHealthRequest(final StatusInfo statusInfo) { final int httpStatusCode = statusInfo.getStatus() == StatusInfo.Status.DOWN ? HTTP_STATUS_SERVICE_UNAVAILABLE : HTTP_STATUS_OK; if (statusInfo.getStatus() == StatusInfo.Status.DOWN) { log.warning("Own health check returned DOWN: {}", statusInfo); } return HttpResponse.create() .withEntity(ContentTypes.APPLICATION_JSON, statusInfo.toJsonString()) .withStatus(httpStatusCode); }