akka.http.javadsl.server.Route Java Examples

The following examples show how to use akka.http.javadsl.server.Route. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OverallStatusRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Builds the {@code /status} route.
 *
 * @return the {@code /status} route.
 */
public Route buildOverallStatusRoute() {
    return rawPathPrefix(PathMatchers.slash().concat(PATH_OVERALL), () -> {// /overall/*
        final DevOpsBasicAuthenticationDirective devOpsBasicAuthenticationDirective =
                DevOpsBasicAuthenticationDirective.getInstance(devOpsConfig);
        return devOpsBasicAuthenticationDirective.authenticateDevOpsBasic(REALM_STATUS, get(() -> // GET
                // /overall/status
                // /overall/status/health
                // /overall/status/cluster
                rawPathPrefix(PathMatchers.slash().concat(PATH_STATUS), () -> concat(
                        // /status
                        pathEndOrSingleSlash(() -> completeWithFuture(createOverallStatusResponse())),
                        // /status/health
                        path(PATH_HEALTH, () -> completeWithFuture(createOverallHealthResponse())),
                        // /status/cluster
                        path(PATH_CLUSTER, () -> complete(
                                HttpResponse.create().withStatus(StatusCodes.OK)
                                        .withEntity(ContentTypes.APPLICATION_JSON,
                                                clusterStateSupplier.get().toJson().toString()))
                        )
                ))
        ));
    });
}
 
Example #2
Source File: FeaturesRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Route features(final RequestContext ctx, final DittoHeaders dittoHeaders, final ThingId thingId) {
    return pathEndOrSingleSlash(() ->
            concat(
                    get(() -> // GET /features?fields=<fieldsString>
                            parameterOptional(ThingsParameter.FIELDS.toString(), fieldsString ->
                                    handlePerRequest(ctx, RetrieveFeatures
                                            .of(thingId,
                                                    calculateSelectedFields(fieldsString).orElse(
                                                            null), dittoHeaders))
                            )
                    ),
                    put(() -> // PUT /features
                            ensureMediaTypeJsonWithFallbacksThenExtractDataBytes(ctx, dittoHeaders,
                                    payloadSource ->
                                    handlePerRequest(ctx, dittoHeaders, payloadSource,
                                            featuresJson -> ModifyFeatures
                                                    .of(thingId, ThingsModelFactory.newFeatures(
                                                            featuresJson), dittoHeaders))
                            )
                    ),
                    delete(() -> // DELETE /features
                            handlePerRequest(ctx, DeleteFeatures.of(thingId, dittoHeaders))
                    )
            )
    );
}
 
Example #3
Source File: CorrelationIdEnsuringDirective.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Extracts the correlationId from the request or creates a new one, if it does not exist.
 *
 * @param inner the inner Route to provide with the correlationId
 * @return the new Route wrapping {@code inner} with the correlationId
 */
public static Route ensureCorrelationId(final Function<String, Route> inner) {
    return extractRequestContext(requestContext -> {
        final HttpRequest request = requestContext.getRequest();
        final Optional<String> correlationIdOpt = extractCorrelationId(request);
        final String correlationId;
        if (correlationIdOpt.isPresent()) {
            correlationId = correlationIdOpt.get();
            LOGGER.withCorrelationId(correlationId)
                    .debug("CorrelationId already exists in request: {}", correlationId);
        } else {
            correlationId = UUID.randomUUID().toString();
            LOGGER.withCorrelationId(correlationId).debug("Created new CorrelationId: {}", correlationId);
        }

        return inner.apply(correlationId);
    });
}
 
Example #4
Source File: EncodingEnsuringDirective.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
public static Route ensureEncoding(final Supplier<Route> inner) {
    return extractRequestContext(requestContext -> {
        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();
    });
}
 
Example #5
Source File: DBProcessor.java    From alpakka-jdbc with Apache License 2.0 6 votes vote down vote up
@Override
protected Route routes() {
    return route(
            path("data", () -> {
                Source<Message, NotUsed> messages
                        = usersStream.map(String::valueOf).map(TextMessage::create);
                return handleWebSocketMessages(Flow.fromSinkAndSourceCoupled(Sink.ignore(),
                        messages));
            }),
            path("more", ()
                    -> {

                CompletionStage<Done> slowFuture = DBProcessor.inserUsersGraph.run(materializer);
                return completeOKWithFutureString(slowFuture.thenApply(done -> "Success"));
            }),
            get(()
                    -> pathSingleSlash(()
                    -> getFromResource("index.html")
            )
            )
    );
}
 
