From f98c1946d8993f85dbf8aa9511ef2bace1f4cd65 Mon Sep 17 00:00:00 2001 From: Hawstein Date: Fri, 3 Jun 2016 19:43:42 +0800 Subject: [PATCH] +doc #20466 example snippet for akka http java dsl: BasicDirectives (#20647) --- .../BasicDirectivesExamplesTest.java | 788 ++++++++++++++++++ .../basic-directives/cancelRejection.rst | 3 +- .../basic-directives/cancelRejections.rst | 3 +- .../directives/basic-directives/extract.rst | 3 +- .../extractExecutionContext.rst | 3 +- .../basic-directives/extractLog.rst | 3 +- .../basic-directives/extractMaterializer.rst | 3 +- .../basic-directives/extractRequest.rst | 3 +- .../extractRequestContext.rst | 3 +- .../basic-directives/extractSettings.rst | 3 +- .../basic-directives/extractUnmatchedPath.rst | 3 +- .../basic-directives/extractUri.rst | 3 +- .../basic-directives/mapInnerRoute.rst | 3 +- .../basic-directives/mapRejections.rst | 3 +- .../basic-directives/mapRequest.rst | 3 +- .../basic-directives/mapRequestContext.rst | 3 +- .../basic-directives/mapResponse.rst | 6 +- .../basic-directives/mapResponseEntity.rst | 3 +- .../basic-directives/mapResponseHeaders.rst | 3 +- .../basic-directives/mapRouteResult.rst | 3 +- .../basic-directives/mapRouteResultFuture.rst | 3 +- .../basic-directives/mapRouteResultPF.rst | 4 +- .../basic-directives/mapRouteResultWith.rst | 3 +- .../basic-directives/mapRouteResultWithPF.rst | 3 +- .../basic-directives/mapSettings.rst | 3 +- .../basic-directives/mapUnmatchedPath.rst | 3 +- .../directives/basic-directives/pass.rst | 3 +- .../directives/basic-directives/provide.rst | 3 +- .../basic-directives/recoverRejections.rst | 3 +- .../recoverRejectionsWith.rst | 3 +- .../basic-directives/withExecutionContext.rst | 3 +- .../directives/basic-directives/withLog.rst | 3 +- .../basic-directives/withMaterializer.rst | 3 +- .../basic-directives/withSettings.rst | 4 +- .../BasicDirectivesExamplesSpec.scala | 24 +- .../javadsl/testkit/TestRouteResult.scala | 11 +- .../http/javadsl/server/RouteResult.scala | 18 + .../server/directives/BasicDirectives.scala | 21 +- 38 files changed, 914 insertions(+), 52 deletions(-) create mode 100644 akka-docs/rst/java/code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java diff --git a/akka-docs/rst/java/code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java b/akka-docs/rst/java/code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java new file mode 100644 index 0000000000..fa5a520460 --- /dev/null +++ b/akka-docs/rst/java/code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java @@ -0,0 +1,788 @@ +/* + * Copyright (C) 2016-2016 Lightbend Inc. + */ +package docs.http.javadsl.server.directives; + +import akka.actor.ActorSystem; +import akka.dispatch.ExecutionContexts; +import akka.event.Logging; +import akka.event.LoggingAdapter; +import akka.http.javadsl.model.ContentTypes; +import akka.http.javadsl.model.HttpEntities; +import akka.http.javadsl.model.HttpEntity; +import akka.http.javadsl.model.HttpMethods; +import akka.http.javadsl.model.HttpRequest; +import akka.http.javadsl.model.HttpResponse; +import akka.http.javadsl.model.ResponseEntity; +import akka.http.javadsl.model.StatusCodes; +import akka.http.javadsl.model.headers.RawHeader; +import akka.http.javadsl.model.headers.Server; +import akka.http.javadsl.model.headers.ProductVersion; +import akka.http.javadsl.settings.RoutingSettings; +import akka.http.javadsl.testkit.JUnitRouteTest; +import akka.http.javadsl.server.*; +import akka.japi.pf.PFBuilder; +import akka.stream.ActorMaterializer; +import akka.stream.ActorMaterializerSettings; +import akka.stream.javadsl.FileIO; +import akka.stream.javadsl.Sink; +import akka.stream.javadsl.Source; +import akka.util.ByteString; +import org.junit.Ignore; +import org.junit.Test; +import scala.concurrent.ExecutionContextExecutor; + +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Collections; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executors; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.StreamSupport; + +public class BasicDirectivesExamplesTest extends JUnitRouteTest { + + @Test + public void testExtract() { + //#extract + final Route route = extract( + ctx -> ctx.getRequest().getUri().toString().length(), + len -> complete("The length of the request URI is " + len) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/abcdef")) + .assertEntity("The length of the request URI is 25"); + //#extract + } + + @Test + public void testExtractLog() { + //#extractLog + final Route route = extractLog(log -> { + log.debug("I'm logging things in much detail..!"); + return complete("It's amazing!"); + }); + + // tests: + testRoute(route).run(HttpRequest.GET("/abcdef")) + .assertEntity("It's amazing!"); + //#extractLog + } + + @Test + public void testWithMaterializer() { + //#withMaterializer + final ActorMaterializerSettings settings = ActorMaterializerSettings.create(system()); + final ActorMaterializer special = ActorMaterializer.create(settings, system(), "special"); + + final Route sample = path("sample", () -> + extractMaterializer(mat -> + onSuccess(() -> + // explicitly use the materializer: + Source.single("Materialized by " + mat.hashCode() + "!") + .runWith(Sink.head(), mat), this::complete + ) + ) + ); + + final Route route = route( + pathPrefix("special", () -> + withMaterializer(special, () -> sample) // `special` materializer will be used + ), + sample // default materializer will be used + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/sample")) + .assertEntity("Materialized by " + materializer().hashCode()+ "!"); + testRoute(route).run(HttpRequest.GET("/special/sample")) + .assertEntity("Materialized by " + special.hashCode()+ "!"); + //#withMaterializer + } + + @Test + public void testExtractMaterializer() { + //#extractMaterializer + final Route route = path("sample", () -> + extractMaterializer(mat -> + onSuccess(() -> + // explicitly use the materializer: + Source.single("Materialized by " + mat.hashCode() + "!") + .runWith(Sink.head(), mat), this::complete + ) + ) + ); // default materializer will be used + + testRoute(route).run(HttpRequest.GET("/sample")) + .assertEntity("Materialized by " + materializer().hashCode()+ "!"); + //#extractMaterializer + } + + @Test + public void testWithExecutionContext() { + //#withExecutionContext + + final ExecutionContextExecutor special = + ExecutionContexts.fromExecutor(Executors.newFixedThreadPool(1)); + + final Route sample = path("sample", () -> + extractExecutionContext(executor -> + onSuccess(() -> + CompletableFuture.supplyAsync(() -> + "Run on " + executor.hashCode() + "!", executor + ), this::complete + ) + ) + ); + + final Route route = route( + pathPrefix("special", () -> + // `special` execution context will be used + withExecutionContext(special, () -> sample) + ), + sample // default execution context will be used + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/sample")) + .assertEntity("Run on " + system().dispatcher().hashCode() + "!"); + testRoute(route).run(HttpRequest.GET("/special/sample")) + .assertEntity("Run on " + special.hashCode() + "!"); + //#withExecutionContext + } + + @Test + public void testExtractExecutionContext() { + //#extractExecutionContext + final Route route = path("sample", () -> + extractExecutionContext(executor -> + onSuccess(() -> + CompletableFuture.supplyAsync( + // uses the `executor` ExecutionContext + () -> "Run on " + executor.hashCode() + "!", executor + ), str -> complete(str) + ) + ) + ); + + //tests: + testRoute(route).run(HttpRequest.GET("/sample")) + .assertEntity("Run on " + system().dispatcher().hashCode() + "!"); + //#extractExecutionContext + } + + @Test + public void testWithLog() { + //#withLog + final LoggingAdapter special = Logging.getLogger(system(), "SpecialRoutes"); + + final Route sample = path("sample", () -> + extractLog(log -> { + final String msg = "Logging using " + log + "!"; + log.debug(msg); + return complete(msg); + } + ) + ); + + final Route route = route( + pathPrefix("special", () -> + withLog(special, () -> sample) + ), + sample + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/sample")) + .assertEntity("Logging using " + system().log() + "!"); + testRoute(route).run(HttpRequest.GET("/special/sample")) + .assertEntity("Logging using " + special + "!"); + //#withLog + } + + @Ignore("Ignore compile-only test") + @Test + public void testWithSettings() { + //#withSettings + final RoutingSettings special = + RoutingSettings + .create(system().settings().config()) + .withFileIODispatcher("special-io-dispatcher"); + + final Route sample = path("sample", () -> { + // internally uses the configured fileIODispatcher: + // ContentTypes.APPLICATION_JSON, source + final Source source = + FileIO.fromPath(Paths.get("example.json")) + .mapMaterializedValue(completionStage -> (Object) completionStage); + return complete( + HttpResponse.create() + .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, source)) + ); + }); + + final Route route = get(() -> + route( + pathPrefix("special", () -> + // `special` file-io-dispatcher will be used to read the file + withSettings(special, () -> sample) + ), + sample // default file-io-dispatcher will be used to read the file + ) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/special/sample")) + .assertEntity("{}"); + testRoute(route).run(HttpRequest.GET("/sample")) + .assertEntity("{}"); + //#withSettings + } + + @Test + public void testMapResponse() { + //#mapResponse + final Route route = mapResponse( + response -> response.withStatus(StatusCodes.BAD_GATEWAY), + () -> complete("abc") + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/abcdef?ghi=12")) + .assertStatusCode(StatusCodes.BAD_GATEWAY); + //#mapResponse + } + + @Test + public void testMapResponseAdvanced() { + //#mapResponse-advanced + class ApiRoute { + + private final ActorSystem system; + + private final LoggingAdapter log; + + private final HttpEntity nullJsonEntity = + HttpEntities.create(ContentTypes.APPLICATION_JSON, "{}"); + + public ApiRoute(ActorSystem system) { + this.system = system; + this.log = Logging.getLogger(system, "ApiRoutes"); + } + + private HttpResponse nonSuccessToEmptyJsonEntity(HttpResponse response) { + if (response.status().isSuccess()) { + return response; + } else { + log.warning( + "Dropping response entity since response status code was: " + response.status()); + return response.withEntity((ResponseEntity) nullJsonEntity); + } + } + + /** Wrapper for all of our JSON API routes */ + private Route apiRoute(Supplier innerRoutes) { + return mapResponse(this::nonSuccessToEmptyJsonEntity, innerRoutes); + } + } + + final ApiRoute api = new ApiRoute(system()); + + final Route route = api.apiRoute(() -> + get(() -> complete(StatusCodes.INTERNAL_SERVER_ERROR)) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("{}"); + //#mapResponse-advanced + } + + @Test + public void testMapRouteResult() { + //#mapRouteResult + // this directive is a joke, don't do that :-) + final Route route = mapRouteResult(r -> { + if (r instanceof Complete) { + final HttpResponse response = ((Complete) r).getResponse(); + return RouteResults.complete(response.withStatus(200)); + } else { + return r; + } + }, () -> complete(StatusCodes.ACCEPTED)); + + // tests: + testRoute(route).run(HttpRequest.GET("/")) + .assertStatusCode(StatusCodes.OK); + //#mapRouteResult + } + + @Test + public void testMapRouteResultFuture() { + //#mapRouteResultFuture + final Route route = mapRouteResultFuture(cr -> + cr.exceptionally(t -> { + if (t instanceof IllegalArgumentException) { + return RouteResults.complete( + HttpResponse.create().withStatus(StatusCodes.INTERNAL_SERVER_ERROR)); + } else { + return null; + } + }).thenApply(rr -> { + if (rr instanceof Complete) { + final HttpResponse res = ((Complete) rr).getResponse(); + return RouteResults.complete( + res.addHeader(Server.create(ProductVersion.create("MyServer", "1.0")))); + } else { + return rr; + } + }), () -> complete("Hello world!")); + + // tests: + testRoute(route).run(HttpRequest.GET("/")) + .assertStatusCode(StatusCodes.OK) + .assertHeaderExists(Server.create(ProductVersion.create("MyServer", "1.0"))); + //#mapRouteResultFuture + } + + @Test + public void testMapResponseEntity() { + //#mapResponseEntity + final Function prefixEntity = entity -> { + if (entity instanceof HttpEntity.Strict) { + final HttpEntity.Strict strict = (HttpEntity.Strict) entity; + return HttpEntities.create( + strict.getContentType(), + ByteString.fromString("test").concat(strict.getData())); + } else { + throw new IllegalStateException("Unexpected entity type"); + } + }; + + final Route route = mapResponseEntity(prefixEntity, () -> complete("abc")); + + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("testabc"); + //#mapResponseEntity + } + + @Test + public void testMapResponseHeaders() { + //#mapResponseHeaders + // adds all request headers to the response + final Route echoRequestHeaders = extract( + ctx -> ctx.getRequest().getHeaders(), + headers -> respondWithHeaders(headers, () -> complete("test")) + ); + + final Route route = mapResponseHeaders(headers -> { + headers.removeIf(header -> header.lowercaseName().equals("id")); + return headers; + }, () -> echoRequestHeaders); + + // tests: + testRoute(route).run(HttpRequest.GET("/").addHeaders( + Arrays.asList(RawHeader.create("id", "12345"),RawHeader.create("id2", "67890")))) + .assertHeaderKindNotExists("id") + .assertHeaderExists("id2", "67890"); + //#mapResponseHeaders + } + + @Ignore("Not implemented yet") + @Test + public void testMapInnerRoute() { + //#mapInnerRoute + // TODO: implement mapInnerRoute + //#mapInnerRoute + } + + @Test + public void testMapRejections() { + //#mapRejections + // ignore any rejections and replace them by AuthorizationFailedRejection + final Route route = mapRejections( + rejections -> Collections.singletonList((Rejection) Rejections.authorizationFailed()), + () -> path("abc", () -> complete("abc")) + ); + + // tests: + runRouteUnSealed(route, HttpRequest.GET("/")) + .assertRejections(Rejections.authorizationFailed()); + testRoute(route).run(HttpRequest.GET("/abc")) + .assertStatusCode(StatusCodes.OK); + //#mapRejections + } + + @Test + public void testRecoverRejections() { + //#recoverRejections + final Function, Optional> neverAuth = + creds -> Optional.empty(); + final Function, Optional> alwaysAuth = + creds -> Optional.of("id"); + + final Route originalRoute = pathPrefix("auth", () -> + route( + path("never", () -> + authenticateBasic("my-realm", neverAuth, obj -> complete("Welcome to the bat-cave!")) + ), + path("always", () -> + authenticateBasic("my-realm", alwaysAuth, obj -> complete("Welcome to the secret place!")) + ) + ) + ); + + final Function, Boolean> existsAuthenticationFailedRejection = + rejections -> + StreamSupport.stream(rejections.spliterator(), false) + .anyMatch(r -> r instanceof AuthenticationFailedRejection); + + final Route route = recoverRejections(rejections -> { + if (existsAuthenticationFailedRejection.apply(rejections)) { + return RouteResults.complete( + HttpResponse.create().withEntity("Nothing to see here, move along.")); + } else if (!rejections.iterator().hasNext()) { // see "Empty Rejections" for more details + return RouteResults.complete( + HttpResponse.create().withStatus(StatusCodes.NOT_FOUND) + .withEntity("Literally nothing to see here.")); + } else { + return RouteResults.rejected(rejections); + } + }, () -> originalRoute); + + // tests: + testRoute(route).run(HttpRequest.GET("/auth/never")) + .assertStatusCode(StatusCodes.OK) + .assertEntity("Nothing to see here, move along."); + testRoute(route).run(HttpRequest.GET("/auth/always")) + .assertStatusCode(StatusCodes.OK) + .assertEntity("Welcome to the secret place!"); + testRoute(route).run(HttpRequest.GET("/auth/does_not_exist")) + .assertStatusCode(StatusCodes.NOT_FOUND) + .assertEntity("Literally nothing to see here."); + //#recoverRejections + } + + @Test + public void testRecoverRejectionsWith() { + //#recoverRejectionsWith + final Function, Optional> neverAuth = + creds -> Optional.empty(); + + final Route originalRoute = pathPrefix("auth", () -> + path("never", () -> + authenticateBasic("my-realm", neverAuth, obj -> complete("Welcome to the bat-cave!")) + ) + ); + + final Function, Boolean> existsAuthenticationFailedRejection = + rejections -> + StreamSupport.stream(rejections.spliterator(), false) + .anyMatch(r -> r instanceof AuthenticationFailedRejection); + + final Route route = recoverRejectionsWith( + rejections -> CompletableFuture.supplyAsync(() -> { + if (existsAuthenticationFailedRejection.apply(rejections)) { + return RouteResults.complete( + HttpResponse.create().withEntity("Nothing to see here, move along.")); + } else { + return RouteResults.rejected(rejections); + } + }), () -> originalRoute); + + // tests: + testRoute(route).run(HttpRequest.GET("/auth/never")) + .assertStatusCode(StatusCodes.OK) + .assertEntity("Nothing to see here, move along."); + //#recoverRejectionsWith + } + + @Test + public void testMapRequest() { + //#mapRequest + final Route route = mapRequest(req -> + req.withMethod(HttpMethods.POST), () -> + extractRequest(req -> complete("The request method was " + req.method().name())) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("The request method was POST"); + //#mapRequest + } + + @Test + public void testMapRequestContext() { + //#mapRequestContext + final Route route = mapRequestContext(ctx -> + ctx.withRequest(HttpRequest.create().withMethod(HttpMethods.POST)), () -> + extractRequest(req -> complete(req.method().value())) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/abc/def/ghi")) + .assertEntity("POST"); + //#mapRequestContext + } + + @Test + public void testMapRouteResult0() { + //#mapRouteResult + final Route route = mapRouteResult(rr -> { + final Iterable rejections = Collections.singletonList(Rejections.authorizationFailed()); + return RouteResults.rejected(rejections); + }, () -> complete("abc")); + + // tests: + runRouteUnSealed(route, HttpRequest.GET("/")) + .assertRejections(Rejections.authorizationFailed()); + //#mapRouteResult + } + + public static final class MyCustomRejection implements akka.http.scaladsl.server.Rejection {} + + @Test + public void testMapRouteResultPF() { + //#mapRouteResultPF + final Route route = mapRouteResultPF( + new PFBuilder() + .match(Rejected.class, rejected -> { + final Iterable rejections = + Collections.singletonList(Rejections.authorizationFailed()); + return RouteResults.rejected(rejections); + }).build(), () -> reject(new MyCustomRejection())); + + // tests: + runRouteUnSealed(route, HttpRequest.GET("/")) + .assertRejections(Rejections.authorizationFailed()); + //#mapRouteResultPF + } + + @Test + public void testMapRouteResultWithPF() { + //#mapRouteResultWithPF + final Route route = mapRouteResultWithPF( + new PFBuilder>() + .match(Rejected.class, rejected -> CompletableFuture.supplyAsync(() -> { + final Iterable rejections = + Collections.singletonList(Rejections.authorizationFailed()); + return RouteResults.rejected(rejections); + }) + ).build(), () -> reject(new MyCustomRejection())); + + // tests: + runRouteUnSealed(route, HttpRequest.GET("/")) + .assertRejections(Rejections.authorizationFailed()); + //#mapRouteResultWithPF + } + + @Test + public void testMapRouteResultWith() { + //#mapRouteResultWith + final Route route = mapRouteResultWith(rr -> CompletableFuture.supplyAsync(() -> { + if (rr instanceof Rejected) { + final Iterable rejections = + Collections.singletonList(Rejections.authorizationFailed()); + return RouteResults.rejected(rejections); + } else { + return rr; + } + }), () -> reject(new MyCustomRejection())); + + // tests: + runRouteUnSealed(route, HttpRequest.GET("/")) + .assertRejections(Rejections.authorizationFailed()); + //#mapRouteResultWith + } + + @Test + public void testPass() { + //#pass + final Route route = pass(() -> complete("abc")); + + // tests: + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("abc"); + //#pass + } + + private Route providePrefixedStringRoute(String value) { + return provide("prefix:" + value, this::complete); + } + + @Test + public void testProvide() { + //#provide + final Route route = providePrefixedStringRoute("test"); + + // tests: + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("prefix:test"); + //#provide + } + + @Ignore("Test failed") + @Test + public void testCancelRejections() { + //#cancelRejections + final Predicate isMethodRejection = p -> p instanceof MethodRejection; + final Route route = cancelRejections( + isMethodRejection, () -> post(() -> complete("Result")) + ); + + // tests: + runRouteUnSealed(route, HttpRequest.GET("/")) + .assertRejections(); + //#cancelRejections + } + + @Ignore("Test failed") + @Test + public void testCancelRejection() { + //#cancelRejection + final Route route = cancelRejection(Rejections.method(HttpMethods.POST), () -> + post(() -> complete("Result")) + ); + + // tests: + runRouteUnSealed(route, HttpRequest.GET("/")) + .assertRejections(); + //#cancelRejection + } + + @Test + public void testExtractRequest() { + //#extractRequest + final Route route = extractRequest(request -> + complete("Request method is " + request.method().name() + + " and content-type is " + request.entity().getContentType()) + ); + + // tests: + testRoute(route).run(HttpRequest.POST("/").withEntity("text")) + .assertEntity("Request method is POST and content-type is text/plain; charset=UTF-8"); + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("Request method is GET and content-type is none/none"); + //#extractRequest + } + + @Test + public void testExtractSettings() { + //#extractSettings + final Route route = extractSettings(settings -> + complete("RoutingSettings.renderVanityFooter = " + settings.getRenderVanityFooter()) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("RoutingSettings.renderVanityFooter = true"); + //#extractSettings + } + + @Test + public void testMapSettings() { + //#mapSettings + final Route route = mapSettings(settings -> + settings.withFileGetConditional(false), () -> + extractSettings(settings -> + complete("RoutingSettings.fileGetConditional = " + settings.getFileGetConditional()) + ) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("RoutingSettings.fileGetConditional = false"); + //#mapSettings + } + + @Test + public void testExtractRequestContext() { + //#extractRequestContext + final Route route = extractRequestContext(ctx -> { + ctx.getLog().debug("Using access to additional context availablethings, like the logger."); + final HttpRequest request = ctx.getRequest(); + return complete("Request method is " + request.method().name() + + " and content-type is " + request.entity().getContentType()); + }); + + // tests: + testRoute(route).run(HttpRequest.POST("/").withEntity("text")) + .assertEntity("Request method is POST and content-type is text/plain; charset=UTF-8"); + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("Request method is GET and content-type is none/none"); + //#extractRequestContext + } + + @Test + public void testExtractUri() { + //#extractUri + final Route route = extractUri(uri -> + complete("Full URI: " + uri) + ); + + // tests: + // tests are executed with the host assumed to be "example.com" + testRoute(route).run(HttpRequest.GET("/")) + .assertEntity("Full URI: http://example.com/"); + testRoute(route).run(HttpRequest.GET("/test")) + .assertEntity("Full URI: http://example.com/test"); + //#extractUri + } + + @Test + public void testMapUnmatchedPath() { + //#mapUnmatchedPath + final Function ignore456 = path -> { + int slashPos = path.indexOf("/"); + if (slashPos != -1) { + String head = path.substring(0, slashPos); + String tail = path.substring(slashPos); + if (head.length() <= 3) { + return tail; + } else { + return path.substring(3); + } + } else { + return path; + } + }; + + final Route route = pathPrefix("123", () -> + mapUnmatchedPath(ignore456, () -> + path("abc", () -> + complete("Content") + ) + ) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/123/abc")) + .assertEntity("Content"); + testRoute(route).run(HttpRequest.GET("/123456/abc")) + .assertEntity("Content"); + //#mapUnmatchedPath + } + + @Test + public void testExtractUnmatchedPath() { + //#extractUnmatchedPath + final Route route = pathPrefix("abc", () -> + extractUnmatchedPath(remaining -> + complete("Unmatched: '" + remaining + "'") + ) + ); + + // tests: + testRoute(route).run(HttpRequest.GET("/abc")) + .assertEntity("Unmatched: ''"); + testRoute(route).run(HttpRequest.GET("/abc/456")) + .assertEntity("Unmatched: '/456'"); + //#extractUnmatchedPath + } + +} diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/cancelRejection.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/cancelRejection.rst index 8651b87a71..f1912765e2 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/cancelRejection.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/cancelRejection.rst @@ -16,4 +16,5 @@ which provides a nicer DSL for building rejection handlers. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#cancelRejection diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/cancelRejections.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/cancelRejections.rst index c91ae5649f..5204437de4 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/cancelRejections.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/cancelRejections.rst @@ -18,4 +18,5 @@ which provides a nicer DSL for building rejection handlers. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#cancelRejections diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extract.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extract.rst index 45bfebf4d0..4896f35e98 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extract.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extract.rst @@ -13,4 +13,5 @@ See :ref:`ProvideDirectives-java` for an overview of similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extract diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractExecutionContext.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractExecutionContext.rst index 878538ca6e..ad37d1975c 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractExecutionContext.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractExecutionContext.rst @@ -14,4 +14,5 @@ See :ref:`-extract-java-` to learn more about how extractions work. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extractExecutionContext diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractLog.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractLog.rst index 02e3d7b825..939090ea95 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractLog.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractLog.rst @@ -15,4 +15,5 @@ See :ref:`-extract-java-` and :ref:`ProvideDirectives-java` for an overview of s Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extractLog diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractMaterializer.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractMaterializer.rst index 447a0698d6..f1ede20d2f 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractMaterializer.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractMaterializer.rst @@ -13,4 +13,5 @@ See also :ref:`-withMaterializer-java-` to see how to customise the used materia Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extractMaterializer diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractRequest.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractRequest.rst index ac990e314a..91c532ea11 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractRequest.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractRequest.rst @@ -13,4 +13,5 @@ directives. See :ref:`Request Directives-java`. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extractRequest diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractRequestContext.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractRequestContext.rst index 44d1efa7f3..3abec29650 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractRequestContext.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractRequestContext.rst @@ -16,4 +16,5 @@ See also :ref:`-extractRequest-java-` if only interested in the :class:`HttpRequ Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extractRequestContext diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractSettings.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractSettings.rst index a694279c5b..3983ba7e79 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractSettings.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractSettings.rst @@ -13,4 +13,5 @@ It is possible to override the settings for specific sub-routes by using the :re Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extractRequestContext diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractUnmatchedPath.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractUnmatchedPath.rst index a0a07266c4..4cabc34f83 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractUnmatchedPath.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractUnmatchedPath.rst @@ -15,4 +15,5 @@ Use ``mapUnmatchedPath`` to change the value of the unmatched path. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extractUnmatchedPath diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractUri.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractUri.rst index 875ab01f1e..38985f0d68 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractUri.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/extractUri.rst @@ -12,4 +12,5 @@ targeted access to parts of the URI. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#extractUri diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapInnerRoute.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapInnerRoute.rst index f2908a90e5..a88cb022bc 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapInnerRoute.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapInnerRoute.rst @@ -12,4 +12,5 @@ with any other route. Usually, the returned route wraps the original one with cu Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapInnerRoute diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRejections.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRejections.rst index 34fdf1d440..351e903cc5 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRejections.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRejections.rst @@ -16,4 +16,5 @@ See :ref:`Response Transforming Directives-java` for similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapRejections diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRequest.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRequest.rst index 87c3a8fa3b..a11e8ef1b8 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRequest.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRequest.rst @@ -16,4 +16,5 @@ See :ref:`Request Transforming Directives-java` for an overview of similar direc Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapRequest diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRequestContext.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRequestContext.rst index 39cd8cc3c7..f5546fa409 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRequestContext.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRequestContext.rst @@ -15,4 +15,5 @@ See :ref:`Request Transforming Directives-java` for an overview of similar direc Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapRequestContext diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponse.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponse.rst index c4a53d4466..912556d536 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponse.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponse.rst @@ -14,8 +14,10 @@ See also :ref:`-mapResponseHeaders-java-` or :ref:`-mapResponseEntity-java-` for Example: Override status ------------------------ -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapResponse Example: Default to empty JSON response on errors ------------------------------------------------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapResponse-advanced diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponseEntity.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponseEntity.rst index 8994140991..799c9618c5 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponseEntity.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponseEntity.rst @@ -13,4 +13,5 @@ See :ref:`Response Transforming Directives-java` for similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapResponseEntity diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponseHeaders.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponseHeaders.rst index eacf9bb0c1..fae2264127 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponseHeaders.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapResponseHeaders.rst @@ -14,4 +14,5 @@ See :ref:`Response Transforming Directives-java` for similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapResponseHeaders diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResult.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResult.rst index d440ba759d..764734e1f9 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResult.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResult.rst @@ -14,4 +14,5 @@ See :ref:`Result Transformation Directives-java` for similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapRouteResult diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultFuture.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultFuture.rst index 0a0e33b8c5..efc21b4515 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultFuture.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultFuture.rst @@ -17,4 +17,5 @@ See :ref:`Result Transformation Directives-java` for similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapRouteResultFuture diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultPF.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultPF.rst index 8ff60a8305..7ed461d4e3 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultPF.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultPF.rst @@ -17,4 +17,6 @@ See :ref:`Result Transformation Directives-java` for similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapRouteResultPF + diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultWith.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultWith.rst index b58e4de9ee..7757074126 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultWith.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultWith.rst @@ -16,4 +16,5 @@ See :ref:`Result Transformation Directives-java` for similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapRouteResultWith diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultWithPF.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultWithPF.rst index bf13964fac..e9f1c5d6eb 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultWithPF.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapRouteResultWithPF.rst @@ -17,4 +17,5 @@ See :ref:`Result Transformation Directives-java` for similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapRouteResultWithPF diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapSettings.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapSettings.rst index 763ca2fc73..b54127a8fc 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapSettings.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapSettings.rst @@ -12,4 +12,5 @@ See also :ref:`-withSettings-java-` or :ref:`-extractSettings-java-`. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapSettings diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapUnmatchedPath.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapUnmatchedPath.rst index 6cef0c4cc3..de38d61c31 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapUnmatchedPath.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/mapUnmatchedPath.rst @@ -14,4 +14,5 @@ Use ``extractUnmatchedPath`` for extracting the current value of the unmatched p Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#mapUnmatchedPath diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/pass.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/pass.rst index 3547026189..06dc518837 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/pass.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/pass.rst @@ -11,4 +11,5 @@ It is usually used as a "neutral element" when combining directives generically. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#pass diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/provide.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/provide.rst index 290f0f07ef..305ea9319a 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/provide.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/provide.rst @@ -13,4 +13,5 @@ See :ref:`ProvideDirectives-java` for an overview of similar directives. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#provide diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/recoverRejections.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/recoverRejections.rst index e561f9c515..78994357c8 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/recoverRejections.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/recoverRejections.rst @@ -17,4 +17,5 @@ rejections. Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#recoverRejections diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/recoverRejectionsWith.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/recoverRejectionsWith.rst index 7b010dbdbc..7220a2cfe7 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/recoverRejectionsWith.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/recoverRejectionsWith.rst @@ -20,4 +20,5 @@ See :ref:`-recoverRejections-java-` (the synchronous equivalent of this directiv Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#recoverRejectionsWith diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withExecutionContext.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withExecutionContext.rst index 746cdbb2be..d8de735585 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withExecutionContext.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withExecutionContext.rst @@ -14,4 +14,5 @@ or used by directives which internally extract the materializer without sufracin Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#withExecutionContext diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withLog.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withLog.rst index e183d088b9..e98d6ef0c2 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withLog.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withLog.rst @@ -14,4 +14,5 @@ or used by directives which internally extract the materializer without surfacin Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#withLog diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withMaterializer.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withMaterializer.rst index 8037dd11ff..510b02058e 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withMaterializer.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withMaterializer.rst @@ -14,4 +14,5 @@ or used by directives which internally extract the materializer without sufracin Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#withMaterializer diff --git a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withSettings.rst b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withSettings.rst index 362e269ab1..b284726c08 100644 --- a/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withSettings.rst +++ b/akka-docs/rst/java/http/routing-dsl/directives/basic-directives/withSettings.rst @@ -13,4 +13,6 @@ or used by directives which internally extract the materializer without sufracin Example ------- -TODO: Example snippets for JavaDSL are subject to community contributions! Help us complete the docs, read more about it here: `write example snippets for Akka HTTP Java DSL #20466 `_. + +.. includecode:: ../../../../code/docs/http/javadsl/server/directives/BasicDirectivesExamplesTest.java#withSettings + diff --git a/akka-docs/rst/scala/code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala b/akka-docs/rst/scala/code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala index 64b292a3a5..368a19328e 100644 --- a/akka-docs/rst/scala/code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala +++ b/akka-docs/rst/scala/code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala @@ -303,13 +303,11 @@ class BasicDirectivesExamplesSpec extends RoutingSpec { "mapRouteResult" in { //#mapRouteResult // this directive is a joke, don't do that :-) - val makeEverythingOk = mapRouteResult { r => - r match { - case Complete(response) => - // "Everything is OK!" - Complete(response.copy(status = 200)) - case _ => r - } + val makeEverythingOk = mapRouteResult { + case Complete(response) => + // "Everything is OK!" + Complete(response.copy(status = 200)) + case r => r } val route = @@ -591,11 +589,9 @@ class BasicDirectivesExamplesSpec extends RoutingSpec { //#mapRouteResultWith-0 case object MyCustomRejection extends Rejection val rejectRejections = // not particularly useful directive - mapRouteResultWith { res => - res match { - case Rejected(_) => Future(Rejected(List(AuthorizationFailedRejection))) - case _ => Future(res) - } + mapRouteResultWith { + case Rejected(_) => Future(Rejected(List(AuthorizationFailedRejection))) + case res => Future(res) } val route = rejectRejections { @@ -694,7 +690,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec { // tests: Get("/") ~> route ~> check { - responseAs[String] shouldEqual s"RoutingSettings.renderVanityFooter = true" + responseAs[String] shouldEqual "RoutingSettings.renderVanityFooter = true" } //# } @@ -767,7 +763,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec { pathPrefix("123") { ignoring456 { path("abc") { - complete(s"Content") + complete("Content") } } } diff --git a/akka-http-testkit/src/main/scala/akka/http/javadsl/testkit/TestRouteResult.scala b/akka-http-testkit/src/main/scala/akka/http/javadsl/testkit/TestRouteResult.scala index aee99e08b9..91edde58ac 100644 --- a/akka-http-testkit/src/main/scala/akka/http/javadsl/testkit/TestRouteResult.scala +++ b/akka-http-testkit/src/main/scala/akka/http/javadsl/testkit/TestRouteResult.scala @@ -194,6 +194,15 @@ abstract class TestRouteResult(_result: RouteResult, awaitAtMost: FiniteDuration this } + /** + * Assert that a header of the given type does not exist. + */ + def assertHeaderKindNotExists(name: String): TestRouteResult = { + val lowercased = name.toRootLowerCase + assertTrue(response.headers.forall(!_.is(lowercased)), s"`$name` header was not expected to appear.") + this + } + /** * Assert that a header of the given name and value exists. */ @@ -235,4 +244,4 @@ abstract class TestRouteResult(_result: RouteResult, awaitAtMost: FiniteDuration protected def assertEquals(expected: AnyRef, actual: AnyRef, message: String): Unit protected def assertEquals(expected: Int, actual: Int, message: String): Unit protected def assertTrue(predicate: Boolean, message: String): Unit -} \ No newline at end of file +} diff --git a/akka-http/src/main/scala/akka/http/javadsl/server/RouteResult.scala b/akka-http/src/main/scala/akka/http/javadsl/server/RouteResult.scala index 7a3a5642ec..0985375a2e 100644 --- a/akka-http/src/main/scala/akka/http/javadsl/server/RouteResult.scala +++ b/akka-http/src/main/scala/akka/http/javadsl/server/RouteResult.scala @@ -11,3 +11,21 @@ trait Complete extends RouteResult { trait Rejected extends RouteResult { def getRejections: java.lang.Iterable[Rejection] } + +object RouteResults { + import akka.http.scaladsl.{ server ⇒ s } + import akka.japi.Util + import scala.language.implicitConversions + import akka.http.impl.util.JavaMapping + import JavaMapping.Implicits._ + import RoutingJavaMapping._ + + def complete(response: HttpResponse): Complete = { + s.RouteResult.Complete(JavaMapping.toScala(response)) + } + + def rejected(rejections: java.lang.Iterable[Rejection]): Rejected = { + s.RouteResult.Rejected(Util.immutableSeq(rejections).map(_.asScala)) + } + +} diff --git a/akka-http/src/main/scala/akka/http/javadsl/server/directives/BasicDirectives.scala b/akka-http/src/main/scala/akka/http/javadsl/server/directives/BasicDirectives.scala index 2fc58edd0d..291453393b 100644 --- a/akka-http/src/main/scala/akka/http/javadsl/server/directives/BasicDirectives.scala +++ b/akka-http/src/main/scala/akka/http/javadsl/server/directives/BasicDirectives.scala @@ -8,7 +8,7 @@ import java.util.function.{ Function ⇒ JFunction } import akka.http.impl.util.JavaMapping import akka.http.javadsl.settings.ParserSettings -import akka.http.scaladsl.settings.RoutingSettings +import akka.http.javadsl.settings.RoutingSettings import akka.japi.Util import scala.concurrent.ExecutionContextExecutor @@ -73,6 +73,10 @@ abstract class BasicDirectives { D.mapRouteResult(route ⇒ f(route.asJava).asScala) { inner.get.delegate } } + def mapRouteResultPF(f: PartialFunction[RouteResult, RouteResult], inner: Supplier[Route]): Route = RouteAdapter { + D.mapRouteResult(route ⇒ f(route.asJava).asScala) { inner.get.delegate } + } + def mapRouteResultFuture(f: JFunction[CompletionStage[RouteResult], CompletionStage[RouteResult]], inner: Supplier[Route]): Route = RouteAdapter { D.mapRouteResultFuture(stage ⇒ f(toJava(stage.fast.map(_.asJava)(ExecutionContexts.sameThreadExecutionContext))).toScala.fast.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext)) { @@ -84,11 +88,15 @@ abstract class BasicDirectives { D.mapRouteResultWith(r ⇒ f(r.asJava).toScala.fast.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext)) { inner.get.delegate } } + def mapRouteResultWithPF(f: PartialFunction[RouteResult, CompletionStage[RouteResult]], inner: Supplier[Route]): Route = RouteAdapter { + D.mapRouteResultWith(r ⇒ f(r.asJava).toScala.fast.map(_.asScala)(ExecutionContexts.sameThreadExecutionContext)) { inner.get.delegate } + } + /** * Runs the inner route with settings mapped by the given function. */ def mapSettings(f: JFunction[RoutingSettings, RoutingSettings], inner: Supplier[Route]): Route = RouteAdapter { - D.mapSettings(rs ⇒ f(rs)) { inner.get.delegate } + D.mapSettings(rs ⇒ f(rs.asJava).asScala) { inner.get.delegate } } /** @@ -215,11 +223,18 @@ abstract class BasicDirectives { D.withExecutionContext(ec) { inner.get.delegate } } + /** + * Runs its inner route with the given alternative [[akka.stream.Materializer]]. + */ + def withMaterializer(mat: Materializer, inner: Supplier[Route]): Route = RouteAdapter { + D.withMaterializer(mat) { inner.get.delegate } + } + /** * Runs its inner route with the given alternative [[RoutingSettings]]. */ def withSettings(s: RoutingSettings, inner: Supplier[Route]): Route = RouteAdapter { - D.withSettings(s) { inner.get.delegate } + D.withSettings(s.asScala) { inner.get.delegate } } /**