!htp #18919 #19519 New JavaDSL for Akka HTTP (#20518)

* !htt #18919 #19519 Align Java HTTP server DSL with Scala

This commits replaces the Java HTTP server DSL with a Java-8 centric one
which exposes all scala DSL concepts to be usable from Java, including
custom directives, (un)marshallers, rejections, headers, and type safety
for path and query parameters.

* Add RequestContext and RouteResult to Java DSL
fix websockets
WIP bring java docs up to date.
This applies some updates to the root-level documentation

* [htp] Fix java documentation to correctly mention timeouts

Timeouts are configured the same in Java and Scala. Hence, linking to the
scala docs for timeouts from Java.

* =htc fix optionalHeaderValueByType in Java

* =htt #20200 fix java testkit always using NoLogging instead logger

* +htt actually run new javadsl tests, allow overriding config

* =htt improve javadsl test infra with more details when fails

* =htt fix bug in wrong path matcher exposed

* +htp add missing remaining path matcher

* =htp Java DSL cookie tests fixed

* =htt Java DSL ParameterDirectivesTest fixed

Protect the tweets from scalariform

Incorrect response expectations in cache condition directives spec fixed

* =htt Path directives for Java DSL

* +!htt PathMatchers rewritten, made uniform and tests passing

* Bugfix in java reject and a little test-boyscouting

* Revert "Incorrect response expectations in cache condition directives spec fixed"

This reverts commit cd50e89d45db010309f8249b090ea654ebb11c7a.

* +htc HttpAPIsTest is compile time only, not for running
Also, moved from the client package since not strictly a client test.

SecurityDirectives passing

Two faulty tests and two actual bugs.

Fix for cache condition spec not working

* Not sending in Unit instad of the implicit magnet in the test
* HeaderMagnet now works as expected
* Java API added for - and + on DateTime

PetStore example and test fixed

* Annotations to make marshalling work without default constructor
* Made model class immutable

Incorrect tests fixed

Some scaladoc boyscouting as bonus

* =htt RequestValTest sprinkled out across multiple directive tests

Client ip extraction test with incorrect header name fixed.

* =htt Incorrect CodingDirectivesTest fixed.

* =htt Bugfix for Java Unmarshaller.firstOf and fixes to JavaRouteTest

* =htt MarshallerTest fixed

* Missing seal signature added to JavaDSL
* More consistent (with Scala) test kit setup for Java
* missing Javadocs added
* Thread.sleep in default exception handler removed

* =htt copy directive docs, prepare for finishing it up

* +htt SecurityDirectives.authorize variants and test coverage added

* +htt Custom headers in Java DSL

* =htt WIP on java docs

* +htp add missing parameterOrDefault directive
Fixed a lot of doc warnings

* =htc intense progress on javadsl docs

* =htc #20470 Link to issue about docs and fix compile error
compile, migration guide
don't mima check http-experimental

* =htt Java DSL doc warnings fixed.
Only `Could not lex literal_block` ones left now

* =htc fix mima settings

* =doc fix MethodDirectives doc test with custom method

* =htc fix coding directives spec after bad merge

* =htc fix concat being corresponding to route() in javadsl

* =htt Disable consistency check for route/concat as it fails only on ci server

* !htt Minor fixes to PathMatchers
This commit is contained in:
Johan Andrén 2016-05-16 10:38:40 +02:00 committed by Konrad Malawski
parent 094c8974ed
commit 29029be31d
381 changed files with 12616 additions and 6630 deletions

View file

@ -4,27 +4,28 @@
package docs.http.javadsl.server;
import org.junit.Test;
import akka.http.javadsl.model.FormData;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.server.values.FormField;
import akka.http.javadsl.server.values.FormFields;
import akka.http.javadsl.server.StringUnmarshallers;
import akka.http.javadsl.server.StringUnmarshaller;
import akka.http.javadsl.server.Unmarshaller;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.japi.Pair;
import org.junit.Test;
public class FormFieldRequestValsExampleTest extends JUnitRouteTest {
@Test
public void testFormFieldVals() {
//#simple
FormField<String> name = FormFields.stringValue("name");
FormField<Integer> age = FormFields.intValue("age");
final Route route =
route(
handleWith2(name, age, (ctx, n, a) ->
ctx.complete(String.format("Name: %s, age: %d", n, a))
formField("name", n ->
formField(StringUnmarshallers.INTEGER, "age", a ->
complete(String.format("Name: %s, age: %d", n, a))
)
);
@ -44,13 +45,11 @@ public class FormFieldRequestValsExampleTest extends JUnitRouteTest {
@Test
public void testFormFieldValsUnmarshaling() {
//#custom-unmarshal
FormField<SampleId> sampleId = FormFields.fromString("id", SampleId.class, s -> new SampleId(Integer.valueOf(s)));
Unmarshaller<String, SampleId> SAMPLE_ID = StringUnmarshaller.sync(s -> new SampleId(Integer.valueOf(s)));
final Route route =
route(
handleWith1(sampleId, (ctx, sid) ->
ctx.complete(String.format("SampleId: %s", sid.id))
)
formField(SAMPLE_ID, "id", sid ->
complete(String.format("SampleId: %s", sid.id))
);
// tests:

View file

@ -4,28 +4,23 @@
package docs.http.javadsl.server;
import org.junit.Test;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.headers.Host;
import akka.http.javadsl.model.headers.RawHeader;
import akka.http.javadsl.server.RequestVal;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.server.values.Headers;
import akka.http.javadsl.testkit.JUnitRouteTest;
import org.junit.Test;
public class HeaderRequestValsExampleTest extends JUnitRouteTest {
@Test
public void testHeaderVals() {
//#by-class
// extract the entire header instance:
RequestVal<Host> host = Headers.byClass(Host.class).instance();
final Route route =
route(
handleWith1(host, (ctx, h) ->
ctx.complete(String.format("Host header was: %s", h.host()))
)
extractHost(host ->
complete(String.format("Host header was: %s", host))
);
// tests:
@ -41,14 +36,11 @@ public class HeaderRequestValsExampleTest extends JUnitRouteTest {
@Test
public void testHeaderByName() {
//#by-name
// extract the `value` of the header:
final RequestVal<String> XFishName = Headers.byName("X-Fish-Name").value();
final Route route =
route(
handleWith1(XFishName, (ctx, xFishName) ->
ctx.complete(String.format("The `X-Fish-Name` header's value was: %s", xFishName))
)
// extract the `value` of the header:
headerValueByName("X-Fish-Name", xFishName ->
complete(String.format("The `X-Fish-Name` header's value was: %s", xFishName))
);
// tests:

View file

@ -5,28 +5,41 @@
package docs.http.javadsl.server;
//#binding-failure-high-level-example
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.http.scaladsl.Http;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.Http;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Flow;
import java.io.IOException;
import java.util.concurrent.CompletionStage;
public class HighLevelServerBindFailureExample {
public static void main(String[] args) throws IOException {
// boot up server using the route as defined below
final ActorSystem system = ActorSystem.create();
public static void main(String[] args) throws IOException {
// boot up server using the route as defined below
final ActorSystem system = ActorSystem.create();
final ActorMaterializer materializer = ActorMaterializer.create(system);
// HttpApp.bindRoute expects a route being provided by HttpApp.createRoute
CompletionStage<Http.ServerBinding> bindingFuture =
new HighLevelServerExample().bindRoute("localhost", 8080, system);
// HttpApp.bindRoute expects a route being provided by HttpApp.createRoute
final HighLevelServerExample app = new HighLevelServerExample();
final Route route = app.createRoute();
bindingFuture.exceptionally(failure -> {
System.err.println("Something very bad happened! " + failure.getMessage());
system.terminate();
return null;
});
final Flow<HttpRequest, HttpResponse, NotUsed> handler = route.flow(system, materializer);
final CompletionStage<ServerBinding> binding = Http.get(system).bindAndHandle(handler, ConnectHttp.toHost("127.0.0.1", 8080), materializer);
system.terminate();
}
binding.exceptionally(failure -> {
System.err.println("Something very bad happened! " + failure.getMessage());
system.terminate();
return null;
});
system.terminate();
}
}
//#binding-failure-high-level-example

View file

@ -5,65 +5,73 @@
package docs.http.javadsl.server;
//#high-level-server-example
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.Http;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.model.ContentTypes;
import akka.http.javadsl.model.MediaTypes;
import akka.http.javadsl.server.*;
import akka.http.javadsl.server.values.Parameters;
import akka.http.javadsl.model.HttpEntities;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.server.AllDirectives;
import akka.http.javadsl.server.Route;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Flow;
import java.io.IOException;
import java.util.concurrent.CompletionStage;
public class HighLevelServerExample extends HttpApp {
public static void main(String[] args) throws IOException {
// boot up server using the route as defined below
ActorSystem system = ActorSystem.create();
public class HighLevelServerExample extends AllDirectives {
public static void main(String[] args) throws IOException {
// boot up server using the route as defined below
ActorSystem system = ActorSystem.create();
// HttpApp.bindRoute expects a route being provided by HttpApp.createRoute
new HighLevelServerExample().bindRoute("localhost", 8080, system);
System.out.println("Type RETURN to exit");
System.in.read();
system.terminate();
}
// HttpApp.bindRoute expects a route being provided by HttpApp.createRoute
final HighLevelServerExample app = new HighLevelServerExample();
// A RequestVal is a type-safe representation of some aspect of the request.
// In this case it represents the `name` URI parameter of type String.
private RequestVal<String> name = Parameters.stringValue("name").withDefault("Mister X");
final Http http = Http.get(system);
final ActorMaterializer materializer = ActorMaterializer.create(system);
@Override
public Route createRoute() {
// This handler generates responses to `/hello?name=XXX` requests
Route helloRoute =
handleWith1(name,
// in Java 8 the following becomes simply
// (ctx, name) -> ctx.complete("Hello " + name + "!")
new Handler1<String>() {
@Override
public RouteResult apply(RequestContext ctx, String name) {
return ctx.complete("Hello " + name + "!");
}
});
final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = app.createRoute().flow(system, materializer);
final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow, ConnectHttp.toHost("localhost", 8080), materializer);
return
// here the complete behavior for this server is defined
route(
// only handle GET requests
get(
// matches the empty path
pathSingleSlash().route(
// return a constant string with a certain content type
complete(ContentTypes.TEXT_HTML_UTF8,
"<html><body>Hello world!</body></html>")
),
path("ping").route(
// return a simple `text/plain` response
complete("PONG!")
),
path("hello").route(
// uses the route defined above
helloRoute
)
)
);
}
System.out.println("Type RETURN to exit");
System.in.read();
binding
.thenCompose(ServerBinding::unbind)
.thenAccept(unbound -> system.terminate());
}
public Route createRoute() {
// This handler generates responses to `/hello?name=XXX` requests
Route helloRoute =
parameterOptional("name", optName -> {
String name = optName.orElse("Mister X");
return complete("Hello " + name + "!");
});
return
// here the complete behavior for this server is defined
// only handle GET requests
get(() -> route(
// matches the empty path
pathSingleSlash(() ->
// return a constant string with a certain content type
complete(HttpEntities.create(ContentTypes.TEXT_HTML_UTF8, "<html><body>Hello world!</body></html>"))
),
path("ping", () ->
// return a simple `text/plain` response
complete("PONG!")
),
path("hello", () ->
// uses the route defined above
helloRoute
)
));
}
}
//#high-level-server-example
//#high-level-server-example

View file

@ -4,59 +4,35 @@
package docs.http.javadsl.server;
import java.util.Optional;
import org.junit.Test;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.headers.Host;
import akka.http.javadsl.server.Handler1;
import akka.http.javadsl.server.RequestContext;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.server.RouteResult;
import akka.http.javadsl.server.values.BasicCredentials;
import akka.http.javadsl.server.values.HttpBasicAuthenticator;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.scaladsl.model.headers.Authorization;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import org.junit.Test;
import scala.Option;
import scala.concurrent.Future;
public class HttpBasicAuthenticatorExample extends JUnitRouteTest {
private final String hardcodedPassword = "correcthorsebatterystaple";
private Optional<String> authenticate(Optional<ProvidedCredentials> creds) {
// this is where your actual authentication logic would go
return creds
.filter(c -> c.verify(hardcodedPassword)) // Only allow users that provide the right password
.map(c -> c.identifier()); // Provide the username down to the inner route
}
@Test
public void testBasicAuthenticator() {
//#basic-authenticator-java
final HttpBasicAuthenticator<String> authentication = new HttpBasicAuthenticator<String>("My realm") {
private final String hardcodedPassword = "correcthorsebatterystaple";
public CompletionStage<Optional<String>> authenticate(BasicCredentials credentials) {
// this is where your actual authentication logic would go
if (credentials.available() && // no anonymous access
credentials.verify(hardcodedPassword)) {
return authenticateAs(credentials.identifier());
} else {
return refuseAccess();
}
}
};
final Route route =
authentication.route(
handleWith1(
authentication,
new Handler1<String>() {
public RouteResult apply(RequestContext ctx, String user) {
return ctx.complete("Hello " + user + "!");
}
}
)
authenticateBasic("My realm", this::authenticate, user ->
complete("Hello " + user + "!")
);
// tests:
final HttpRequest okRequest =
HttpRequest

View file

@ -6,18 +6,11 @@ package docs.http.javadsl.server;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.dispatch.OnFailure;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.Http;
import akka.http.javadsl.IncomingConnection;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.model.*;
import akka.http.javadsl.model.ContentTypes;
import akka.http.javadsl.model.HttpMethods;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.model.Uri;
import akka.http.scaladsl.model.HttpEntity;
import akka.japi.function.Function;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
@ -34,180 +27,182 @@ import java.util.concurrent.TimeUnit;
@SuppressWarnings("unused")
public class HttpServerExampleDocTest {
public static void bindingExample() throws Exception {
//#binding-example
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
public static void bindingExample() throws Exception {
//#binding-example
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 8080), materializer);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 8080), materializer);
CompletionStage<ServerBinding> serverBindingFuture =
serverSource.to(Sink.foreach(connection -> {
System.out.println("Accepted new connection from " + connection.remoteAddress());
// ... and then actually handle the connection
}
)).run(materializer);
//#binding-example
serverBindingFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
}
public static void bindingFailureExample() throws Exception {
//#binding-failure-handling
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 80), materializer);
CompletionStage<ServerBinding> serverBindingFuture =
serverSource.to(Sink.foreach(connection -> {
System.out.println("Accepted new connection from " + connection.remoteAddress());
// ... and then actually handle the connection
}
)).run(materializer);
serverBindingFuture.whenCompleteAsync((binding, failure) -> {
// possibly report the failure somewhere...
}, system.dispatcher());
//#binding-failure-handling
serverBindingFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
}
public static void connectionSourceFailureExample() throws Exception {
//#incoming-connections-source-failure-handling
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 8080), materializer);
Flow<IncomingConnection, IncomingConnection, NotUsed> failureDetection =
Flow.of(IncomingConnection.class).watchTermination((notUsed, termination) -> {
termination.whenComplete((done, cause) -> {
if (cause != null) {
// signal the failure to external monitoring service!
}
});
return NotUsed.getInstance();
});
CompletionStage<ServerBinding> serverBindingFuture =
serverSource
.via(failureDetection) // feed signals through our custom stage
.to(Sink.foreach(connection -> {
System.out.println("Accepted new connection from " + connection.remoteAddress());
// ... and then actually handle the connection
}))
.run(materializer);
//#incoming-connections-source-failure-handling
serverBindingFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
}
public static void connectionStreamFailureExample() throws Exception {
//#connection-stream-failure-handling
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 8080), materializer);
Flow<HttpRequest, HttpRequest, NotUsed> failureDetection =
Flow.of(HttpRequest.class)
.watchTermination((notUsed, termination) -> {
termination.whenComplete((done, cause) -> {
if (cause != null) {
// signal the failure to external monitoring service!
}
});
return NotUsed.getInstance();
});
Flow<HttpRequest, HttpResponse, NotUsed> httpEcho =
Flow.of(HttpRequest.class)
.via(failureDetection)
.map(request -> {
Source<ByteString, Object> bytes = request.entity().getDataBytes();
HttpEntity.Chunked entity = HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8, bytes);
return HttpResponse.create()
.withEntity(entity);
});
CompletionStage<ServerBinding> serverBindingFuture =
serverSource.to(Sink.foreach(conn -> {
System.out.println("Accepted new connection from " + conn.remoteAddress());
conn.handleWith(httpEcho, materializer);
}
)).run(materializer);
//#connection-stream-failure-handling
serverBindingFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
}
public static void fullServerExample() throws Exception {
//#full-server-example
ActorSystem system = ActorSystem.create();
//#full-server-example
try {
//#full-server-example
final Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 8080), materializer);
//#request-handler
final Function<HttpRequest, HttpResponse> requestHandler =
new Function<HttpRequest, HttpResponse>() {
private final HttpResponse NOT_FOUND =
HttpResponse.create()
.withStatus(404)
.withEntity("Unknown resource!");
@Override
public HttpResponse apply(HttpRequest request) throws Exception {
Uri uri = request.getUri();
if (request.method() == HttpMethods.GET) {
if (uri.path().equals("/"))
return
HttpResponse.create()
.withEntity(ContentTypes.TEXT_HTML_UTF8,
"<html><body>Hello world!</body></html>");
else if (uri.path().equals("/hello")) {
String name = uri.query().get("name").orElse("Mister X");
return
HttpResponse.create()
.withEntity("Hello " + name + "!");
}
else if (uri.path().equals("/ping"))
return HttpResponse.create().withEntity("PONG!");
else
return NOT_FOUND;
}
else return NOT_FOUND;
}
};
//#request-handler
CompletionStage<ServerBinding> serverBindingFuture =
serverSource.to(Sink.foreach(connection -> {
System.out.println("Accepted new connection from " + connection.remoteAddress());
connection.handleWithSyncHandler(requestHandler, materializer);
// this is equivalent to
//connection.handleWith(Flow.of(HttpRequest.class).map(requestHandler), materializer);
})).run(materializer);
//#full-server-example
serverBindingFuture.toCompletableFuture().get(1, TimeUnit.SECONDS); // will throw if binding fails
System.out.println("Press ENTER to stop.");
new BufferedReader(new InputStreamReader(System.in)).readLine();
} finally {
system.terminate();
CompletionStage<ServerBinding> serverBindingFuture =
serverSource.to(Sink.foreach(connection -> {
System.out.println("Accepted new connection from " + connection.remoteAddress());
// ... and then actually handle the connection
}
)).run(materializer);
//#binding-example
serverBindingFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
}
public static void bindingFailureExample() throws Exception {
//#binding-failure-handling
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 80), materializer);
CompletionStage<ServerBinding> serverBindingFuture =
serverSource.to(Sink.foreach(connection -> {
System.out.println("Accepted new connection from " + connection.remoteAddress());
// ... and then actually handle the connection
}
)).run(materializer);
serverBindingFuture.whenCompleteAsync((binding, failure) -> {
// possibly report the failure somewhere...
}, system.dispatcher());
//#binding-failure-handling
serverBindingFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
}
public static void connectionSourceFailureExample() throws Exception {
//#incoming-connections-source-failure-handling
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 8080), materializer);
Flow<IncomingConnection, IncomingConnection, NotUsed> failureDetection =
Flow.of(IncomingConnection.class).watchTermination((notUsed, termination) -> {
termination.whenComplete((done, cause) -> {
if (cause != null) {
// signal the failure to external monitoring service!
}
});
return NotUsed.getInstance();
});
CompletionStage<ServerBinding> serverBindingFuture =
serverSource
.via(failureDetection) // feed signals through our custom stage
.to(Sink.foreach(connection -> {
System.out.println("Accepted new connection from " + connection.remoteAddress());
// ... and then actually handle the connection
}))
.run(materializer);
//#incoming-connections-source-failure-handling
serverBindingFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
}
public static void connectionStreamFailureExample() throws Exception {
//#connection-stream-failure-handling
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 8080), materializer);
Flow<HttpRequest, HttpRequest, NotUsed> failureDetection =
Flow.of(HttpRequest.class)
.watchTermination((notUsed, termination) -> {
termination.whenComplete((done, cause) -> {
if (cause != null) {
// signal the failure to external monitoring service!
}
});
return NotUsed.getInstance();
});
Flow<HttpRequest, HttpResponse, NotUsed> httpEcho =
Flow.of(HttpRequest.class)
.via(failureDetection)
.map(request -> {
Source<ByteString, Object> bytes = request.entity().getDataBytes();
HttpEntity.Chunked entity = HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8, bytes);
return HttpResponse.create()
.withEntity(entity);
});
CompletionStage<ServerBinding> serverBindingFuture =
serverSource.to(Sink.foreach(conn -> {
System.out.println("Accepted new connection from " + conn.remoteAddress());
conn.handleWith(httpEcho, materializer);
}
)).run(materializer);
//#connection-stream-failure-handling
serverBindingFuture.toCompletableFuture().get(3, TimeUnit.SECONDS);
}
public static void fullServerExample() throws Exception {
//#full-server-example
ActorSystem system = ActorSystem.create();
//#full-server-example
try {
//#full-server-example
final Materializer materializer = ActorMaterializer.create(system);
Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
Http.get(system).bind(ConnectHttp.toHost("localhost", 8080), materializer);
//#request-handler
final Function<HttpRequest, HttpResponse> requestHandler =
new Function<HttpRequest, HttpResponse>() {
private final HttpResponse NOT_FOUND =
HttpResponse.create()
.withStatus(404)
.withEntity("Unknown resource!");
@Override
public HttpResponse apply(HttpRequest request) throws Exception {
Uri uri = request.getUri();
if (request.method() == HttpMethods.GET) {
if (uri.path().equals("/")) {
return
HttpResponse.create()
.withEntity(ContentTypes.TEXT_HTML_UTF8,
"<html><body>Hello world!</body></html>");
} else if (uri.path().equals("/hello")) {
String name = uri.query().get("name").orElse("Mister X");
return
HttpResponse.create()
.withEntity("Hello " + name + "!");
} else if (uri.path().equals("/ping")) {
return HttpResponse.create().withEntity("PONG!");
} else {
return NOT_FOUND;
}
} else {
return NOT_FOUND;
}
}
};
//#request-handler
CompletionStage<ServerBinding> serverBindingFuture =
serverSource.to(Sink.foreach(connection -> {
System.out.println("Accepted new connection from " + connection.remoteAddress());
connection.handleWithSyncHandler(requestHandler, materializer);
// this is equivalent to
//connection.handleWith(Flow.of(HttpRequest.class).map(requestHandler), materializer);
})).run(materializer);
//#full-server-example
serverBindingFuture.toCompletableFuture().get(1, TimeUnit.SECONDS); // will throw if binding fails
System.out.println("Press ENTER to stop.");
new BufferedReader(new InputStreamReader(System.in)).readLine();
} finally {
system.terminate();
}
public static void main(String[] args) throws Exception {
fullServerExample();
}
}
public static void main(String[] args) throws Exception {
fullServerExample();
}
}