Example #6
Source File: RootRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Route buildRoute() {
    return wrapWithRootDirectives(correlationId ->
            parameterMap(queryParameters ->
                    extractRequestContext(ctx ->
                            concat(
                                    statsRoute.buildStatsRoute(correlationId), // /stats
                                    cachingHealthRoute.buildHealthRoute(), // /health
                                    api(ctx, correlationId, queryParameters), // /api
                                    ws(ctx, correlationId), // /ws
                                    ownStatusRoute.buildStatusRoute(), // /status
                                    overallStatusRoute.buildOverallStatusRoute(), // /overall
                                    devopsRoute.buildDevOpsRoute(ctx, queryParameters) // /devops
                            )
                    )
            )
    );
}
 
Example #7
Source File: RootRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Route api(final RequestContext ctx, final CharSequence correlationId,
        final Map<String, String> queryParameters) {

    return rawPathPrefix(PathMatchers.slash().concat(HTTP_PATH_API_PREFIX), () -> // /api
            ensureSchemaVersion(apiVersion -> // /api/<apiVersion>
                    customApiRoutesProvider.unauthorized(apiVersion, correlationId).orElse(
                            apiAuthentication(apiVersion, correlationId, initialHeadersBuilder -> {
                                        final CompletionStage<DittoHeaders> dittoHeadersPromise =
                                                rootRouteHeadersStepBuilder
                                                        .withInitialDittoHeadersBuilder(initialHeadersBuilder)
                                                        .withRequestContext(ctx)
                                                        .withQueryParameters(queryParameters)
                                                        .build(CustomHeadersHandler.RequestType.API);

                                        return withDittoHeaders(dittoHeadersPromise,
                                                dittoHeaders -> buildApiSubRoutes(ctx, dittoHeaders));
                                    }
                            )
                    )
            )
    );
}
 
Example #8
Source File: RootRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Route ws(final RequestContext ctx, final CharSequence correlationId) {
    return rawPathPrefix(PathMatchers.slash().concat(WS_PATH_PREFIX), () -> // /ws
            ensureSchemaVersion(wsVersion -> // /ws/<wsVersion>
                    wsAuthentication(wsVersion, correlationId, initialHeadersBuilder -> {
                                final CompletionStage<DittoHeaders> dittoHeadersPromise =
                                        rootRouteHeadersStepBuilder
                                                .withInitialDittoHeadersBuilder(initialHeadersBuilder)
                                                .withRequestContext(ctx)
                                                .withQueryParameters(Collections.emptyMap())
                                                .build(CustomHeadersHandler.RequestType.WS);

                                return withDittoHeaders(dittoHeadersPromise, dittoHeaders -> {
                                    @Nullable final String userAgent = getUserAgentOrNull(ctx);
                                    final ProtocolAdapter chosenProtocolAdapter =
                                            protocolAdapterProvider.getProtocolAdapter(userAgent);
                                    return websocketRouteBuilder.build(wsVersion, correlationId, dittoHeaders,
                                            chosenProtocolAdapter);
                                });
                            }
                    )
            )
    );
}
 
Example #9
Source File: WhoamiRouteTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    final ActorSystem system = ActorSystem.create();
    final ProtocolAdapterProvider adapterProvider = ProtocolAdapterProvider.load(protocolConfig, system);

    final AuthorizationContext context = AuthorizationContext.newInstance(DittoAuthorizationContextType.JWT,
            AuthorizationSubject.newInstance(SubjectId.newInstance(SubjectIssuer.GOOGLE, "any-google-user")),
            AuthorizationSubject.newInstance(SubjectId.newInstance(SubjectIssuer.INTEGRATION, "any-integration-subject")));
    dittoHeaders = DittoHeaders.newBuilder()
            .correlationId(testName.getMethodName())
            .authorizationContext(context)
            .build();

    whoamiRoute = new WhoamiRoute(createDummyResponseActor(), system, httpConfig, commandConfig,
            adapterProvider.getHttpHeaderTranslator());
    final Route route = extractRequestContext(
            ctx -> whoamiRoute.buildWhoamiRoute(ctx, dittoHeaders));
    underTest = testRoute(route);
}
 
