@Override public Route unauthorized(final String correlationId) { return Directives.complete(StatusCodes.UNAUTHORIZED); }
/** * Builds the {@code /status} route. * * @return the {@code /status} route. */ public Route buildOverallStatusRoute() { return rawPathPrefix(mergeDoubleSlashes().concat(PATH_OVERALL), () -> // /overall/* authenticateDevopsBasic(REALM_DEVOPS, get(() -> // GET // /overall/status // /overall/status/health // /overall/status/cluster rawPathPrefix(mergeDoubleSlashes().concat(PATH_STATUS), () -> route( // /status pathEndOrSingleSlash( () -> completeWithFuture(createOverallStatusResponse())), // /status/health path(PATH_HEALTH, () -> completeWithFuture(createOverallHealthResponse())), path(PATH_CLUSTER, () -> complete( // /status/cluster HttpResponse.create().withStatus(StatusCodes.OK) .withEntity(ContentTypes.APPLICATION_JSON, clusterStateSupplier.get().toJson().toString())) ) )) ))); }
onComplete(lookupProduct(productId), (Try<DbActor.ProductResult> result) -> { if (result.isFailure()) { return complete(StatusCodes.SERVICE_UNAVAILABLE); } else { final DbActor.ProductResult productResult = result.get(); return completeOK(productResult.product.get(), productMarshaller); } else { return complete(StatusCodes.NOT_FOUND);
@Override public Route apply(final String correlationId) { LOGGER.debug("Returning status {}", STATUS_CODE); return Directives.complete(STATUS_CODE); } }
private static Route disallowRequest(final Uri requestUri) { LOGGER.info("REST request on uri '{}' did not originate via HTTPS, sending back '{}'", requestUri, StatusCodes.NOT_FOUND); return complete(StatusCodes.NOT_FOUND, HTTPS_TEXT); } }
private static Route handleMissingQueryParam(MissingQueryParamRejection missingQueryParamRejection) { // return status code 400 instead of the akka default 404 return complete(StatusCodes.BAD_REQUEST, MessageFormat.format(MISSING_QUERY_PARAM_TEMPLATE, missingQueryParamRejection.parameterName())); } }
/** * Builds the {@code /ws} route. * * @return the {@code /ws} route. */ public Route buildWebsocketRoute(final Integer version, final String correlationId, final AuthorizationContext connectionAuthContext, final DittoHeaders additionalHeaders, final ProtocolAdapter chosenProtocolAdapter) { return extractUpgradeToWebSocket(upgradeToWebSocket -> complete( createWebsocket(upgradeToWebSocket, version, correlationId, connectionAuthContext, additionalHeaders, chosenProtocolAdapter) ) ); }
/** * Authenticates with the Basic Authentication. * * @param realm the realm to apply * @param inner the inner route, which will be performed on successful authentication * @return the inner route wrapped with authentication */ public static Route authenticateDevopsBasic(final String realm, final Route inner) { return Directives.extractActorSystem(actorSystem -> { final Config config = actorSystem.settings().config(); if (REALM_DEVOPS.equals(realm)) { final boolean devopsSecureStatus = config.getBoolean(ConfigKeys.DEVOPS_SECURE_STATUS); if (!devopsSecureStatus) { LOGGER.warn("DevOps resource is not secured by BasicAuth"); return inner; } final String devOpsPassword = config.getString(ConfigKeys.SECRETS_DEVOPS_PASSWORD); LOGGER.debug("Devops authentication is enabled."); return Directives.authenticateBasic(REALM_DEVOPS, new Authenticator(USER_DEVOPS, devOpsPassword), userName -> inner); } else { LOGGER.warn("Did not know realm '{}'. NOT letting the inner Route pass ..", realm); return Directives.complete(StatusCodes.UNAUTHORIZED); } }); }
public static Route ensureEncoding(final String correlationId, final Supplier<Route> inner) { return extractRequestContext(requestContext -> enhanceLogWithCorrelationId(correlationId, () -> { final Uri uri = requestContext.getRequest().getUri(); try { // per default, Akka evaluates the query params "lazily" in the routes and throws an IllegalUriException // in case of error; we evaluate the query params explicitly here to be able to handle this error at // a central location uri.query(); } catch (final IllegalUriException e) { LOGGER.debug("URI parsing failed", e); final String rawRequestUri = HttpUtils.getRawRequestUri(requestContext.getRequest()); final String message = MessageFormat.format(URI_INVALID_TEMPLATE, rawRequestUri); return complete(StatusCodes.BAD_REQUEST, message); } return inner.get(); })); } }
/** * Builds the {@code /status} route. * * @return the {@code /status} route. */ public Route buildStatusRoute() { return pathPrefix(PATH_STATUS, () -> // /status/* get(() -> // GET route( pathEndOrSingleSlash(() -> // /status complete( HttpResponse.create().withStatus(StatusCodes.OK) .withEntity(ContentTypes.APPLICATION_JSON, Status.provideStaticStatus().toString()) ) ), path(PATH_HEALTH, healthRouteSupplier), // /status/health path(PATH_CLUSTER, () -> complete( // /status/cluster HttpResponse.create().withStatus(StatusCodes.OK) .withEntity(ContentTypes.APPLICATION_JSON, clusterStateSupplier.get().toJson().toString())) ) ) ).orElse(complete(StatusCodes.METHOD_NOT_ALLOWED))); }
/** * Builds the {@code /status} route. * * @return the {@code /status} route. */ public Route buildStatusRoute() { return pathPrefix(PATH_STATUS, () -> // /status/* get(() -> // GET route( pathEndOrSingleSlash(() -> // /status complete( HttpResponse.create().withStatus(StatusCodes.OK) .withEntity(ContentTypes.APPLICATION_JSON, Status.provideStaticStatus().toString()) ) ), path(PATH_HEALTH, healthRouteSupplier), // /status/health path(PATH_CLUSTER, () -> complete( // /status/cluster HttpResponse.create().withStatus(StatusCodes.OK) .withEntity(ContentTypes.APPLICATION_JSON, clusterStateSupplier.get().toJson().toString())) ) ) ).orElse(complete(StatusCodes.METHOD_NOT_ALLOWED))); }
/** * 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(); } }); }
/** * Builds a Route for a HTTP Prometheus endpoint where Prometheus can scrape metrics from. * * @param prometheusReporter the PrometheusReporter to retrieve the {@code scrapeData} from * @return the Prometheus Route */ public static Route buildPrometheusReporterRoute(final PrometheusReporter prometheusReporter) { return get(() -> complete(HttpResponse.create() .withStatus(StatusCodes.OK) .withEntity(CONTENT_TYPE, ByteString.fromString(prometheusReporter.scrapeData())) ) ); } }
LOGGER.info("DittoRuntimeException in gateway RootRoute: {}", cre.getMessage()) ); return complete(HttpResponse.create().withStatus(cre.getStatusCode().toInt()) .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(cre.toJsonString()))); }) LOGGER.info("DittoJsonException in gateway RootRoute: {}", dittoJsonException.getMessage())); return complete(HttpResponse.create().withStatus(dittoJsonException.getStatusCode().toInt()) .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(dittoJsonException.toJsonString()))); LOGGER.error("Unexpected RuntimeException in gateway RootRoute: {}", throwable.getMessage(), throwable); return complete(StatusCodes.INTERNAL_SERVER_ERROR); }) .build();
/** * Builds a Route for a HTTP Prometheus endpoint where Prometheus can scrape metrics from. * * @param prometheusReporter the PrometheusReporter to retrieve the {@code scrapeData} from * @return the Prometheus Route */ public static Route buildPrometheusReporterRoute(final PrometheusReporter prometheusReporter) { return get(() -> complete(HttpResponse.create() .withStatus(StatusCodes.OK) .withEntity(CONTENT_TYPE, ByteString.fromString(buildMetricsString(prometheusReporter))) ) ); }
private Route ensureSchemaVersion(final Function<Integer, Route> inner) { return rawPathPrefix(mergeDoubleSlashes().concat(PathMatchers.integerSegment()), apiVersion -> { // /xx/<schemaVersion> if (supportedSchemaVersions.contains(apiVersion)) { try { return inner.apply(apiVersion); } catch (final RuntimeException e) { throw e; // rethrow RuntimeExceptions } catch (final Exception e) { throw new IllegalStateException("Unexpected checked exception", e); } } else { final CommandNotSupportedException commandNotSupportedException = CommandNotSupportedException.newBuilder(apiVersion).build(); return complete( HttpResponse.create().withStatus(commandNotSupportedException.getStatusCode().toInt()) .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(commandNotSupportedException.toJsonString()))); } }); }