View file

@ -5,62 +5,36 @@ package docs.http.javadsl.server;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.headers.Host;
import akka.http.javadsl.model.headers.OAuth2BearerToken;
import akka.http.javadsl.server.Handler1;
import akka.http.javadsl.server.RequestContext;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.server.RouteResult;
import akka.http.javadsl.server.values.BasicCredentials;
import akka.http.javadsl.server.values.HttpBasicAuthenticator;
import akka.http.javadsl.server.values.OAuth2Authenticator;
import akka.http.javadsl.server.values.OAuth2Credentials;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.scaladsl.model.headers.Authorization;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import org.junit.Test;
import scala.Option;
import scala.concurrent.Future;
public class OAuth2AuthenticatorExample extends JUnitRouteTest {
private final String hardcodedToken = "token";
private Optional<String> authenticate(Optional<ProvidedCredentials> creds) {
// this is where your actual authentication logic would go, looking up the user
// based on the token or something in that direction
// We will not allow anonymous access.
return creds
.filter(c -> c.verify(hardcodedToken)) //
.map(c -> c.identifier()); // Provide the "identifier" down to the inner route
// (for OAuth2, that's actually just the token)
}
@Test
public void testOAuth2Authenticator() {
//#oauth2-authenticator-java
final OAuth2Authenticator<String> authentication = new OAuth2Authenticator<String>("My realm") {
private final String hardcodedToken = "token";
@Override
public CompletionStage<Optional<String>> authenticate(OAuth2Credentials credentials) {
// this is where your actual authentication logic would go, looking up the user
// based on the token or something in that direction
if (credentials.available() && // no anonymous access
credentials.verify(hardcodedToken)) {
// not a secret + identity pair, so this is actually the token
return authenticateAs(credentials.identifier());
} else {
return refuseAccess();
}
}
};
final Route route =
authentication.route(
handleWith1(
authentication,
new Handler1<String>() {
public RouteResult apply(RequestContext ctx, String token) {
return ctx.complete("The secret token is: " + token);
}
}
)
);
authenticateOAuth2("My realm", this::authenticate, token ->
complete("The secret token is: " + token)
);
// tests:

View file

@ -5,73 +5,75 @@
package docs.http.javadsl.server;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.server.Handler1;
import akka.http.javadsl.server.values.PathMatcher;
import akka.http.javadsl.server.values.PathMatchers;
import akka.http.javadsl.server.PathMatchers;
import akka.http.javadsl.testkit.JUnitRouteTest;
import org.junit.Test;
public class PathDirectiveExampleTest extends JUnitRouteTest {
@Test
public void testPathPrefix() {
//#path-examples
// matches "/test"
path("test").route(
completeWithStatus(StatusCodes.OK)
);
@Test
public void testPathPrefix() {
//#path-examples
// matches "/test"
path("test", () ->
complete(StatusCodes.OK)
);
// matches "/test", as well
path(PathMatchers.segment("test")).route(
completeWithStatus(StatusCodes.OK)
);
// matches "/test", as well
path(PathMatchers.segment("test"), () ->
complete(StatusCodes.OK)
);
// matches "/admin/user"
path("admin", "user").route(
completeWithStatus(StatusCodes.OK)
);
// matches "/admin/user"
path(PathMatchers.segment("admin")
.slash("user"), () ->
complete(StatusCodes.OK)
);
// matches "/admin/user", as well
pathPrefix("admin").route(
path("user").route(
completeWithStatus(StatusCodes.OK)
)
);
// matches "/admin/user", as well
pathPrefix("admin", () ->
path("user", () ->
complete(StatusCodes.OK)
)
);
// matches "/admin/user/<user-id>"
Handler1<Integer> completeWithUserId =
(ctx, userId) -> ctx.complete("Hello user " + userId);
PathMatcher<Integer> userId = PathMatchers.intValue();
pathPrefix("admin", "user").route(
path(userId).route(
handleWith1(userId, completeWithUserId)
)
);
// matches "/admin/user/<user-id>"
path(PathMatchers.segment("admin")
.slash("user")
.slash(PathMatchers.integerSegment()), userId -> {
return complete("Hello user " + userId);
}
);
// matches "/admin/user/<user-id>", as well
path("admin", "user", userId).route(
handleWith1(userId, completeWithUserId)
);
// matches "/admin/user/<user-id>", as well
pathPrefix("admin", () ->
path("user", () ->
path(PathMatchers.integerSegment(), userId ->
complete("Hello user " + userId)
)
)
);
// never matches
path("admin").route( // oops this only matches "/admin"
path("user").route(
completeWithStatus(StatusCodes.OK)
)
);
// never matches
path("admin", () -> // oops this only matches "/admin", and no sub-paths
path("user", () ->
complete(StatusCodes.OK)
)
);
// matches "/user/" with the first subroute, "/user" (without a trailing slash)
// with the second subroute, and "/user/<user-id>" with the last one.
pathPrefix("user").route(
pathSingleSlash().route(
completeWithStatus(StatusCodes.OK)
),
pathEnd().route(
completeWithStatus(StatusCodes.OK)
),
path(userId).route(
handleWith1(userId, completeWithUserId)
)
);
//#path-examples
}
}
// matches "/user/" with the first subroute, "/user" (without a trailing slash)
// with the second subroute, and "/user/<user-id>" with the last one.
pathPrefix("user", () -> route(
pathSingleSlash(() ->
complete(StatusCodes.OK)
),
pathEnd(() ->
complete(StatusCodes.OK)
),
path(PathMatchers.integerSegment(), userId ->
complete("Hello user " + userId)
)
));
//#path-examples
}
}

View file

@ -5,6 +5,7 @@
package docs.http.javadsl.server;
//#websocket-example-using-core
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.CompletionStage;
@ -12,11 +13,6 @@ import java.util.concurrent.TimeUnit;
import akka.NotUsed;
import akka.http.javadsl.ConnectHttp;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.FiniteDuration;
import scala.runtime.BoxedUnit;
import akka.japi.Function;
import akka.japi.JavaPartialFunction;
@ -34,66 +30,76 @@ import akka.http.javadsl.model.ws.Message;
import akka.http.javadsl.model.ws.TextMessage;
import akka.http.javadsl.model.ws.WebSocket;
@SuppressWarnings("Convert2MethodRef")
public class WebSocketCoreExample {
//#websocket-handling
public static HttpResponse handleRequest(HttpRequest request) {
System.out.println("Handling request to " + request.getUri());
//#websocket-handling
public static HttpResponse handleRequest(HttpRequest request) {
System.out.println("Handling request to " + request.getUri());
if (request.getUri().path().equals("/greeter"))
return WebSocket.handleWebSocketRequestWith(request, greeter());
else
return HttpResponse.create().withStatus(404);
if (request.getUri().path().equals("/greeter")) {
final Flow<Message, Message, NotUsed> greeterFlow = greeter();
return WebSocket.handleWebSocketRequestWith(request, greeterFlow);
} else {
return HttpResponse.create().withStatus(404);
}
//#websocket-handling
}
//#websocket-handling
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create();
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create();
try {
final Materializer materializer = ActorMaterializer.create(system);
try {
final Materializer materializer = ActorMaterializer.create(system);
CompletionStage<ServerBinding> serverBindingFuture =
Http.get(system).bindAndHandleSync(
new Function<HttpRequest, HttpResponse>() {
public HttpResponse apply(HttpRequest request) throws Exception {
return handleRequest(request);
}
}, ConnectHttp.toHost("localhost", 8080), materializer);
final Function<HttpRequest, HttpResponse> handler = request -> handleRequest(request);
CompletionStage<ServerBinding> serverBindingFuture =
Http.get(system).bindAndHandleSync(
handler, ConnectHttp.toHost("localhost", 8080), materializer);
// will throw if binding fails
serverBindingFuture.toCompletableFuture().get(1, TimeUnit.SECONDS);
System.out.println("Press ENTER to stop.");
new BufferedReader(new InputStreamReader(System.in)).readLine();
} finally {
system.terminate();
}
// will throw if binding fails
serverBindingFuture.toCompletableFuture().get(1, TimeUnit.SECONDS);
System.out.println("Press ENTER to stop.");
new BufferedReader(new InputStreamReader(System.in)).readLine();
} finally {
system.terminate();
}
}
//#websocket-handler
/**
* A handler that treats incoming messages as a name,
* and responds with a greeting to that name
*/
public static Flow<Message, Message, NotUsed> greeter() {
return
Flow.<Message>create()
.collect(new JavaPartialFunction<Message, Message>() {
@Override
public Message apply(Message msg, boolean isCheck) throws Exception {
if (isCheck)
if (msg.isText()) return null;
else throw noMatch();
else
return handleTextMessage(msg.asTextMessage());
}
});
//#websocket-handler
/**
* A handler that treats incoming messages as a name,
* and responds with a greeting to that name
*/
public static Flow<Message, Message, NotUsed> greeter() {
return
Flow.<Message>create()
.collect(new JavaPartialFunction<Message, Message>() {
@Override
public Message apply(Message msg, boolean isCheck) throws Exception {
if (isCheck) {
if (msg.isText()) {
return null;
} else {
throw noMatch();
}
} else {
return handleTextMessage(msg.asTextMessage());
}
}
});
}
public static TextMessage handleTextMessage(TextMessage msg) {
if (msg.isStrict()) // optimization that directly creates a simple response...
{
return TextMessage.create("Hello " + msg.getStrictText());
} else // ... this would suffice to handle all text messages in a streaming fashion
{
return TextMessage.create(Source.single("Hello ").concat(msg.getStreamedText()));
}
public static TextMessage handleTextMessage(TextMessage msg) {
if (msg.isStrict()) // optimization that directly creates a simple response...
return TextMessage.create("Hello "+msg.getStrictText());
else // ... this would suffice to handle all text messages in a streaming fashion
return TextMessage.create(Source.single("Hello ").concat(msg.getStreamedText()));
}
//#websocket-handler
}
//#websocket-handler
}
//#websocket-example-using-core
//#websocket-example-using-core

View file

@ -4,51 +4,51 @@
package docs.http.javadsl.server;
import akka.NotUsed;
import akka.http.javadsl.server.AllDirectives;
import akka.http.javadsl.server.Route;
import akka.japi.JavaPartialFunction;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Source;
import akka.http.javadsl.model.ws.Message;
import akka.http.javadsl.model.ws.TextMessage;
import akka.http.javadsl.server.HttpApp;
public class WebSocketRoutingExample extends AllDirectives {
public class WebSocketRoutingExample extends HttpApp {
//#websocket-route
@Override
public Route createRoute() {
return
path("greeter").route(
handleWebSocketMessages(greeter())
);
}
//#websocket-route
//#websocket-route
public Route createRoute() {
return
path("greeter", () ->
handleWebSocketMessages(greeter())
);
}
//#websocket-route
/**
* A handler that treats incoming messages as a name,
* and responds with a greeting to that name
*/
public static Flow<Message, Message, ?> greeter() {
return
Flow.<Message>create()
.collect(new JavaPartialFunction<Message, Message>() {
@Override
public Message apply(Message msg, boolean isCheck) throws Exception {
if (isCheck)
if (msg.isText()) return null;
else throw noMatch();
else
return handleTextMessage(msg.asTextMessage());
}
});
}
public static TextMessage handleTextMessage(TextMessage msg) {
if (msg.isStrict()) // optimization that directly creates a simple response...
return TextMessage.create("Hello "+msg.getStrictText());
else // ... this would suffice to handle all text messages in a streaming fashion
return TextMessage.create(Source.single("Hello ").concat(msg.getStreamedText()));
/**
* A handler that treats incoming messages as a name,
* and responds with a greeting to that name
*/
public static Flow<Message, Message, NotUsed> greeter() {
return
Flow.<Message>create()
.collect(new JavaPartialFunction<Message, Message>() {
@Override
public Message apply(Message msg, boolean isCheck) throws Exception {
if (isCheck) {
if (msg.isText()) return null;
else throw noMatch();
} else return handleTextMessage(msg.asTextMessage());
}
});
}
public static TextMessage handleTextMessage(TextMessage msg) {
if (msg.isStrict()) // optimization that directly creates a simple response...
{
return TextMessage.create("Hello " + msg.getStrictText());
} else // ... this would suffice to handle all text messages in a streaming fashion
{
return TextMessage.create(Source.single("Hello ").concat(msg.getStreamedText()));
}
}
}

View file

@ -0,0 +1,126 @@
/*
* Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
*/
package docs.http.javadsl.server.directives;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.model.headers.RawHeader;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
import java.util.function.Function;
public class CustomDirectivesExamplesTest extends JUnitRouteTest {
//#labeling-1
public Route getOrPut(Supplier<Route> inner) {
return get(inner).orElse(put(inner));
}
//#
@Test
public void testLabeling() {
// tests:
//#labeling-2
Route route = getOrPut(() -> complete("ok"));
//#
testRoute(route).run(HttpRequest.GET("/"))
.assertStatusCode(StatusCodes.OK);
testRoute(route).run(HttpRequest.PUT("/"))
.assertStatusCode(StatusCodes.OK);
}
public static class MyCredentials {
private final String userId;
private final String secret;
public MyCredentials(String userId, String secret) {
this.userId = userId;
this.secret = secret;
}
public String getUserId() {
return userId;
}
public boolean safeSecretVerification(String correct) {
// of course this is not what you would do in a real app
return correct.equals(secret);
}
}
public static enum MyRole {
USER,
ADMIN
}
//#composition-1
// the composed custom directive
/**
* @param authenticate A function returns a set of roles for the credentials of a user
* @param inner Inner route to execute if the provided credentials has the given role
* if not, the request is completed with a
*/
public Route headerBasedAuth(Function<MyCredentials, Set<MyRole>> authenticate, MyRole requiredRole, Supplier<Route> inner) {
return headerValueByName("X-My-User-Id", (userId) -> {
return headerValueByName("X-My-User-Secret", (secret) -> {
Set<MyRole> userRoles = authenticate.apply(new MyCredentials(userId, secret));
if (userRoles.contains(requiredRole)) {
return inner.get();
} else {
return complete(StatusCodes.FORBIDDEN, "Role " + requiredRole + " required for access");
}
});
});
}
//#
@Test
public void testComposition() {
// tests:
//#composition-2
// a function for authentication
Function<MyCredentials, Set<MyRole>> authLogic =
(credentials) -> {
if (credentials.userId.equals("admin") && credentials.safeSecretVerification("secret"))
return new HashSet<>(Arrays.asList(MyRole.USER, MyRole.ADMIN));
else
return Collections.emptySet();
};
// and then using the custom route
Route route = get(() ->
path("admin", () ->
headerBasedAuth(authLogic, MyRole.ADMIN, () -> complete(StatusCodes.OK, "admin stuff"))
)
);
//#
testRoute(route).run(HttpRequest.GET("/admin"))
.assertStatusCode(StatusCodes.BAD_REQUEST);
testRoute(route).run(HttpRequest.GET("/admin").addHeaders(
Arrays.asList(RawHeader.create("X-My-User-Id", "user"), RawHeader.create("X-My-User-Secret", "wrong"))))
.assertStatusCode(StatusCodes.FORBIDDEN);
testRoute(route).run(HttpRequest.GET("/admin").addHeaders(
Arrays.asList(RawHeader.create("X-My-User-Id", "admin"), RawHeader.create("X-My-User-Secret", "secret"))))
.assertStatusCode(StatusCodes.OK);
}
}

View file

@ -7,15 +7,14 @@ package docs.http.javadsl.server.directives;
import java.util.Arrays;
import java.util.regex.Pattern;
import akka.http.javadsl.model.HttpMethod;
import org.junit.Test;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.model.headers.Host;
import akka.http.javadsl.server.*;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import org.junit.Test;
public class HostDirectivesExamplesTest extends JUnitRouteTest {
@Test
@ -23,7 +22,7 @@ public class HostDirectivesExamplesTest extends JUnitRouteTest {
//#host1
final Route matchListOfHosts = host(
Arrays.asList("api.company.com", "rest.company.com"),
completeWithStatus(StatusCodes.OK));
() -> complete(StatusCodes.OK));
testRoute(matchListOfHosts).run(HttpRequest.GET("/").addHeader(Host.create("api.company.com")))
.assertStatusCode(StatusCodes.OK);
@ -34,7 +33,7 @@ public class HostDirectivesExamplesTest extends JUnitRouteTest {
public void testHostPredicate() {
//#host2
final Route shortOnly = host(hostname -> hostname.length() < 10,
completeWithStatus(StatusCodes.OK));
() -> complete(StatusCodes.OK));
testRoute(shortOnly).run(HttpRequest.GET("/").addHeader(Host.create("short.com")))
.assertStatusCode(StatusCodes.OK);
@ -47,10 +46,9 @@ public class HostDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testExtractHost() {
//#extractHostname
final RequestVal<String> host = RequestVals.host();
final Route route = handleWith1(host,
(ctx, hn) -> ctx.complete("Hostname: " + hn));
final Route route = extractHost(hn ->
complete("Hostname: " + hn));
testRoute(route).run(HttpRequest.GET("/").addHeader(Host.create("company.com", 9090)))
.assertEntity("Hostname: company.com");
@ -60,18 +58,12 @@ public class HostDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testMatchAndExtractHost() {
//#matchAndExtractHost
final RequestVal<String> hostPrefix = RequestVals
.matchAndExtractHost(Pattern.compile("api|rest"));
final Route hostPrefixRoute = handleWith1(hostPrefix,
(ctx, prefix) -> ctx.complete("Extracted prefix: " + prefix));
final Route hostPrefixRoute = host(Pattern.compile("api|rest"), prefix ->
complete("Extracted prefix: " + prefix));
final RequestVal<String> hostPart = RequestVals.matchAndExtractHost(Pattern
.compile("public.(my|your)company.com"));
final Route hostPartRoute = handleWith1(
hostPart,
(ctx, captured) -> ctx.complete("You came through " + captured
final Route hostPartRoute = host(Pattern.compile("public.(my|your)company.com"), captured ->
complete("You came through " + captured
+ " company"));
final Route route = route(hostPrefixRoute, hostPartRoute);
@ -90,9 +82,10 @@ public class HostDirectivesExamplesTest extends JUnitRouteTest {
public void testFailingMatchAndExtractHost() {
//#failing-matchAndExtractHost
// this will throw IllegalArgumentException
final RequestVal<String> hostRegex = RequestVals
.matchAndExtractHost(Pattern
.compile("server-([0-9]).company.(com|net|org)"));
final Route hostRegex = host(Pattern.compile("server-([0-9]).company.(com|net|org)"), s ->
// will not reach here
complete(s)
);
//#failing-matchAndExtractHost
}

View file

@ -4,20 +4,19 @@
package docs.http.javadsl.server.directives;
import akka.http.javadsl.model.HttpMethod;
import org.junit.Test;
import akka.http.javadsl.model.HttpMethods;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.server.*;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import org.junit.Test;
public class MethodDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testDelete() {
//#delete
final Route route = delete(complete("This is a DELETE request."));
final Route route = delete(() -> complete("This is a DELETE request."));
testRoute(route).run(HttpRequest.DELETE("/")).assertEntity(
"This is a DELETE request.");
@ -27,7 +26,7 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testGet() {
//#get
final Route route = get(complete("This is a GET request."));
final Route route = get(() -> complete("This is a GET request."));
testRoute(route).run(HttpRequest.GET("/")).assertEntity(
"This is a GET request.");
@ -37,7 +36,7 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testHead() {
//#head
final Route route = head(complete("This is a HEAD request."));
final Route route = head(() -> complete("This is a HEAD request."));
testRoute(route).run(HttpRequest.HEAD("/")).assertEntity(
"This is a HEAD request.");
@ -47,7 +46,7 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testOptions() {
//#options
final Route route = options(complete("This is a OPTIONS request."));
final Route route = options(() -> complete("This is a OPTIONS request."));
testRoute(route).run(HttpRequest.OPTIONS("/")).assertEntity(
"This is a OPTIONS request.");
@ -57,7 +56,7 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testPatch() {
//#patch
final Route route = patch(complete("This is a PATCH request."));
final Route route = patch(() -> complete("This is a PATCH request."));
testRoute(route).run(HttpRequest.PATCH("/").withEntity("patch content"))
.assertEntity("This is a PATCH request.");
@ -67,7 +66,7 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testPost() {
//#post
final Route route = post(complete("This is a POST request."));
final Route route = post(() -> complete("This is a POST request."));
testRoute(route).run(HttpRequest.POST("/").withEntity("post content"))
.assertEntity("This is a POST request.");
@ -77,7 +76,7 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testPut() {
//#put
final Route route = put(complete("This is a PUT request."));
final Route route = put(() -> complete("This is a PUT request."));
testRoute(route).run(HttpRequest.PUT("/").withEntity("put content"))
.assertEntity("This is a PUT request.");
@ -88,7 +87,7 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
public void testMethodExample() {
//#method-example
final Route route = method(HttpMethods.PUT,
complete("This is a PUT request."));
() -> complete("This is a PUT request."));
testRoute(route).run(HttpRequest.PUT("/").withEntity("put content"))
.assertEntity("This is a PUT request.");
@ -101,15 +100,15 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
@Test
public void testExtractMethodExample() {
//#extractMethod
final RequestVal<HttpMethod> requestMethod = RequestVals.requestMethod();
final Route otherMethod = handleWith1(
requestMethod,
(ctx, method) -> ctx.complete("This " + method.value()
+ " request, clearly is not a GET!"));
final Route route = route(get(complete("This is a GET request.")),
otherMethod);
final Route route = route(
get(() ->
complete("This is a GET request.")
),
extractMethod(method ->
complete("This " + method.value() + " request, clearly is not a GET!")
)
);
testRoute(route).run(HttpRequest.GET("/")).assertEntity(
"This is a GET request.");
@ -121,4 +120,31 @@ public class MethodDirectivesExamplesTest extends JUnitRouteTest {
"This HEAD request, clearly is not a GET!");
//#extractMethod
}
@Test
public void testOverrideMethodWithParameter() {
//#overrideMethodWithParameter
final Route route = route(
overrideMethodWithParameter("method", () ->
route(
get(() -> complete("This looks like a GET request.")),
post(() -> complete("This looks like a POST request."))
)
)
);
// tests:
testRoute(route).run(HttpRequest.GET("/?method=POST")).assertEntity(
"This looks like a POST request.");
testRoute(route).run(HttpRequest.POST("/?method=get"))
.assertEntity("This looks like a GET request.");
testRoute(route).run(HttpRequest.GET("/?method=hallo")).assertEntity(
"The server either does not recognize the request method, or it lacks the ability to fulfill the request.");
//#overrideMethodWithParameter
}
}

View file

@ -5,29 +5,51 @@
package docs.http.javadsl.server.testkit;
//#simple-app
import akka.http.javadsl.server.*;
import akka.http.javadsl.server.values.Parameters;
public class MyAppService extends HttpApp {
RequestVal<Double> x = Parameters.doubleValue("x");
RequestVal<Double> y = Parameters.doubleValue("y");
import akka.actor.ActorSystem;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.Http;
import akka.http.javadsl.server.AllDirectives;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.server.StringUnmarshallers;
import akka.http.javadsl.server.examples.simple.SimpleServerApp;
import akka.stream.ActorMaterializer;
public RouteResult add(RequestContext ctx, double x, double y) {
return ctx.complete("x + y = " + (x + y));
}
import java.io.IOException;
@Override
public Route createRoute() {
return
route(
get(
pathPrefix("calculator").route(
path("add").route(
handleReflectively(this, "add", x, y)
)
)
)
);
}
public class MyAppService extends AllDirectives {
public String add(double x, double y) {
return "x + y = " + (x + y);
}
public Route createRoute() {
return
get(() ->
pathPrefix("calculator", () ->
path("add", () ->
parameter(StringUnmarshallers.DOUBLE, "x", x ->
parameter(StringUnmarshallers.DOUBLE, "y", y ->
complete(add(x, y))
)
)
)
)
);
}
public static void main(String[] args) throws IOException {
final ActorSystem system = ActorSystem.create();
final ActorMaterializer materializer = ActorMaterializer.create(system);
final SimpleServerApp app = new SimpleServerApp();
final ConnectHttp host = ConnectHttp.toHost("127.0.0.1");
Http.get(system).bindAndHandle(app.createRoute().flow(system, materializer), host, materializer);
System.console().readLine("Type RETURN to exit...");
system.terminate();
}
}
//#simple-app
//#simple-app

View file

@ -61,13 +61,7 @@ explicitly drained by attaching it to ``Sink.ignore()``.
Timeouts
--------
Currently Akka HTTP doesn't implement client-side request timeout checking itself as this functionality can be regarded
as a more general purpose streaming infrastructure feature.
It should be noted that Akka Streams provide various timeout functionality so any API that uses streams can benefit
from the stream stages such as ``idleTimeout``, ``backpressureTimeout``, ``completionTimeout``, ``initialTimeout``
and ``throttle``. To learn more about these refer to their documentation in Akka Streams (and Java Doc).
Timeouts are configured in the same way for Scala and Akka. See :ref:`http-timeouts-java` .
.. _http-client-layer-java:

View file

@ -0,0 +1,16 @@
Encoding / Decoding
===================
The `HTTP spec`_ defines a ``Content-Encoding`` header, which signifies whether the entity body of an HTTP message is
"encoded" and, if so, by which algorithm. The only commonly used content encodings are compression algorithms.
Currently Akka HTTP supports the compression and decompression of HTTP requests and responses with the ``gzip`` or
``deflate`` encodings.
The core logic for this lives in the `akka.http.scaladsl.coding`_ package.
The support is not enabled automatically, but must be explicitly requested.
For enabling message encoding/decoding with :ref:`Routing DSL <http-high-level-server-side-api>` see the :ref:`CodingDirectives`.
.. _HTTP spec: http://tools.ietf.org/html/rfc7231#section-3.1.2.1
.. _akka.http.scaladsl.coding: @github@/akka-http/src/main/scala/akka/http/scaladsl/coding

View file

@ -0,0 +1,21 @@
.. _http-java-common:
Common Abstractions (Client- and Server-Side)
=============================================
HTTP and related specifications define a great number of concepts and functionality that is not specific to either
HTTP's client- or server-side since they are meaningful on both end of an HTTP connection.
The documentation for their counterparts in Akka HTTP lives in this section rather than in the ones for the
:ref:`Client-Side API <http-client-side>`, :ref:`http-low-level-server-side-api` or :ref:`http-high-level-server-side-api`,
which are specific to one side only.
.. toctree::
:maxdepth: 2
../http-model
marshalling
unmarshalling
de-coding
json-support
timeouts

View file

@ -18,13 +18,13 @@ Json Support via Jackson
To make use of the support module, you need to add a dependency on `akka-http-jackson-experimental`.
Use ``akka.http.javadsl.marshallers.jackson.Jackson.jsonAs[T]`` to create a ``RequestVal<T>`` which expects the request
body to be of type ``application/json`` and converts it to ``T`` using Jackson.
Use ``akka.http.javadsl.marshallers.jackson.Jackson.unmarshaller(T.class)`` to create an ``Unmarshaller<HttpEntity,T>`` which expects the request
body (HttpEntity) to be of type ``application/json`` and converts it to ``T`` using Jackson.
See `this example`__ in the sources for an example.
Use ``akka.http.javadsl.marshallers.jackson.Jackson.json[T]`` to create a ``Marshaller<T>`` which can be used with
``RequestContext.completeAs`` to convert a POJO to an HttpResponse.
Use ``akka.http.javadsl.marshallers.jackson.Jackson.marshaller(T.class)`` to create a ``Marshaller<T,RequestEntity>`` which can be used with
``RequestContext.complete`` or ``RouteDirectives.complete`` to convert a POJO to an HttpResponse.
.. _jackson: https://github.com/FasterXML/jackson

View file

@ -0,0 +1,166 @@
.. _http-marshalling-java:
Marshalling
===========
TODO overhaul for Java
"Marshalling" is the process of converting a higher-level (object) structure into some kind of lower-level
representation, often a "wire format". Other popular names for it are "Serialization" or "Pickling".
In Akka HTTP "Marshalling" means the conversion of an object of type ``T`` into a lower-level target type,
e.g. a ``MessageEntity`` (which forms the "entity body" of an HTTP request or response) or a full ``HttpRequest`` or
``HttpResponse``.
Basic Design
------------
Marshalling of instances of type ``A`` into instances of type ``B`` is performed by a ``Marshaller[A, B]``.
Akka HTTP also predefines a number of helpful aliases for the types of marshallers that you'll likely work with most:
.. includecode2:: /../../akka-http/src/main/scala/akka/http/scaladsl/marshalling/package.scala
:snippet: marshaller-aliases
Contrary to what you might initially expect ``Marshaller[A, B]`` is not a plain function ``A => B`` but rather
essentially a function ``A => Future[List[Marshalling[B]]]``.
Let's dissect this rather complicated looking signature piece by piece to understand what marshallers are designed this
way.
Given an instance of type ``A`` a ``Marshaller[A, B]`` produces:
1. A ``Future``: This is probably quite clear. Marshallers are not required to synchronously produce a result, so instead
they return a future, which allows for asynchronicity in the marshalling process.
2. of ``List``: Rather than only a single target representation for ``A`` marshallers can offer several ones. Which
one will be rendered onto the wire in the end is decided by content negotiation.
For example, the ``ToEntityMarshaller[OrderConfirmation]`` might offer a JSON as well as an XML representation.
The client can decide through the addition of an ``Accept`` request header which one is preferred. If the client doesn't
express a preference the first representation is picked.
3. of ``Marshalling[B]``: Rather than returning an instance of ``B`` directly marshallers first produce a
``Marshalling[B]``. This allows for querying the ``MediaType`` and potentially the ``HttpCharset`` that the marshaller
will produce before the actual marshalling is triggered. Apart from enabling content negotiation this design allows for
delaying the actual construction of the marshalling target instance to the very last moment when it is really needed.
This is how ``Marshalling`` is defined:
.. includecode2:: /../../akka-http/src/main/scala/akka/http/scaladsl/marshalling/Marshaller.scala
:snippet: marshalling
Predefined Marshallers
----------------------
Akka HTTP already predefines a number of marshallers for the most common types.
Specifically these are:
- PredefinedToEntityMarshallers_
- ``Array[Byte]``
- ``ByteString``
- ``Array[Char]``
- ``String``
- ``akka.http.scaladsl.model.FormData``
- ``akka.http.scaladsl.model.MessageEntity``
- ``T <: akka.http.scaladsl.model.Multipart``
- PredefinedToResponseMarshallers_
- ``T``, if a ``ToEntityMarshaller[T]`` is available
- ``HttpResponse``
- ``StatusCode``
- ``(StatusCode, T)``, if a ``ToEntityMarshaller[T]`` is available
- ``(Int, T)``, if a ``ToEntityMarshaller[T]`` is available
- ``(StatusCode, immutable.Seq[HttpHeader], T)``, if a ``ToEntityMarshaller[T]`` is available
- ``(Int, immutable.Seq[HttpHeader], T)``, if a ``ToEntityMarshaller[T]`` is available
- PredefinedToRequestMarshallers_
- ``HttpRequest``
- ``Uri``
- ``(HttpMethod, Uri, T)``, if a ``ToEntityMarshaller[T]`` is available
- ``(HttpMethod, Uri, immutable.Seq[HttpHeader], T)``, if a ``ToEntityMarshaller[T]`` is available
- GenericMarshallers_
- ``Marshaller[Throwable, T]``
- ``Marshaller[Option[A], B]``, if a ``Marshaller[A, B]`` and an ``EmptyValue[B]`` is available
- ``Marshaller[Either[A1, A2], B]``, if a ``Marshaller[A1, B]`` and a ``Marshaller[A2, B]`` is available
- ``Marshaller[Future[A], B]``, if a ``Marshaller[A, B]`` is available
- ``Marshaller[Try[A], B]``, if a ``Marshaller[A, B]`` is available
.. _PredefinedToEntityMarshallers: @github@/akka-http/src/main/scala/akka/http/scaladsl/marshalling/PredefinedToEntityMarshallers.scala
.. _PredefinedToResponseMarshallers: @github@/akka-http/src/main/scala/akka/http/scaladsl/marshalling/PredefinedToResponseMarshallers.scala
.. _PredefinedToRequestMarshallers: @github@/akka-http/src/main/scala/akka/http/scaladsl/marshalling/PredefinedToRequestMarshallers.scala
.. _GenericMarshallers: @github@/akka-http/src/main/scala/akka/http/scaladsl/marshalling/GenericMarshallers.scala
Implicit Resolution
-------------------
The marshalling infrastructure of Akka HTTP relies on a type-class based approach, which means that ``Marshaller``
instances from a certain type ``A`` to a certain type ``B`` have to be available implicitly.
The implicits for most of the predefined marshallers in Akka HTTP are provided through the companion object of the
``Marshaller`` trait. This means that they are always available and never need to be explicitly imported.
Additionally, you can simply "override" them by bringing your own custom version into local scope.
Custom Marshallers
------------------
Akka HTTP gives you a few convenience tools for constructing marshallers for your own types.
Before you do that you need to think about what kind of marshaller you want to create.
If all your marshaller needs to produce is a ``MessageEntity`` then you should probably provide a
``ToEntityMarshaller[T]``. The advantage here is that it will work on both the client- as well as the server-side since
a ``ToResponseMarshaller[T]`` as well as a ``ToRequestMarshaller[T]`` can automatically be created if a
``ToEntityMarshaller[T]`` is available.
If, however, your marshaller also needs to set things like the response status code, the request method, the request URI
or any headers then a ``ToEntityMarshaller[T]`` won't work. You'll need to fall down to providing a
``ToResponseMarshaller[T]`` or a ``ToRequestMarshaller[T]`` directly.
For writing you own marshallers you won't have to "manually" implement the ``Marshaller`` trait directly.
Rather, it should be possible to use one of the convenience construction helpers defined on the ``Marshaller``
companion:
.. includecode2:: /../../akka-http/src/main/scala/akka/http/scaladsl/marshalling/Marshaller.scala
:snippet: marshaller-creation
Deriving Marshallers
--------------------
Sometimes you can save yourself some work by reusing existing marshallers for your custom ones.
The idea is to "wrap" an existing marshaller with some logic to "re-target" it to your type.
In this regard wrapping a marshaller can mean one or both of the following two things:
- Transform the input before it reaches the wrapped marshaller
- Transform the output of the wrapped marshaller
For the latter (transforming the output) you can use ``baseMarshaller.map``, which works exactly as it does for functions.
For the former (transforming the input) you have four alternatives:
- ``baseMarshaller.compose``
- ``baseMarshaller.composeWithEC``
- ``baseMarshaller.wrap``
- ``baseMarshaller.wrapWithEC``
``compose`` works just like it does for functions.
``wrap`` is a compose that allows you to also change the ``ContentType`` that the marshaller marshals to.
The ``...WithEC`` variants allow you to receive an ``ExecutionContext`` internally if you need one, without having to
depend on one being available implicitly at the usage site.
Using Marshallers
-----------------
In many places throughput Akka HTTP marshallers are used implicitly, e.g. when you define how to :ref:`-complete-` a
request using the :ref:`Routing DSL <http-high-level-server-side-api>`.
However, you can also use the marshalling infrastructure directly if you wish, which can be useful for example in tests.
The best entry point for this is the ``akka.http.scaladsl.marshalling.Marshal`` object, which you can use like this:
.. TODO rewrite for Java
.. .. includecode2:: ../../code/docs/http/scaladsl/MarshalSpec.scala
:snippet: use marshal

View file

@ -0,0 +1,76 @@
.. _http-timeouts-java:
Akka HTTP Timeouts
==================
Akka HTTP comes with a variety of built-in timeout mechanisms to protect your servers from malicious attacks or
programming mistakes. Some of these are simply configuration options (which may be overriden in code) while others
are left to the streaming APIs and are easily implementable as patterns in user-code directly.
Common timeouts
---------------
Idle timeouts
^^^^^^^^^^^^^
The ``idle-timeout`` is a global setting which sets the maximum inactivity time of a given connection.
In other words, if a connection is open but no request/response is being written to it for over ``idle-timeout`` time,
the connection will be automatically closed.
The setting works the same way for all connections, be it server-side or client-side, and it's configurable
independently for each of those using the following keys::
akka.http.server.idle-timeout
akka.http.client.idle-timeout
akka.http.http-connection-pool.idle-timeout
akka.http.http-connection-pool.client.idle-timeout
.. note::
For the connection pooled client side the idle period is counted only when the pool has no pending requests waiting.
Server timeouts
---------------
.. _request-timeout-java:
Request timeout
^^^^^^^^^^^^^^^
Request timeouts are a mechanism that limits the maximum time it may take to produce an ``HttpResponse`` from a route.
If that deadline is not met the server will automatically inject a Service Unavailable HTTP response and close the connection
to prevent it from leaking and staying around indefinitely (for example if by programming error a Future would never complete,
never sending the real response otherwise).
The default ``HttpResponse`` that is written when a request timeout is exceeded looks like this:
.. includecode2:: /../../akka-http-core/src/main/scala/akka/http/impl/engine/server/HttpServerBluePrint.scala
:snippet: default-request-timeout-httpresponse
A default request timeout is applied globally to all routes and can be configured using the
``akka.http.server.request-timeout`` setting (which defaults to 20 seconds).
.. note::
Please note that if multiple requests (``R1,R2,R3,...``) were sent by a client (see "HTTP pipelining")
using the same connection and the ``n-th`` request triggers a request timeout the server will reply with an Http Response
and close the connection, leaving the ``(n+1)-th`` (and subsequent requests on the same connection) unhandled.
The request timeout can be configured at run-time for a given route using the any of the :ref:`TimeoutDirectives`.
Bind timeout
^^^^^^^^^^^^
The bind timeout is the time period within which the TCP binding process must be completed (using any of the ``Http().bind*`` methods).
It can be configured using the ``akka.http.server.bind-timeout`` setting.
Client timeouts
---------------
Connecting timeout
^^^^^^^^^^^^^^^^^^
The connecting timeout is the time period within which the TCP connecting process must be completed.
Tweaking it should rarely be required, but it allows erroring out the connection in case a connection
is unable to be established for a given amount of time.
it can be configured using the ``akka.http.client.connecting-timeout`` setting.

View file

@ -0,0 +1,124 @@
.. _http-unmarshalling-java:
Unmarshalling
=============
TODO overhaul for Java
"Unmarshalling" is the process of converting some kind of a lower-level representation, often a "wire format", into a
higher-level (object) structure. Other popular names for it are "Deserialization" or "Unpickling".
In Akka HTTP "Unmarshalling" means the conversion of a lower-level source object, e.g. a ``MessageEntity``
(which forms the "entity body" of an HTTP request or response) or a full ``HttpRequest`` or ``HttpResponse``,
into an instance of type ``T``.
Basic Design
------------
Unmarshalling of instances of type ``A`` into instances of type ``B`` is performed by an ``Unmarshaller[A, B]``.
Akka HTTP also predefines a number of helpful aliases for the types of unmarshallers that you'll likely work with most:
.. includecode2:: /../../akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/package.scala
:snippet: unmarshaller-aliases
At its core an ``Unmarshaller[A, B]`` is very similar to a ``Function<A, CompletionStage<B>>`` and as such quite a bit simpler
than its :ref:`marshalling <http-marshalling-java>` counterpart. The process of unmarshalling does not have to support
content negotiation which saves two additional layers of indirection that are required on the marshalling side.
Predefined Unmarshallers
------------------------
Akka HTTP already predefines a number of marshallers for the most common types.
Specifically these are:
- PredefinedFromStringUnmarshallers_
- ``Byte``
- ``Short``
- ``Int``
- ``Long``
- ``Float``
- ``Double``
- ``Boolean``
- PredefinedFromEntityUnmarshallers_
- ``Array[Byte]``
- ``ByteString``
- ``Array[Char]``
- ``String``
- ``akka.http.scaladsl.model.FormData``
- GenericUnmarshallers_
- ``Unmarshaller[T, T]`` (identity unmarshaller)
- ``Unmarshaller[Option[A], B]``, if an ``Unmarshaller[A, B]`` is available
- ``Unmarshaller[A, Option[B]]``, if an ``Unmarshaller[A, B]`` is available
.. _PredefinedFromStringUnmarshallers: @github@/akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/PredefinedFromStringUnmarshallers.scala
.. _PredefinedFromEntityUnmarshallers: @github@/akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/PredefinedFromEntityUnmarshallers.scala
.. _GenericUnmarshallers: @github@/akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/GenericUnmarshallers.scala
Implicit Resolution
-------------------
The unmarshalling infrastructure of Akka HTTP relies on a type-class based approach, which means that ``Unmarshaller``
instances from a certain type ``A`` to a certain type ``B`` have to be available implicitly.
The implicits for most of the predefined unmarshallers in Akka HTTP are provided through the companion object of the
``Unmarshaller`` trait. This means that they are always available and never need to be explicitly imported.
Additionally, you can simply "override" them by bringing your own custom version into local scope.
Custom Unmarshallers
--------------------
Akka HTTP gives you a few convenience tools for constructing unmarshallers for your own types.
Usually you won't have to "manually" implement the ``Unmarshaller`` trait directly.
Rather, it should be possible to use one of the convenience construction helpers defined on the ``Marshaller``
companion:
TODO rewrite sample for Java
..
.. includecode2:: /../../akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/Unmarshaller.scala
:snippet: unmarshaller-creation
Deriving Unmarshallers
----------------------
Sometimes you can save yourself some work by reusing existing unmarshallers for your custom ones.
The idea is to "wrap" an existing unmarshaller with some logic to "re-target" it to your type.
Usually what you want to do is to transform the output of some existing unmarshaller and convert it to your type.
For this type of unmarshaller transformation Akka HTTP defines these methods:
- ``baseUnmarshaller.transform``
- ``baseUnmarshaller.map``
- ``baseUnmarshaller.mapWithInput``
- ``baseUnmarshaller.flatMap``
- ``baseUnmarshaller.flatMapWithInput``
- ``baseUnmarshaller.recover``
- ``baseUnmarshaller.withDefaultValue``
- ``baseUnmarshaller.mapWithCharset`` (only available for FromEntityUnmarshallers)
- ``baseUnmarshaller.forContentTypes`` (only available for FromEntityUnmarshallers)
The method signatures should make their semantics relatively clear.
Using Unmarshallers
-------------------
In many places throughput Akka HTTP unmarshallers are used implicitly, e.g. when you want to access the :ref:`-entity-`
of a request using the :ref:`Routing DSL <http-high-level-server-side-api>`.
However, you can also use the unmarshalling infrastructure directly if you wish, which can be useful for example in tests.
The best entry point for this is the ``akka.http.scaladsl.unmarshalling.Unmarshal`` object, which you can use like this:
.. TODO rewrite for java
.. .. includecode2:: ../../code/docs/http/scaladsl/UnmarshalSpec.scala
:snippet: use unmarshal

View file

@ -36,7 +36,8 @@ akka-http-jackson
server-side/websocket-support
routing-dsl/index
client-side/index
server-side-https-support
common/index
configuration
server-side-https-support
.. _jackson: https://github.com/FasterXML/jackson
.. _jackson: https://github.com/FasterXML/jackson

View file

@ -0,0 +1,148 @@
.. _Predefined Directives-java:
Predefined Directives (alphabetically)
======================================
================================================ ============================================================================
Directive Description
================================================ ============================================================================
:ref:`-authenticateBasic-java-` Wraps the inner route with Http Basic authentication support using a given ``Authenticator<T>``
:ref:`-authenticateBasicAsync-java-` Wraps the inner route with Http Basic authentication support using a given ``AsyncAuthenticator<T>``
:ref:`-authenticateBasicPF-java-` Wraps the inner route with Http Basic authentication support using a given ``AuthenticatorPF<T>``
:ref:`-authenticateBasicPFAsync-java-` Wraps the inner route with Http Basic authentication support using a given ``AsyncAuthenticatorPF<T>``
:ref:`-authenticateOAuth2-java-` Wraps the inner route with OAuth Bearer Token authentication support using a given ``AuthenticatorPF<T>``
:ref:`-authenticateOAuth2Async-java-` Wraps the inner route with OAuth Bearer Token authentication support using a given ``AsyncAuthenticator<T>``
:ref:`-authenticateOAuth2PF-java-` Wraps the inner route with OAuth Bearer Token authentication support using a given ``AuthenticatorPF<T>``
:ref:`-authenticateOAuth2PFAsync-java-` Wraps the inner route with OAuth Bearer Token authentication support using a given ``AsyncAuthenticatorPF<T>``
:ref:`-authenticateOrRejectWithChallenge-java-` Lifts an authenticator function into a directive
:ref:`-authorize-java-` Applies the given authorization check to the request
:ref:`-authorizeAsync-java-` Applies the given asynchronous authorization check to the request
:ref:`-cancelRejection-java-` Adds a ``TransformationRejection`` cancelling all rejections equal to the given one to the rejections potentially coming back from the inner route.
:ref:`-cancelRejections-java-` Adds a ``TransformationRejection`` cancelling all matching rejections to the rejections potentially coming back from the inner route
:ref:`-complete-java-` Completes the request using the given arguments
:ref:`-completeOrRecoverWith-java-` "Unwraps" a ``CompletionStage<T>`` and runs the inner route when the future has failed with the error as an extraction of type ``Throwable``
:ref:`-completeWith-java-` Uses the marshaller for a given type to extract a completion function
:ref:`-conditional-java-` Wraps its inner route with support for conditional requests as defined by http://tools.ietf.org/html/rfc7232
:ref:`-cookie-java-` Extracts the ``HttpCookie`` with the given name
:ref:`-decodeRequest-java-` Decompresses the request if it is ``gzip`` or ``deflate`` compressed
:ref:`-decodeRequestWith-java-` Decodes the incoming request using one of the given decoders
:ref:`-delete-java-` Rejects all non-DELETE requests
:ref:`-deleteCookie-java-` Adds a ``Set-Cookie`` response header expiring the given cookies
:ref:`-encodeResponse-java-` Encodes the response with the encoding that is requested by the client via the ``Accept-Encoding`` header (``NoCoding``, ``Gzip`` and ``Deflate``)
:ref:`-encodeResponseWith-java-` Encodes the response with the encoding that is requested by the client via the ``Accept-Encoding`` header (from a user-defined set)
:ref:`-entity-java-` Extracts the request entity unmarshalled to a given type
:ref:`-extract-java-` Extracts a single value using a ``RequestContext ⇒ T`` function
:ref:`-extractClientIP-java-` Extracts the client's IP from either the ``X-Forwarded-``, ``Remote-Address`` or ``X-Real-IP`` header
:ref:`-extractCredentials-java-` Extracts the potentially present ``HttpCredentials`` provided with the request's ``Authorization`` header
:ref:`-extractExecutionContext-java-` Extracts the ``ExecutionContext`` from the ``RequestContext``
:ref:`-extractMaterializer-java-` Extracts the ``Materializer`` from the ``RequestContext``
:ref:`-extractHost-java-` Extracts the hostname part of the Host request header value
:ref:`-extractLog-java-` Extracts the ``LoggingAdapter`` from the ``RequestContext``
:ref:`-extractMethod-java-` Extracts the request method
:ref:`-extractRequest-java-` Extracts the current ``HttpRequest`` instance
:ref:`-extractRequestContext-java-` Extracts the ``RequestContext`` itself
:ref:`-extractScheme-java-` Extracts the URI scheme from the request
:ref:`-extractSettings-java-` Extracts the ``RoutingSettings`` from the ``RequestContext``
:ref:`-extractUnmatchedPath-java-` Extracts the yet unmatched path from the ``RequestContext``
:ref:`-extractUri-java-` Extracts the complete request URI
:ref:`-failWith-java-` Bubbles the given error up the response chain where it is dealt with by the closest :ref:`-handleExceptions-java-` directive and its ``ExceptionHandler``
:ref:`-fileUpload-java-` Provides a stream of an uploaded file from a multipart request
:ref:`-formField-java-` Extracts an HTTP form field from the request
:ref:`-formFieldMap-java-` Extracts a number of HTTP form field from the request as a ``Map<String, String>``
:ref:`-formFieldMultiMap-java-` Extracts a number of HTTP form field from the request as a ``Map<String, List<String>``
:ref:`-formFieldList-java-` Extracts a number of HTTP form field from the request as a ``List<Pair<String, String>>``
:ref:`-get-java-` Rejects all non-GET requests
:ref:`-getFromBrowseableDirectories-java-` Serves the content of the given directories as a file-system browser, i.e. files are sent and directories served as browseable listings
:ref:`-getFromBrowseableDirectory-java-` Serves the content of the given directory as a file-system browser, i.e. files are sent and directories served as browseable listings
:ref:`-getFromDirectory-java-` Completes GET requests with the content of a file underneath a given file-system directory
:ref:`-getFromFile-java-` Completes GET requests with the content of a given file
:ref:`-getFromResource-java-` Completes GET requests with the content of a given class-path resource
:ref:`-getFromResourceDirectory-java-` Completes GET requests with the content of a file underneath a given "class-path resource directory"
:ref:`-handleExceptions-java-` Transforms exceptions thrown during evaluation of the inner route using the given ``ExceptionHandler``
:ref:`-handleRejections-java-` Transforms rejections produced by the inner route using the given ``RejectionHandler``
:ref:`-handleWebSocketMessages-java-` Handles websocket requests with the given handler and rejects other requests with an ``ExpectedWebSocketRequestRejection``
:ref:`-handleWebSocketMessagesForProtocol-java-` Handles websocket requests with the given handler if the subprotocol matches and rejects other requests with an ``ExpectedWebSocketRequestRejection`` or an ``UnsupportedWebSocketSubprotocolRejection``.
:ref:`-handleWith-java-` Completes the request using a given function
:ref:`-head-java-` Rejects all non-HEAD requests
:ref:`-headerValue-java-` Extracts an HTTP header value using a given ``HttpHeader ⇒ Option<T>`` function
:ref:`-headerValueByName-java-` Extracts the value of the first HTTP request header with a given name
:ref:`-headerValueByType-java-` Extracts the first HTTP request header of the given type
:ref:`-headerValuePF-java-` Extracts an HTTP header value using a given ``PartialFunction<HttpHeader, T>``
:ref:`-host-java-` Rejects all requests with a non-matching host name
:ref:`-listDirectoryContents-java-` Completes GET requests with a unified listing of the contents of all given file-system directories
:ref:`-logRequest-java-` Produces a log entry for every incoming request
:ref:`-logRequestResult-java-` Produces a log entry for every incoming request and ``RouteResult``
:ref:`-logResult-java-` Produces a log entry for every ``RouteResult``
:ref:`-mapInnerRoute-java-` Transforms its inner ``Route`` with a ``Route => Route`` function
:ref:`-mapRejections-java-` Transforms rejections from a previous route with an ``List<Rejection] ⇒ List<Rejection>`` function
:ref:`-mapRequest-java-` Transforms the request with an ``HttpRequest => HttpRequest`` function
:ref:`-mapRequestContext-java-` Transforms the ``RequestContext`` with a ``RequestContext => RequestContext`` function
:ref:`-mapResponse-java-` Transforms the response with an ``HttpResponse => HttpResponse`` function
:ref:`-mapResponseEntity-java-` Transforms the response entity with an ``ResponseEntity ⇒ ResponseEntity`` function
:ref:`-mapResponseHeaders-java-` Transforms the response headers with an ``List<HttpHeader] ⇒ List<HttpHeader>`` function
:ref:`-mapRouteResult-java-` Transforms the ``RouteResult`` with a ``RouteResult ⇒ RouteResult`` function
:ref:`-mapRouteResultFuture-java-` Transforms the ``RouteResult`` future with a ``CompletionStage<RouteResult] ⇒ CompletionStage<RouteResult>`` function
:ref:`-mapRouteResultPF-java-` Transforms the ``RouteResult`` with a ``PartialFunction<RouteResult, RouteResult>``
:ref:`-mapRouteResultWith-java-` Transforms the ``RouteResult`` with a ``RouteResult ⇒ CompletionStage<RouteResult>`` function
:ref:`-mapRouteResultWithPF-java-` Transforms the ``RouteResult`` with a ``PartialFunction<RouteResult, CompletionStage<RouteResult]>``
:ref:`-mapSettings-java-` Transforms the ``RoutingSettings`` with a ``RoutingSettings ⇒ RoutingSettings`` function
:ref:`-mapUnmatchedPath-java-` Transforms the ``unmatchedPath`` of the ``RequestContext`` using a ``Uri.Path ⇒ Uri.Path`` function
:ref:`-method-java-` Rejects all requests whose HTTP method does not match the given one
:ref:`-onComplete-java-` "Unwraps" a ``CompletionStage<T>`` and runs the inner route after future completion with the future's value as an extraction of type ``Try<T>``
:ref:`-onSuccess-java-` "Unwraps" a ``CompletionStage<T>`` and runs the inner route after future completion with the future's value as an extraction of type ``T``
:ref:`-optionalCookie-java-` Extracts the ``HttpCookiePair`` with the given name as an ``Option<HttpCookiePair>``
:ref:`-optionalHeaderValue-java-` Extracts an optional HTTP header value using a given ``HttpHeader ⇒ Option<T>`` function
:ref:`-optionalHeaderValueByName-java-` Extracts the value of the first optional HTTP request header with a given name
:ref:`-optionalHeaderValueByType-java-` Extracts the first optional HTTP request header of the given type
:ref:`-optionalHeaderValuePF-java-` Extracts an optional HTTP header value using a given ``PartialFunction<HttpHeader, T>``
:ref:`-options-java-` Rejects all non-OPTIONS requests
:ref:`-overrideMethodWithParameter-java-` Changes the request method to the value of the specified query parameter
:ref:`-parameter-java-` Extracts a query parameter value from the request
:ref:`-parameterMap-java-` Extracts the request's query parameters as a ``Map<String, String>``
:ref:`-parameterMultiMap-java-` Extracts the request's query parameters as a ``Map<String, List<String>>``
:ref:`-parameterList-java-` Extracts the request's query parameters as a ``Seq<Pair<String, String>>``
:ref:`-pass-java-` Always simply passes the request on to its inner route, i.e. doesn't do anything, neither with the request nor the response
:ref:`-patch-java-` Rejects all non-PATCH requests
:ref:`-path-java-` Applies the given ``PathMatcher`` to the remaining unmatched path after consuming a leading slash
:ref:`-pathEnd-java-` Only passes on the request to its inner route if the request path has been matched completely
:ref:`-pathEndOrSingleSlash-java-` Only passes on the request to its inner route if the request path has been matched completely or only consists of exactly one remaining slash
:ref:`-pathPrefix-java-` Applies the given ``PathMatcher`` to a prefix of the remaining unmatched path after consuming a leading slash
:ref:`-pathPrefixTest-java-` Checks whether the unmatchedPath has a prefix matched by the given ``PathMatcher`` after implicitly consuming a leading slash
:ref:`-pathSingleSlash-java-` Only passes on the request to its inner route if the request path consists of exactly one remaining slash
:ref:`-pathSuffix-java-` Applies the given ``PathMatcher`` to a suffix of the remaining unmatched path (Caution: check java!)
:ref:`-pathSuffixTest-java-` Checks whether the unmatched path has a suffix matched by the given ``PathMatcher`` (Caution: check java!)
:ref:`-post-java-` Rejects all non-POST requests
:ref:`-provide-java-` Injects a given value into a directive
:ref:`-put-java-` Rejects all non-PUT requests
:ref:`-rawPathPrefix-java-` Applies the given matcher directly to a prefix of the unmatched path of the ``RequestContext``, without implicitly consuming a leading slash
:ref:`-rawPathPrefixTest-java-` Checks whether the unmatchedPath has a prefix matched by the given ``PathMatcher``
:ref:`-recoverRejections-java-` Transforms rejections from the inner route with an ``List<Rejection] ⇒ RouteResult`` function
:ref:`-recoverRejectionsWith-java-` Transforms rejections from the inner route with an ``List<Rejection] ⇒ CompletionStage<RouteResult>`` function
:ref:`-redirect-java-` Completes the request with redirection response of the given type to the given URI
:ref:`-redirectToNoTrailingSlashIfPresent-java-` If the request path ends with a slash, redirects to the same uri without trailing slash in the path
:ref:`-redirectToTrailingSlashIfMissing-java-` If the request path doesn't end with a slash, redirects to the same uri with trailing slash in the path
:ref:`-reject-java-` Rejects the request with the given rejections
:ref:`-rejectEmptyResponse-java-` Converts responses with an empty entity into (empty) rejections
:ref:`-requestEncodedWith-java-` Rejects the request with an ``UnsupportedRequestEncodingRejection`` if its encoding doesn't match the given one
:ref:`-requestEntityEmpty-java-` Rejects if the request entity is non-empty
:ref:`-requestEntityPresent-java-` Rejects with a ``RequestEntityExpectedRejection`` if the request entity is empty
:ref:`-respondWithDefaultHeader-java-` Adds a given response header if the response doesn't already contain a header with the same name
:ref:`-respondWithDefaultHeaders-java-` Adds the subset of the given headers to the response which doesn't already have a header with the respective name present in the response
:ref:`-respondWithHeader-java-` Unconditionally adds a given header to the outgoing response
:ref:`-respondWithHeaders-java-` Unconditionally adds the given headers to the outgoing response
:ref:`-responseEncodingAccepted-java-` Rejects the request with an ``UnacceptedResponseEncodingRejection`` if the given response encoding is not accepted by the client
:ref:`-scheme-java-` Rejects all requests whose URI scheme doesn't match the given one
:ref:`-selectPreferredLanguage-java-` Inspects the request's ``Accept-Language`` header and determines, which of a given set of language alternatives is preferred by the client
:ref:`-setCookie-java-` Adds a ``Set-Cookie`` response header with the given cookies
:ref:`-uploadedFile-java-` Streams one uploaded file from a multipart request to a file on disk
:ref:`-validate-java-` Checks a given condition before running its inner route
:ref:`-withoutRequestTimeout-java-` Disables :ref:`request timeouts <request-timeout-java>` for a given route.
:ref:`-withExecutionContext-java-` Runs its inner route with the given alternative ``ExecutionContext``
:ref:`-withMaterializer-java-` Runs its inner route with the given alternative ``Materializer``
:ref:`-withLog-java-` Runs its inner route with the given alternative ``LoggingAdapter``
:ref:`-withRangeSupport-java-` Adds ``Accept-Ranges: bytes`` to responses to GET requests, produces partial responses if the initial request contained a valid ``Range`` header
:ref:`-withRequestTimeout-java-` Configures the :ref:`request timeouts <request-timeout-java>` for a given route.
:ref:`-withRequestTimeoutResponse-java-` Prepares the ``HttpResponse`` that is emitted if a request timeout is triggered. ``RequestContext => RequestContext`` function
:ref:`-withSettings-java-` Runs its inner route with the given alternative ``RoutingSettings``
================================================ ============================================================================

View file

@ -0,0 +1,19 @@
.. _-cancelRejection-java-:
cancelRejection
===============
Description
-----------
Adds a ``TransformationRejection`` cancelling all rejections equal to the
given one to the rejections potentially coming back from the inner route.
Read :ref:`rejections-java` to learn more about rejections.
For more advanced handling of rejections refer to the :ref:`-handleRejections-java-` directive
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,21 @@
.. _-cancelRejections-java-:
cancelRejections
================
Description
-----------
Adds a ``TransformationRejection`` cancelling all rejections created by the inner route for which
the condition argument function returns ``true``.
See also :ref:`-cancelRejection-java-`, for canceling a specific rejection.
Read :ref:`rejections-java` to learn more about rejections.
For more advanced handling of rejections refer to the :ref:`-handleRejections-java-` directive
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-extract-java-:
extract
=======
Description
-----------
The ``extract`` directive is used as a building block for :ref:`Custom Directives-java` to extract data from the
``RequestContext`` and provide it to the inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-extractExecutionContext-java-:
extractExecutionContext
=======================
Description
-----------
Extracts the ``ExecutionContext`` from the ``RequestContext``.
See :ref:`-withExecutionContext-java-` to see how to customise the execution context provided for an inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,18 @@
.. _-extractLog-java-:
extractLog
==========
Description
-----------
Extracts a :class:`LoggingAdapter` from the request context which can be used for logging inside the route.
The ``extractLog`` directive is used for providing logging to routes, such that they don't have to depend on
closing over a logger provided in the class body.
See :ref:`-extract-java-` and :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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-extractMaterializer-java-:
extractMaterializer
===================
Description
-----------
Extracts the ``Materializer`` from the ``RequestContext``, which can be useful when you want to run an
Akka Stream directly in your route.
See also :ref:`-withMaterializer-java-` to see how to customise the used materializer for specific inner routes.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-extractRequest-java-:
extractRequest
==============
Description
-----------
Extracts the complete ``HttpRequest`` instance.
Use ``extractRequest`` to extract just the complete URI of the request. Usually there's little use of
extracting the complete request because extracting of most of the aspects of HttpRequests is handled by specialized
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,19 @@
.. _-extractRequestContext-java-:
extractRequestContext
=====================
Description
-----------
Extracts the request's underlying :class:`RequestContext`.
This directive is used as a building block for most of the other directives,
which extract the context and by inspecting some of it's values can decide
what to do with the request - for example provide a value, or reject the request.
See also :ref:`-extractRequest-java-` if only interested in the :class:`HttpRequest` instance itself.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-extractSettings-java-:
extractSettings
===============
Description
-----------
Extracts the :class:`RoutingSettings` from the :class:`RequestContext`.
By default the settings of the ``Http()`` extension running the route will be returned.
It is possible to override the settings for specific sub-routes by using the :ref:`-withSettings-java-` directive.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,18 @@
.. _-extractUnmatchedPath-java-:
extractUnmatchedPath
====================
Description
-----------
Extracts the unmatched path from the request context.
The ``extractUnmatchedPath`` directive extracts the remaining path that was not yet matched by any of the :ref:`PathDirectives-java`
(or any custom ones that change the unmatched path field of the request context). You can use it for building directives
that handle complete suffixes of paths (like the ``getFromDirectory`` directives and similar ones).
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,15 @@
.. _-extractUri-java-:
extractUri
==========
Description
-----------
Access the full URI of the request.
Use :ref:`SchemeDirectives-java`, :ref:`HostDirectives-java`, :ref:`PathDirectives-java`, and :ref:`ParameterDirectives-java` for more
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,123 @@
.. _BasicDirectives-java:
BasicDirectives
===============
Basic directives are building blocks for building :ref:`Custom Directives`. As such they
usually aren't used in a route directly but rather in the definition of new directives.
.. _ProvideDirectives-java:
Providing Values to Inner Routes
--------------------------------
These directives provide values to the inner routes with extractions. They can be distinguished
on two axes: a) provide a constant value or extract a value from the ``RequestContext`` b) provide
a single value or a tuple of values.
* :ref:`-extract-java-`
* :ref:`-extractExecutionContext-java-`
* :ref:`-extractMaterializer-java-`
* :ref:`-extractLog-java-`
* :ref:`-extractRequest-java-`
* :ref:`-extractRequestContext-java-`
* :ref:`-extractSettings-java-`
* :ref:`-extractUnmatchedPath-java-`
* :ref:`-extractUri-java-`
* :ref:`-provide-java-`
.. _Request Transforming Directives-java:
Transforming the Request(Context)
---------------------------------
* :ref:`-mapRequest-java-`
* :ref:`-mapRequestContext-java-`
* :ref:`-mapSettings-java-`
* :ref:`-mapUnmatchedPath-java-`
* :ref:`-withExecutionContext-java-`
* :ref:`-withMaterializer-java-`
* :ref:`-withLog-java-`
* :ref:`-withSettings-java-`
.. _Response Transforming Directives-java:
Transforming the Response
-------------------------
These directives allow to hook into the response path and transform the complete response or
the parts of a response or the list of rejections:
* :ref:`-mapResponse-java-`
* :ref:`-mapResponseEntity-java-`
* :ref:`-mapResponseHeaders-java-`
.. _Result Transformation Directives-java:
Transforming the RouteResult
----------------------------
These directives allow to transform the RouteResult of the inner route.
* :ref:`-cancelRejection-java-`
* :ref:`-cancelRejections-java-`
* :ref:`-mapRejections-java-`
* :ref:`-mapRouteResult-java-`
* :ref:`-mapRouteResultFuture-java-`
* :ref:`-mapRouteResultPF-java-`
* :ref:`-mapRouteResultWith-java-`
* :ref:`-mapRouteResultWithPF-java-`
* :ref:`-recoverRejections-java-`
* :ref:`-recoverRejectionsWith-java-`
Other
-----
* :ref:`-mapInnerRoute-java-`
* :ref:`-pass-java-`
Alphabetically
--------------
.. toctree::
:maxdepth: 1
cancelRejection
cancelRejections
extract
extractExecutionContext
extractMaterializer
extractLog
extractRequest
extractRequestContext
extractSettings
extractUnmatchedPath
extractUri
mapInnerRoute
mapRejections
mapRequest
mapRequestContext
mapResponse
mapResponseEntity
mapResponseHeaders
mapRouteResult
mapRouteResultFuture
mapRouteResultPF
mapRouteResultWith
mapRouteResultWithPF
mapSettings
mapUnmatchedPath
pass
provide
recoverRejections
recoverRejectionsWith
withExecutionContext
withMaterializer
withLog
withSettings

View file

@ -0,0 +1,15 @@
.. _-mapInnerRoute-java-:
mapInnerRoute
=============
Description
-----------
Changes the execution model of the inner route by wrapping it with arbitrary logic.
The ``mapInnerRoute`` directive is used as a building block for :ref:`Custom Directives-java` to replace the inner route
with any other route. Usually, the returned route wraps the original one with custom execution logic.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,19 @@
.. _-mapRejections-java-:
mapRejections
=============
Description
-----------
**Low level directive** unless you're sure you need to be working on this low-level you might instead
want to try the :ref:`-handleRejections-java-` directive which provides a nicer DSL for building rejection handlers.
The ``mapRejections`` directive is used as a building block for :ref:`Custom Directives-java` to transform a list
of rejections from the inner route to a new list of rejections.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,19 @@
.. _-mapRequest-java-:
mapRequest
==========
Description
-----------
Transforms the request before it is handled by the inner route.
The ``mapRequest`` directive is used as a building block for :ref:`Custom Directives-java` to transform a request before it
is handled by the inner route. Changing the ``request.uri`` parameter has no effect on path matching in the inner route
because the unmatched path is a separate field of the ``RequestContext`` value which is passed into routes. To change
the unmatched path or other fields of the ``RequestContext`` use the :ref:`-mapRequestContext-java-` directive.
See :ref:`Request Transforming Directives-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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,18 @@
.. _-mapRequestContext-java-:
mapRequestContext
=================
Description
-----------
Transforms the ``RequestContext`` before it is passed to the inner route.
The ``mapRequestContext`` directive is used as a building block for :ref:`Custom Directives-java` to transform
the request context before it is passed to the inner route. To change only the request value itself the
:ref:`-mapRequest-java-` directive can be used instead.
See :ref:`Request Transforming Directives-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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,21 @@
.. _-mapResponse-java-:
mapResponse
===========
Description
-----------
The ``mapResponse`` directive is used as a building block for :ref:`Custom Directives-java` to transform a response that
was generated by the inner route. This directive transforms complete responses.
See also :ref:`-mapResponseHeaders-java-` or :ref:`-mapResponseEntity-java-` for more specialized variants and
:ref:`Response Transforming Directives-java` for similar directives.
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 <https://github.com/akka/akka/issues/20466>`_.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-mapResponseEntity-java-:
mapResponseEntity
=================
Description
-----------
The ``mapResponseEntity`` directive is used as a building block for :ref:`Custom Directives-java` to transform a
response entity that was generated by the inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-mapResponseHeaders-java-:
mapResponseHeaders
==================
Description
-----------
Changes the list of response headers that was generated by the inner route.
The ``mapResponseHeaders`` directive is used as a building block for :ref:`Custom Directives-java` to transform the list of
response headers that was generated by the inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-mapRouteResult-java-:
mapRouteResult
==============
Description
-----------
Changes the message the inner route sends to the responder.
The ``mapRouteResult`` directive is used as a building block for :ref:`Custom Directives-java` to transform the
:class:`RouteResult` coming back from the inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,20 @@
.. _-mapRouteResultFuture-java-:
mapRouteResultFuture
====================
Description
-----------
Asynchronous version of :ref:`-mapRouteResult-java-`.
It's similar to :ref:`-mapRouteResultWith-java-`, however it's
``Function<CompletionStage<RouteResult>, CompletionStage<RouteResult>>``
instead of ``Function<RouteResult, CompletionStage<RouteResult>>`` which may be useful when
combining multiple transformations and / or wanting to ``recover`` from a failed route result.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,20 @@
.. _-mapRouteResultPF-java-:
mapRouteResultPF
================
Description
-----------
*Partial Function* version of :ref:`-mapRouteResult-java-`.
Changes the message the inner route sends to the responder.
The ``mapRouteResult`` directive is used as a building block for :ref:`Custom Directives-java` to transform the
:class:`RouteResult` coming back from the inner route. It's similar to the :ref:`-mapRouteResult-java-` directive but allows to
specify a partial function that doesn't have to handle all potential ``RouteResult`` instances.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,19 @@
.. _-mapRouteResultWith-java-:
mapRouteResultWith
==================
Description
-----------
Changes the message the inner route sends to the responder.
The ``mapRouteResult`` directive is used as a building block for :ref:`Custom Directives-java` to transform the
:class:`RouteResult` coming back from the inner route. It's similar to the :ref:`-mapRouteResult-java-` directive but
returning a ``CompletionStage`` instead of a result immediately, which may be useful for longer running transformations.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,20 @@
.. _-mapRouteResultWithPF-java-:
mapRouteResultWithPF
====================
Description
-----------
Asynchronous variant of :ref:`-mapRouteResultPF-java-`.
Changes the message the inner route sends to the responder.
The ``mapRouteResult`` directive is used as a building block for :ref:`Custom Directives-java` to transform the
:class:`RouteResult` coming back from the inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,15 @@
.. _-mapSettings-java-:
mapSettings
===========
Description
-----------
Transforms the ``RoutingSettings`` with a ``Function<RoutingSettings, RoutingSettings>``.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-mapUnmatchedPath-java-:
mapUnmatchedPath
================
Description
-----------
Transforms the unmatchedPath field of the request context for inner routes.
The ``mapUnmatchedPath`` directive is used as a building block for writing :ref:`Custom Directives-java`. You can use it
for implementing custom path matching directives.
Use ``extractUnmatchedPath`` for extracting the current 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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,14 @@
.. _-pass-java-:
pass
====
Description
-----------
A directive that passes the request unchanged to its inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-provide-java-:
provide
=======
Description
-----------
Provides a constant value to the inner route.
The `provide` directive is used as a building block for :ref:`Custom Directives-java` to provide a single value to the
inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,20 @@
.. _-recoverRejections-java-:
recoverRejections
=================
Description
-----------
**Low level directive** unless you're sure you need to be working on this low-level you might instead
want to try the :ref:`-handleRejections-java-` directive which provides a nicer DSL for building rejection handlers.
Transforms rejections from the inner route with a ``Function<Iterable<Rejection>, RouteResult>``.
A ``RouteResult`` is either a ``Complete`` containing the ``HttpResponse`` or a ``Rejected`` containing the
rejections.
.. note::
To learn more about how and why rejections work read the :ref:`rejections-java` section of the documentation.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,23 @@
.. _-recoverRejectionsWith-java-:
recoverRejectionsWith
=====================
Description
-----------
**Low level directive** unless you're sure you need to be working on this low-level you might instead
want to try the :ref:`-handleRejections-java-` directive which provides a nicer DSL for building rejection handlers.
Transforms rejections from the inner route with a ``Function<Iterable<Rejection>, CompletionStage<RouteResult>>``.
Asynchronous version of :ref:`-recoverRejections-java-`.
See :ref:`-recoverRejections-java-` (the synchronous equivalent of this directive) for a detailed description.
.. note::
To learn more about how and why rejections work read the :ref:`rejections-java` section of the documentation.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-withExecutionContext-java-:
withExecutionContext
====================
Description
-----------
Allows running an inner route using an alternative ``ExecutionContextExecutor`` in place of the default one.
The execution context can be extracted in an inner route using :ref:`-extractExecutionContext-java-` directly,
or used by directives which internally extract the materializer without sufracing this fact in the API.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-withLog-java-:
withLog
=======
Description
-----------
Allows running an inner route using an alternative :class:`LoggingAdapter` in place of the default one.
The logging adapter can be extracted in an inner route using :ref:`-extractLog-java-` directly,
or used by directives which internally extract the materializer without surfacing this fact in the API.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-withMaterializer-java-:
withMaterializer
================
Description
-----------
Allows running an inner route using an alternative ``Materializer`` in place of the default one.
The materializer can be extracted in an inner route using :ref:`-extractMaterializer-java-` directly,
or used by directives which internally extract the materializer without sufracing this fact in the API
(e.g. responding with a Chunked entity).
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-withSettings-java-:
withSettings
============
Description
-----------
Allows running an inner route using an alternative :class:`RoutingSettings` in place of the default one.
The execution context can be extracted in an inner route using :ref:`-extractSettings-java-` directly,
or used by directives which internally extract the materializer without sufracing this fact in the API.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,110 @@
Predefined Directives (by trait)
================================
All predefined directives are organized into traits that form one part of the overarching ``Directives`` trait.
.. _Request Directives-java:
Directives filtering or extracting from the request
---------------------------------------------------
:ref:`MethodDirectives-java`
Filter and extract based on the request method.
:ref:`HeaderDirectives-java`
Filter and extract based on request headers.
:ref:`PathDirectives-java`
Filter and extract from the request URI path.
:ref:`HostDirectives-java`
Filter and extract based on the target host.
:ref:`ParameterDirectives-java`, :ref:`FormFieldDirectives-java`
Filter and extract based on query parameters or form fields.
:ref:`CodingDirectives-java`
Filter and decode compressed request content.
:ref:`MarshallingDirectives-java`
Extract the request entity.
:ref:`SchemeDirectives-java`
Filter and extract based on the request scheme.
:ref:`SecurityDirectives-java`
Handle authentication data from the request.
:ref:`CookieDirectives-java`
Filter and extract cookies.
:ref:`BasicDirectives-java` and :ref:`MiscDirectives-java`
Directives handling request properties.
:ref:`FileUploadDirectives-java`
Handle file uploads.
.. _Response Directives-java:
Directives creating or transforming the response
------------------------------------------------
:ref:`CacheConditionDirectives-java`
Support for conditional requests (``304 Not Modified`` responses).
:ref:`CookieDirectives-java`
Set, modify, or delete cookies.
:ref:`CodingDirectives-java`
Compress responses.
:ref:`FileAndResourceDirectives-java`
Deliver responses from files and resources.
:ref:`RangeDirectives-java`
Support for range requests (``206 Partial Content`` responses).
:ref:`RespondWithDirectives-java`
Change response properties.
:ref:`RouteDirectives-java`
Complete or reject a request with a response.
:ref:`BasicDirectives-java` and :ref:`MiscDirectives-java`
Directives handling or transforming response properties.
:ref:`TimeoutDirectives-java`
Configure request timeouts and automatic timeout responses.
List of predefined directives by trait
--------------------------------------
.. toctree::
:maxdepth: 1
basic-directives/index
cache-condition-directives/index
coding-directives/index
cookie-directives/index
debugging-directives/index
execution-directives/index
file-and-resource-directives/index
file-upload-directives/index
form-field-directives/index
future-directives/index
header-directives/index
host-directives/index
marshalling-directives/index
method-directives/index
misc-directives/index
parameter-directives/index
path-directives/index
range-directives/index
respond-with-directives/index
route-directives/index
scheme-directives/index
security-directives/index
websocket-directives/index
timeout-directives/index

View file

@ -0,0 +1,33 @@
.. _-conditional-java-:
conditional
===========
Description
-----------
Wraps its inner route with support for Conditional Requests as defined
by http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26.
Depending on the given ``eTag`` and ``lastModified`` values this directive immediately responds with
``304 Not Modified`` or ``412 Precondition Failed`` (without calling its inner route) if the request comes with the
respective conditional headers. Otherwise the request is simply passed on to its inner route.
The algorithm implemented by this directive closely follows what is defined in `this section`__ of the
`HTTPbis spec`__.
All responses (the ones produces by this directive itself as well as the ones coming back from the inner route) are
augmented with respective ``ETag`` and ``Last-Modified`` response headers.
Since this directive requires the ``EntityTag`` and ``lastModified`` time stamp for the resource as concrete arguments
it is usually used quite deep down in the route structure (i.e. close to the leaf-level), where the exact resource
targeted by the request has already been established and the respective ETag/Last-Modified values can be determined.
The :ref:`FileAndResourceDirectives-java` internally use the ``conditional`` directive for ETag and Last-Modified support
(if the ``akka.http.routing.file-get-conditional`` setting is enabled).
__ http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-6
__ https://datatracker.ietf.org/wg/httpbis/

View file

@ -0,0 +1,9 @@
.. _CacheConditionDirectives-java:
CacheConditionDirectives
========================
.. toctree::
:maxdepth: 1
conditional

View file

@ -0,0 +1,13 @@
.. _-decodeRequest-java-:
decodeRequest
=============
Description
-----------
Decompresses the incoming request if it is ``gzip`` or ``deflate`` compressed. Uncompressed requests are passed through untouched. If the request encoded with another encoding the request is rejected with an ``UnsupportedRequestEncodingRejection``.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,13 @@
.. _-decodeRequestWith-java-:
decodeRequestWith
=================
Description
-----------
Decodes the incoming request if it is encoded with one of the given encoders. If the request encoding doesn't match one of the given encoders the request is rejected with an ``UnsupportedRequestEncodingRejection``. If no decoders are given the default encoders (``Gzip``, ``Deflate``, ``NoCoding``) are used.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,19 @@
.. _-encodeResponse-java-:
encodeResponse
==============
Description
-----------
Encodes the response with the encoding that is requested by the client via the ``Accept-Encoding`` header or rejects the request with an ``UnacceptedResponseEncodingRejection(supportedEncodings)``.
The response encoding is determined by the rules specified in RFC7231_.
If the ``Accept-Encoding`` header is missing or empty or specifies an encoding other than identity, gzip or deflate then no encoding is used.
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 <https://github.com/akka/akka/issues/20466>`_.
.. _RFC7231: http://tools.ietf.org/html/rfc7231#section-5.3.4

View file

@ -0,0 +1,22 @@
.. _-encodeResponseWith-java-:
encodeResponseWith
==================
Description
-----------
Encodes the response with the encoding that is requested by the client via the ``Accept-Encoding`` if it is among the provided encoders or rejects the request with an ``UnacceptedResponseEncodingRejection(supportedEncodings)``.
The response encoding is determined by the rules specified in RFC7231_.
If the ``Accept-Encoding`` header is missing then the response is encoded using the ``first`` encoder.
If the ``Accept-Encoding`` header is empty and ``NoCoding`` is part of the encoders then no
response encoding is used. Otherwise the request is rejected.
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 <https://github.com/akka/akka/issues/20466>`_.
.. _RFC7231: http://tools.ietf.org/html/rfc7231#section-5.3.4

View file

@ -0,0 +1,14 @@
.. _CodingDirectives-java:
CodingDirectives
================
.. toctree::
:maxdepth: 1
decodeRequest
decodeRequestWith
encodeResponse
encodeResponseWith
requestEncodedWith
responseEncodingAccepted

View file

@ -0,0 +1,15 @@
.. _-requestEncodedWith-java-:
requestEncodedWith
==================
Description
-----------
Passes the request to the inner route if the request is encoded with the argument encoding. Otherwise, rejects the request with an ``UnacceptedRequestEncodingRejection(encoding)``.
This directive is the building block for ``decodeRequest`` to reject unsupported encodings.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,13 @@
.. _-responseEncodingAccepted-java-:
responseEncodingAccepted
========================
Description
-----------
Passes the request to the inner route if the request accepts the argument encoding. Otherwise, rejects the request with an ``UnacceptedResponseEncodingRejection(encoding)``.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-cookie-java-:
cookie
======
Description
-----------
Extracts a cookie with a given name from a request or otherwise rejects the request with a ``MissingCookieRejection`` if
the cookie is missing.
Use the :ref:`-optionalCookie-java-` directive instead if you want to support missing cookies in your inner route.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,14 @@
.. _-deleteCookie-java-:
deleteCookie
============
Description
-----------
Adds a header to the response to request the removal of the cookie with the given name on the client.
Use the :ref:`-setCookie-java-` directive to update a cookie.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,12 @@
.. _CookieDirectives-java:
CookieDirectives
================
.. toctree::
:maxdepth: 1
cookie
deleteCookie
optionalCookie
setCookie

View file

@ -0,0 +1,15 @@
.. _-optionalCookie-java-:
optionalCookie
==============
Description
-----------
Extracts an optional cookie with a given name from a request.
Use the :ref:`-cookie-java-` directive instead if the inner route does not handle a missing cookie.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,15 @@
.. _-setCookie-java-:
setCookie
=========
Description
-----------
Adds a header to the response to request the update of the cookie with the given name on the client.
Use the :ref:`-deleteCookie-java-` directive to delete a cookie.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,35 @@
.. _Custom Directives-java:
Custom Directives
=================
Part of the power of akka-http directives comes from the ease with which its possible to define
custom directives at differing levels of abstraction.
There are essentially three ways of creating custom directives:
1. By introducing new “labels” for configurations of existing directives
2. By transforming existing directives
3. By writing a directive “from scratch”
Configuration Labeling
______________________
The easiest way to create a custom directive is to simply assign a new name for a certain configuration
of one or more existing directives. In fact, most of the predefined akka-http directives can be considered
named configurations of more low-level directives.
The basic technique is explained in the chapter about Composing Directives, where, for example, a new directive
``getOrPut`` is defined like this:
.. includecode2:: ../../../code/docs/http/javadsl/server/directives/CustomDirectivesExamplesTest.java
:snippet: labeling
Multiple directives can be nested to produce a single directive out of multiple like this:
.. includecode2:: ../../../code/docs/http/javadsl/server/directives/CustomDirectivesExamplesTest.java
:snippet: composition
Another example is the :ref:`MethodDirectives-java` which are simply instances of a preconfigured :ref:`-method-java-` directive.
The low-level directives that most often form the basis of higher-level “named configuration” directives are grouped
together in the :ref:`BasicDirectives-java` trait.

View file

@ -0,0 +1,11 @@
.. _DebuggingDirectives-java:
DebuggingDirectives
===================
.. toctree::
:maxdepth: 1
logRequest
logRequestResult
logResult

View file

@ -0,0 +1,19 @@
.. _-logRequest-java-:
logRequest
==========
Description
-----------
Logs the request. The directive is available with the following parameters:
* A marker to prefix each log message with.
* A log level.
* A function that creates a :class:``LogEntry`` from the :class:``HttpRequest``
Use ``logResult`` for logging the response, or ``logRequestResult`` for logging both.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-logRequestResult-java-:
logRequestResult
================
Description
-----------
Logs both, the request and the response.
This directive is a combination of :ref:`-logRequest-java-` and :ref:`-logResult-java-`.
See :ref:`-logRequest-java-` for the general description how these directives 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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-logResult-java-:
logResult
=========
Description
-----------
Logs the response.
See :ref:`-logRequest-java-` for the general description how these directives work.
Use ``logRequest`` for logging the request, or ``logRequestResult`` for logging both.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-handleExceptions-java-:
handleExceptions
================
Description
-----------
Catches exceptions thrown by the inner route and handles them using the specified ``ExceptionHandler``.
Using this directive is an alternative to using a global implicitly defined ``ExceptionHandler`` that
applies to the complete route.
See :ref:`exception-handling-java` for general information about options for handling exceptions.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,16 @@
.. _-handleRejections-java-:
handleRejections
================
Description
-----------
Using this directive is an alternative to using a global implicitly defined ``RejectionHandler`` that
applies to the complete route.
See :ref:`rejections-java` for general information about options for handling 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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,10 @@
.. _ExecutionDirectives-java:
ExecutionDirectives
===================
.. toctree::
:maxdepth: 1
handleExceptions
handleRejections

View file

@ -0,0 +1,22 @@
.. _-getFromBrowseableDirectories-java-:
getFromBrowseableDirectories
============================
Description
-----------
The ``getFromBrowseableDirectories`` is a combination of serving files from the specified directories
(like ``getFromDirectory``) and listing a browseable directory with ``listDirectoryContents``.
Nesting this directive beneath ``get`` is not necessary as this directive will only respond to ``GET`` requests.
Use ``getFromBrowseableDirectory`` to serve only one directory.
Use ``getFromDirectory`` if directory browsing isn't required.
For more details refer to :ref:`-getFromBrowseableDirectory-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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,43 @@
.. _-getFromBrowseableDirectory-java-:
getFromBrowseableDirectory
==========================
Description
-----------
The ``getFromBrowseableDirectories`` is a combination of serving files from the specified directories (like
``getFromDirectory``) and listing a browseable directory with ``listDirectoryContents``.
Nesting this directive beneath ``get`` is not necessary as this directive will only respond to ``GET`` requests.
Use ``getFromBrowseableDirectory`` to serve only one directory.
Use ``getFromDirectory`` if directory browsing isn't required.
For more details refer to :ref:`-getFromBrowseableDirectory-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 <https://github.com/akka/akka/issues/20466>`_.
Default file listing page example
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Directives which list directories (e.g. ``getFromBrowsableDirectory``) use an implicit ``DirectoryRenderer``
instance to perfm the actual rendering of the file listing. This rendered can be easily overriden by simply
providing one in-scope for the directives to use, so you can build your custom directory listings.
The default renderer is ``akka.http.scaladsl.server.directives.FileAndResourceDirectives.defaultDirectoryRenderer``,
and renders a listing which looks like this:
.. figure:: ../../../../../images/akka-http-file-listing.png
:scale: 75%
:align: center
Example page rendered by the ``defaultDirectoryRenderer``.
It's possible to turn off rendering the footer stating which version of Akka HTTP is rendering this page by configuring
the ``akka.http.routing.render-vanity-footer`` configuration option to ``off``.

View file

@ -0,0 +1,30 @@
.. _-getFromDirectory-java-:
getFromDirectory
================
Description
-----------
Allows exposing a directory's files for GET requests for its contents.
The ``unmatchedPath`` (see :ref:`-extractUnmatchedPath-java-`) of the ``RequestContext`` is first transformed by
the given ``pathRewriter`` function, before being appended to the given directory name to build the final file name.
To serve a single file use :ref:`-getFromFile-java-`.
To serve browsable directory listings use :ref:`-getFromBrowseableDirectories-java-`.
To serve files from a classpath directory use :ref:`-getFromResourceDirectory-java-` instead.
Note that it's not required to wrap this directive with ``get`` as this directive will only respond to ``GET`` requests.
.. note::
The file's contents will be read using an Akka Streams `Source` which *automatically uses
a pre-configured dedicated blocking io dispatcher*, which separates the blocking file operations from the rest of the stream.
Note also that thanks to using Akka Streams internally, the file will be served at the highest speed reachable by
the client, and not faster i.e. the file will *not* end up being loaded in full into memory before writing it to
the client.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,30 @@
.. _-getFromFile-java-:
getFromFile
===========
Description
-----------
Allows exposing a file to be streamed to the client issuing the request.
The ``unmatchedPath`` (see :ref:`-extractUnmatchedPath-java-`) of the ``RequestContext`` is first transformed by
the given ``pathRewriter`` function, before being appended to the given directory name to build the final file name.
To files from a given directory use :ref:`-getFromDirectory-java-`.
To serve browsable directory listings use :ref:`-getFromBrowseableDirectories-java-`.
To serve files from a classpath directory use :ref:`-getFromResourceDirectory-java-` instead.
Note that it's not required to wrap this directive with ``get`` as this directive will only respond to ``GET`` requests.
.. note::
The file's contents will be read using an Akka Streams `Source` which *automatically uses
a pre-configured dedicated blocking io dispatcher*, which separates the blocking file operations from the rest of the stream.
Note also that thanks to using Akka Streams internally, the file will be served at the highest speed reachable by
the client, and not faster i.e. the file will *not* end up being loaded in full into memory before writing it to
the client.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,18 @@
.. _-getFromResource-java-:
getFromResource
===============
Description
-----------
Completes ``GET`` requests with the content of the given classpath resource.
For details refer to :ref:`-getFromFile-java-` which works the same way but obtaining the file from the filesystem
instead of the applications classpath.
Note that it's not required to wrap this directive with ``get`` as this directive will only respond to ``GET`` requests.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,18 @@
.. _-getFromResourceDirectory-java-:
getFromResourceDirectory
========================
Description
-----------
Completes ``GET`` requests with the content of the given classpath resource directory.
For details refer to :ref:`-getFromDirectory-java-` which works the same way but obtaining the file from the filesystem
instead of the applications classpath.
Note that it's not required to wrap this directive with ``get`` as this directive will only respond to ``GET`` requests.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,24 @@
.. _FileAndResourceDirectives-java:
FileAndResourceDirectives
=========================
Like the :ref:`RouteDirectives-java` the ``FileAndResourceDirectives`` are somewhat special in akka-http's routing DSL.
Contrary to all other directives they do not produce instances of type ``Directive[L <: HList]`` but rather "plain"
routes of type ``Route``.
The reason is that they are not meant for wrapping an inner route (like most other directives, as intermediate-level
elements of a route structure, do) but rather form the actual route structure **leaves**.
So in most cases the inner-most element of a route structure branch is one of the :ref:`RouteDirectives-java` or
``FileAndResourceDirectives``.
.. toctree::
:maxdepth: 1
getFromBrowseableDirectories
getFromBrowseableDirectory
getFromDirectory
getFromFile
getFromResource
getFromResourceDirectory
listDirectoryContents

View file

@ -0,0 +1,23 @@
.. _-listDirectoryContents-java-:
listDirectoryContents
=====================
Description
-----------
Completes GET requests with a unified listing of the contents of all given directories. The actual rendering of the
directory contents is performed by the in-scope ``Marshaller[DirectoryListing]``.
To just serve files use :ref:`-getFromDirectory-java-`.
To serve files and provide a browseable directory listing use :ref:`-getFromBrowseableDirectories-java-` instead.
The rendering can be overridden by providing a custom ``Marshaller[DirectoryListing]``, you can read more about it in
:ref:`-getFromDirectory-java-` 's documentation.
Note that it's not required to wrap this directive with ``get`` as this directive will only respond to ``GET`` requests.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,21 @@
.. _-fileUpload-java-:
fileUpload
==========
Description
-----------
Simple access to the stream of bytes for a file uploaded as a multipart form together with metadata
about the upload as extracted value.
If there is no field with the given name the request will be rejected, if there are multiple file parts
with the same name, the first one will be used and the subsequent ones ignored.
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 <https://github.com/akka/akka/issues/20466>`_.
::
curl --form "csv=@uploadFile.txt" http://<host>:<port>

View file

@ -0,0 +1,10 @@
.. _FileUploadDirectives-java:
FileUploadDirectives
====================
.. toctree::
:maxdepth: 1
uploadedFile
fileUpload

View file

@ -0,0 +1,23 @@
.. _-uploadedFile-java-:
uploadedFile
============
Description
-----------
Streams the contents of a file uploaded as a multipart form into a temporary file on disk and provides the file and
metadata about the upload as extracted value.
If there is an error writing to disk the request will be failed with the thrown exception, if there is no field
with the given name the request will be rejected, if there are multiple file parts with the same name, the first
one will be used and the subsequent ones ignored.
.. note::
This directive will stream contents of the request into a file, however one can not start processing these
until the file has been written completely. For streaming APIs it is preferred to use the :ref:`-fileUpload-java-`
directive, as it allows for streaming handling of the incoming data bytes.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,11 @@
.. _-formField-java-:
formField
=========
-----------
Allows extracting a single Form field sent in the request.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,20 @@
.. _-formFieldList-java-:
formFieldList
=============
Description
-----------
Extracts all HTTP form fields at once in the original order as (name, value) tuples of type ``Map.Entry<String, String>``.
This directive can be used if the exact order of form fields is important or if parameters can occur several times.
Warning
-------
The directive reads all incoming HTT form fields without any configured upper bound.
It means, that requests with form fields holding significant amount of data (ie. during a file upload)
can cause performance issues or even an ``OutOfMemoryError`` 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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,19 @@
.. _-formFieldMap-java-:
formFieldMap
============
Description
-----------
Extracts all HTTP form fields at once as a ``Map<String, String>`` mapping form field names to form field values.
If form data contain a field value several times, the map will contain the last one.
Warning
-------
Use of this directive can result in performance degradation or even in ``OutOfMemoryError`` s.
See :ref:`-formFieldList-java-` for details.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,22 @@
.. _-formFieldMultiMap-java-:
formFieldMultiMap
=================
Description
-----------
Extracts all HTTP form fields at once as a multi-map of type ``Map<String, <List<String>>`` mapping
a form name to a list of all its values.
This directive can be used if form fields can occur several times.
The order of values is *not* specified.
Warning
-------
Use of this directive can result in performance degradation or even in ``OutOfMemoryError`` 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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,12 @@
.. _FormFieldDirectives-java:
FormFieldDirectives
===================
.. toctree::
:maxdepth: 1
formField
formFieldList
formFieldMap
formFieldMultiMap

View file

@ -0,0 +1,18 @@
.. _-completeOrRecoverWith-java-:
completeOrRecoverWith
=====================
Description
-----------
"Unwraps" a ``CompletionStage<T>`` and runs the inner route when the stage has failed
with the stage's failure exception as an extraction of type ``Throwable``.
If the completion stage succeeds the request is completed using the values marshaller
(This directive therefore requires a marshaller for the completion stage value type to be
provided.)
To handle the successful case manually as well, use the :ref:`-onComplete-java-` directive, instead.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,14 @@
.. _FutureDirectives-java:
FuturesDirectives
=================
Future directives can be used to run inner routes once the provided ``Future[T]`` has been completed.
.. toctree::
:maxdepth: 1
onComplete
onSuccess
completeOrRecoverWith

View file

@ -0,0 +1,18 @@
.. _-onComplete-java-:
onComplete
==========
Description
-----------
Evaluates its parameter of type ``CompletionStage<T>``, and once it has been completed, extracts its
result as a value of type ``Try<T>`` and passes it to the inner route. A ``Try<T>`` can either be a ``Success`` containing
the ``T`` value or a ``Failure`` containing the ``Throwable``.
To handle the ``Failure`` case automatically and only work with the result value, use :ref:`-onSuccess-java-`.
To complete with a successful result automatically and just handle the failure result, use :ref:`-completeOrRecoverWith-java-`, instead.
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 <https://github.com/akka/akka/issues/20466>`_.

View file

@ -0,0 +1,17 @@
.. _-onSuccess-java-:
onSuccess
=========
Description
-----------
Evaluates its parameter of type ``CompletionStage<T>``, and once it has been completed successfully,
extracts its result as a value of type ``T`` and passes it to the inner route.
If the future fails its failure throwable is bubbled up to the nearest ``ExceptionHandler``.
To handle the ``Failure`` case manually as well, use :ref:`-onComplete-java-`, instead.
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 <https://github.com/akka/akka/issues/20466>`_.

Some files were not shown because too many files have changed in this diff Show more