Example #10
Source File: ThingsRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Route thingsEntryAcl(final RequestContext ctx, final DittoHeaders dittoHeaders, final ThingId thingId) {
    return rawPathPrefix(PathMatchers.slash().concat(PATH_ACL), () -> // /things/<thingId>/acl
            pathEndOrSingleSlash(() ->
                    concat(
                            get(() -> // GET /things/<thingId>/acl
                                    handlePerRequest(ctx, RetrieveAcl.of(thingId, dittoHeaders))
                            ),
                            put(() -> // PUT /things/<thingId>/acl
                                    ensureMediaTypeJsonWithFallbacksThenExtractDataBytes(ctx, dittoHeaders,
                                            payloadSource ->
                                                    handlePerRequest(ctx, dittoHeaders, payloadSource, aclJson ->
                                                            ModifyAcl.of(thingId,
                                                                    ThingsModelFactory.newAcl(aclJson),
                                                                    dittoHeaders))
                                    )
                            )
                    )
            )
    );
}
 
Example #11
Source File: ThingsRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Route thingsEntryPolicyId(final RequestContext ctx, final DittoHeaders dittoHeaders,
        final ThingId thingId) {
    return path(PATH_POLICY_ID, () -> // /things/<thingId>/policyId
            concat(
                    get(() -> // GET /things/<thingId>/policyId
                            handlePerRequest(ctx, RetrievePolicyId.of(thingId, dittoHeaders))
                    ),
                    put(() -> // PUT /things/<thingId>/policyId
                            ensureMediaTypeJsonWithFallbacksThenExtractDataBytes(ctx, dittoHeaders,
                                    payloadSource ->
                                            handlePerRequest(ctx, dittoHeaders, payloadSource,
                                                    policyIdJson -> ModifyPolicyId.of(thingId,
                                                            PolicyId.of(
                                                                    Optional.of(JsonFactory.readFrom(policyIdJson))
                                                                            .filter(JsonValue::isString)
                                                                            .map(JsonValue::asString)
                                                                            .orElse(policyIdJson)), dittoHeaders)
                                            )
                            )
                    )
            )
    );
}
 
Example #12
Source File: DevOpsRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @return the {@code /devops} route.
 * @throws NullPointerException if any argument is {@code null}.
 */
public Route buildDevOpsRoute(final RequestContext ctx, final Map<String, String> queryParameters) {
    checkNotNull(ctx, "ctx");
    checkNotNull(queryParameters, "queryParameters");

    return rawPathPrefix(PathMatchers.slash().concat(PATH_DEVOPS), () -> {// /devops
        final DevOpsBasicAuthenticationDirective devOpsBasicAuthenticationDirective =
                DevOpsBasicAuthenticationDirective.getInstance(devOpsConfig);
        return devOpsBasicAuthenticationDirective.authenticateDevOpsBasic(REALM_DEVOPS,
                concat(
                        rawPathPrefix(PathMatchers.slash().concat(PATH_LOGGING),
                                () -> // /devops/logging
                                        logging(ctx, createHeaders(queryParameters))
                        ),
                        rawPathPrefix(PathMatchers.slash().concat(PATH_PIGGYBACK),
                                () -> // /devops/piggyback
                                        piggyback(ctx, createHeaders(queryParameters))
                        ),
                        rawPathPrefix(PathMatchers.slash().concat(PATH_CONFIG),
                                () -> // /devops/config
                                        config(ctx, createHeaders(queryParameters)))
                )
        );
    });
}
 
Example #13
Source File: PoliciesRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Route policyEntry(final RequestContext ctx, final DittoHeaders dittoHeaders, final PolicyId policyId) {
    return pathEndOrSingleSlash(() ->
            concat(
                    get(() -> // GET /policies/<policyId>
                            handlePerRequest(ctx, RetrievePolicy.of(policyId, dittoHeaders))
                    ),
                    put(() -> // PUT /policies/<policyId>
                            ensureMediaTypeJsonWithFallbacksThenExtractDataBytes(ctx, dittoHeaders,
                                    payloadSource ->
                                            handlePerRequest(ctx, dittoHeaders, payloadSource,
                                                    policyJson -> ModifyPolicy
                                                            .of(policyId, PoliciesModelFactory.newPolicy(
                                                                    createPolicyJsonObjectForPut(policyJson,
                                                                            policyId)),
                                                                    dittoHeaders)
                                            )
                            )
                    ),
                    delete(() -> // DELETE /policies/<policyId>
                            handlePerRequest(ctx, DeletePolicy.of(policyId, dittoHeaders))
                    )
            )
    );
}
 
Example #14
Source File: RequestTimeoutHandlingDirective.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Handles a request timeout.
 *
 * @param correlationId the correlation ID which will be added to the log.
 * @param inner the inner Route to wrap with the response headers.
 * @return the new Route wrapping {@code inner} with the response headers.
 */
public Route handleRequestTimeout(final CharSequence correlationId, final Supplier<Route> inner) {
    return Directives.extractActorSystem(actorSystem -> extractRequestContext(requestContext -> {
                final StartedTimer timer = TraceUtils.newHttpRoundTripTimer(requestContext.getRequest()).build();
                LOGGER.withCorrelationId(correlationId).debug("Started mutable timer <{}>.", timer);

                final Supplier<Route> innerWithTimer = () -> Directives.mapResponse(response -> {
                    final int statusCode = response.status().intValue();
                    if (timer.isRunning()) {
                        final StoppedTimer stoppedTimer = timer.tag(TracingTags.STATUS_CODE, statusCode).stop();
                        LOGGER.withCorrelationId(correlationId)
                                .debug("Finished timer <{}> with status <{}>.", timer, statusCode);
                        checkDurationWarning(stoppedTimer, correlationId);
                    }
                    return response;
                }, inner);

                return Directives.withRequestTimeoutResponse(request ->
                        doHandleRequestTimeout(correlationId, requestContext, timer), innerWithTimer);
            }
    ));
}
 
Example #15
Source File: DevOpsRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Route routeLogging(final RequestContext ctx,
        final String serviceName,
        final String instance,
        final DittoHeaders dittoHeaders) {

    return concat(
            get(() ->
                    handlePerRequest(ctx,
                            RetrieveLoggerConfig.ofAllKnownLoggers(serviceName, instance, dittoHeaders),
                            transformResponse(serviceName, instance)
                    )
            ),
            put(() ->
                    extractDataBytes(payloadSource ->
                            handlePerRequest(ctx, dittoHeaders, payloadSource,
                                    loggerConfigJson ->
                                            ChangeLogLevel.of(serviceName, instance,
                                                    ImmutableLoggerConfig.fromJson(loggerConfigJson), dittoHeaders),
                                    transformResponse(serviceName, instance)
                            )
                    )
            )
    );
}
 
Example #16
Source File: WebSocketRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Builds the {@code /ws} route.
 *
 * @return the {@code /ws} route.
 */
@Override
public Route build(final JsonSchemaVersion version,
        final CharSequence correlationId,
        final DittoHeaders dittoHeaders,
        final ProtocolAdapter chosenProtocolAdapter) {

    return Directives.extractUpgradeToWebSocket(
            upgradeToWebSocketHeader -> Directives.extractRequest(
                    request -> {
                        authorizationEnforcer.checkAuthorization(dittoHeaders);
                        return Directives.completeWithFuture(
                                createWebSocket(upgradeToWebSocketHeader, version, correlationId.toString(),
                                        dittoHeaders, chosenProtocolAdapter, request));
                    }));
}
 
Example #17
Source File: FeaturesRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route featuresEntryInboxOutbox(final RequestContext ctx, final DittoHeaders dittoHeaders,
        final ThingId thingId) {

    return rawPathPrefix(PathMatchers.slash().concat(PathMatchers.segment()), featureId ->
            // POST /features/{featureId}/<inbox|outbox>
            messagesRoute.buildFeaturesInboxOutboxRoute(ctx, dittoHeaders, thingId, featureId)
    );
}
 
Example #18
Source File: AbstractRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route increaseHttpRequestTimeout(final java.util.function.Function<Duration, Route> inner,
        final scala.concurrent.duration.Duration requestTimeout) {
    if (requestTimeout.isFinite()) {
        // adds some time in order to avoid race conditions with internal receiveTimeouts which shall return "408"
        // in case of message timeouts or "424" in case of requested-acks timeouts:
        final scala.concurrent.duration.Duration akkaHttpRequestTimeout = requestTimeout
                .plus(scala.concurrent.duration.Duration.create(5, TimeUnit.SECONDS));
        return withRequestTimeout(akkaHttpRequestTimeout, () ->
                inner.apply(Duration.ofMillis(requestTimeout.toMillis()))
        );
    } else {
        return inner.apply(Duration.ofMillis(Long.MAX_VALUE));
    }
}
 
Example #19
Source File: ThingsRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route thingsEntryAttributesEntry(final RequestContext ctx, final DittoHeaders dittoHeaders,
        final ThingId thingId) {

    return rawPathPrefix(PathMatchers.slash()
                    .concat(PATH_ATTRIBUTES)
                    .concat(PathMatchers.slash())
                    .concat(PathMatchers.remaining())
                    .map(path -> UriEncoding.decode(path, UriEncoding.EncodingType.RFC3986))
                    .map(path -> "/" + path), // Prepend slash to path to fail request with double slashes
            jsonPointerString -> concat(
                    get(() -> // GET /things/<thingId>/attributes/<attributePointerStr>
                            handlePerRequest(ctx,
                                    RetrieveAttribute.of(thingId, JsonFactory.newPointer(jsonPointerString),
                                            dittoHeaders))
                    ),
                    put(() -> // PUT /things/<thingId>/attributes/<attributePointerStr>
                            ensureMediaTypeJsonWithFallbacksThenExtractDataBytes(ctx, dittoHeaders,
                                    payloadSource ->
                                            handlePerRequest(ctx, dittoHeaders, payloadSource, attributeValueJson ->
                                                    ModifyAttribute.of(thingId,
                                                            JsonFactory.newPointer(jsonPointerString),
                                                            DittoJsonException.wrapJsonRuntimeException(() ->
                                                                    JsonFactory.readFrom(attributeValueJson)),
                                                            dittoHeaders))
                            )
                    ),
                    delete(() -> // DELETE /things/<thingId>/attributes/<attributePointerStr>
                            handlePerRequest(ctx,
                                    DeleteAttribute.of(thingId, JsonFactory.newPointer(jsonPointerString),
                                            dittoHeaders))
                    )
            )
    );
}
 
Example #20
Source File: PolicyEntriesRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route thingsEntryPolicyEntry(final RequestContext ctx, final DittoHeaders dittoHeaders,
        final PolicyId policyId) {

    return rawPathPrefix(PathMatchers.slash().concat(PathMatchers.segment()), label ->
            pathEndOrSingleSlash(() ->
                    concat(
                            get(() -> // GET /entries/<label>
                                    handlePerRequest(ctx,
                                            RetrievePolicyEntry.of(policyId,
                                                    Label.of(label),
                                                    dittoHeaders))
                            ),
                            put(() -> // PUT /entries/<label>
                                    ensureMediaTypeJsonWithFallbacksThenExtractDataBytes(ctx, dittoHeaders,
                                            payloadSource ->
                                                    handlePerRequest(ctx, dittoHeaders, payloadSource,
                                                            policyEntryJson -> ModifyPolicyEntry
                                                                    .of(policyId,
                                                                            createPolicyEntryForPut(policyEntryJson,
                                                                                    label), dittoHeaders))
                                    )
                            ),
                            delete(() -> // DELETE /entries/<label>
                                    handlePerRequest(ctx,
                                            DeletePolicyEntry.of(policyId, Label.of(label),
                                                    dittoHeaders)))
                    )
            )
    );
}
 
Example #21
Source File: FeaturesRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route featuresEntry(final RequestContext ctx, final DittoHeaders dittoHeaders, final ThingId thingId) {
    return rawPathPrefix(PathMatchers.slash().concat(PathMatchers.segment()), featureId ->
            pathEndOrSingleSlash(() ->
                    concat(
                            get(() -> // GET /features/{featureId}?fields=<fieldsString>
                                    parameterOptional(ThingsParameter.FIELDS.toString(),
                                            fieldsString ->
                                                    handlePerRequest(ctx,
                                                            RetrieveFeature.of(thingId, featureId,
                                                                    calculateSelectedFields(
                                                                            fieldsString).orElse(
                                                                            null), dittoHeaders))
                                    )
                            ),
                            put(() -> // PUT /features/<featureId>
                                    ensureMediaTypeJsonWithFallbacksThenExtractDataBytes(ctx, dittoHeaders,
                                            payloadSource ->
                                            handlePerRequest(ctx, dittoHeaders, payloadSource,
                                                    featureJson ->
                                                            ModifyFeature.of(thingId,
                                                                    ThingsModelFactory
                                                                            .newFeatureBuilder(
                                                                                    featureJson)
                                                                            .useId(featureId)
                                                                            .build(),
                                                                    dittoHeaders))
                                    )
                            ),
                            delete(() -> // DELETE /features/<featureId>
                                    handlePerRequest(ctx,
                                            DeleteFeature.of(thingId, featureId, dittoHeaders))
                            )
                    )
            )
    );
}
 
Example #22
Source File: PoliciesRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Builds the {@code /policies} route.
 *
 * @return the {@code /policies} route.
 */
public Route buildPoliciesRoute(final RequestContext ctx, final DittoHeaders dittoHeaders) {
    return rawPathPrefix(PathMatchers.slash().concat(PATH_POLICIES), () ->
            rawPathPrefix(PathMatchers.slash().concat(PathMatchers.segment()), policyId ->
                    // /policies/<policyId>
                    policyRoute(ctx, dittoHeaders, PolicyId.of(policyId))
            )
    );
}
 
Example #23
Source File: ThingsRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Builds the {@code /things} route.
 *
 * @return the {@code /things} route.
 */
public Route buildThingsRoute(final RequestContext ctx, final DittoHeaders dittoHeaders) {
    return rawPathPrefix(PathMatchers.slash().concat(PATH_THINGS), () ->
            concat(
                    things(ctx, dittoHeaders),
                    rawPathPrefix(PathMatchers.slash().concat(PathMatchers.segment()),
                            // /things/<thingId>
                            thingId -> buildThingEntryRoute(ctx, dittoHeaders, ThingId.of(thingId))
                    )
            )
    );
}
 
Example #24
Source File: RequestResultLoggingDirective.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Logs the StatusCode and duration of the route.
 *
 * @param correlationId the correlationId which will be added to the log
 * @param inner the inner Route to be logged
 * @return the new Route wrapping {@code inner} with logging
 */
public static Route logRequestResult(final CharSequence correlationId, final Supplier<Route> inner) {
    // add akka standard logging to the route
    final Supplier<Route> innerWithAkkaLoggingRoute = () -> logRequest("http-request", () ->
            logResult("http-response", inner));

    // add our own logging with time measurement and creating a kamon trace
    // code is inspired by DebuggingDirectives#logRequestResult
    return extractRequest(request -> {
        final String requestMethod = request.method().name();
        final String requestUri = request.getUri().toRelative().toString();
        return mapRouteResult(routeResult -> {
            try (final AutoCloseableSlf4jLogger logger = LOGGER.setCorrelationId(correlationId)) {
                if (routeResult instanceof Complete) {
                    final Complete complete = (Complete) routeResult;
                    final int statusCode = complete.getResponse().status().intValue();
                    logger.info("StatusCode of request {} '{}' was: {}", requestMethod, requestUri, statusCode);
                    final String rawRequestUri = HttpUtils.getRawRequestUri(request);
                    logger.debug("Raw request URI was: {}", rawRequestUri);
                    request.getHeader(DITTO_TRACE_HEADERS)
                            .filter(unused -> TRACE_LOGGER.isDebugEnabled())
                            .ifPresent(unused -> TRACE_LOGGER.withCorrelationId(correlationId)
                                    .debug("Request headers: {}", request.getHeaders()));
                } else {
                     /* routeResult could be Rejected, if no route is able to handle the request -> but this should
                        not happen when rejections are handled before this directive is called. */
                    logger.warn("Unexpected routeResult for request {} '{}': {}, routeResult will be handled by " +
                                    "akka default RejectionHandler.", requestMethod, requestUri,
                            routeResult);
                }

                return routeResult;
            }
        }, innerWithAkkaLoggingRoute);
    });
}
 
Example #25
Source File: StatsRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route handleDevOpsPerRequest(final RequestContext ctx,
        final Source<ByteString, ?> payloadSource,
        final Function<String, DevOpsCommand<?>> requestJsonToCommandFunction) {
    final CompletableFuture<HttpResponse> httpResponseFuture = new CompletableFuture<>();

    payloadSource
            .fold(ByteString.empty(), ByteString::concat)
            .map(ByteString::utf8String)
            .map(requestJsonToCommandFunction)
            .to(Sink.actorRef(createHttpPerRequestActor(ctx, httpResponseFuture),
                    AbstractHttpRequestActor.COMPLETE_MESSAGE))
            .run(materializer);

    return completeWithFuture(httpResponseFuture);
}
 
Example #26
Source File: ThingSearchRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route countThings(final RequestContext ctx, final DittoHeaders dittoHeaders) {
    // GET things/count?filter=<filterString>&namespaces=<namespacesString>
    return get(() -> thingSearchParameterOptional(params -> handlePerRequest(ctx,
            CountThings.of(calculateFilter(params.get(FILTER)),
                    calculateNamespaces(params.get(NAMESPACES)),
                    dittoHeaders))));
}
 
Example #27
Source File: GatewayAuthenticationDirective.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route handleFailedAuthentication(final Throwable reasonOfFailure, final Uri requestUri,
        final DittoHeaders dittoHeaders) {

    if (reasonOfFailure instanceof DittoRuntimeException) {
        LOGGER.debug("Authentication for URI <{}> failed. Rethrow DittoRuntimeException.", requestUri,
                reasonOfFailure);
        throw (DittoRuntimeException) reasonOfFailure;
    }

    LOGGER.debug("Unexpected error during authentication for URI <{}>! Applying unauthorizedDirective",
            requestUri, reasonOfFailure);
    throw defaultUnauthorizedExceptionFactory.apply(dittoHeaders);
}
 
Example #28
Source File: ThingSearchRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route thingSearchParameterOptionalImpl(final ThingSearchParameter[] values,
        final EnumMap<ThingSearchParameter, Optional<String>> accumulator,
        final Function<EnumMap<ThingSearchParameter, Optional<String>>, Route> inner) {

    if (accumulator.size() >= values.length) {
        return inner.apply(accumulator);
    } else {
        final ThingSearchParameter parameter = values[accumulator.size()];
        return parameterOptional(parameter.toString(), parameterValueOptional -> {
            accumulator.put(parameter, parameterValueOptional);
            return thingSearchParameterOptionalImpl(values, accumulator, inner);
        });
    }
}
 
Example #29
Source File: CachingHealthRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Builds the {@code /health} route.
 *
 * @return the {@code /health} route.
 */
public Route buildHealthRoute() {
    return path(PATH_HEALTH, () -> // /health
            get(() -> // GET
                    completeWithFuture(createOverallHealthResponse())
            )
    );
}
 
Example #30
Source File: ThingSearchRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Builds the {@code /search} route.
 *
 * @return the {@code /search}} route.
 */
public Route buildSearchRoute(final RequestContext ctx, final DittoHeaders dittoHeaders) {
    return Directives.rawPathPrefix(PathMatchers.slash().concat(PATH_SEARCH), () ->
            Directives.rawPathPrefix(PathMatchers.slash().concat(PATH_THINGS),
                    () -> // /search/things
                            concat(
                                    // /search/things/count
                                    path(PATH_COUNT, () -> countThings(ctx, dittoHeaders)),
                                    // /search/things
                                    pathEndOrSingleSlash(() -> searchThings(ctx, dittoHeaders))
                            )
            )
    );
}