Merge pull request #17990 from spray/w/java-side-documentation

A few last minute Java-side changes + documentation
This commit is contained in:
Konrad Malawski 2015-07-14 19:38:43 +02:00
commit 75229b0711
24 changed files with 829 additions and 98 deletions

View file

@ -63,8 +63,8 @@ public class HandlerExampleSpec extends JUnitRouteTest {
RequestVal<Integer> xParam = Parameters.intValue("x");
RequestVal<Integer> yParam = Parameters.intValue("y");
RequestVal<Integer> xSegment = PathMatchers.integerNumber();
RequestVal<Integer> ySegment = PathMatchers.integerNumber();
RequestVal<Integer> xSegment = PathMatchers.intValue();
RequestVal<Integer> ySegment = PathMatchers.intValue();
//#handler2
Handler2<Integer, Integer> multiply =
@ -114,8 +114,8 @@ public class HandlerExampleSpec extends JUnitRouteTest {
RequestVal<Integer> xParam = Parameters.intValue("x");
RequestVal<Integer> yParam = Parameters.intValue("y");
RequestVal<Integer> xSegment = PathMatchers.integerNumber();
RequestVal<Integer> ySegment = PathMatchers.integerNumber();
RequestVal<Integer> xSegment = PathMatchers.intValue();
RequestVal<Integer> ySegment = PathMatchers.intValue();
//#reflective

View file

@ -0,0 +1,90 @@
/*
* Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.http.javadsl;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.server.*;
import akka.http.javadsl.server.values.Parameters;
import akka.http.javadsl.server.values.PathMatcher;
import akka.http.javadsl.server.values.PathMatchers;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRoute;
import org.junit.Test;
public class PathDirectiveExampleTest extends JUnitRouteTest {
@Test
public void testPathPrefix() {
//#path-examples
// matches "/test"
path("test").route(
completeWithStatus(StatusCodes.OK)
);
// matches "/test", as well
path(PathMatchers.segment("test")).route(
completeWithStatus(StatusCodes.OK)
);
// matches "/admin/user"
path("admin", "user").route(
completeWithStatus(StatusCodes.OK)
);
// matches "/admin/user", as well
pathPrefix("admin").route(
path("user").route(
completeWithStatus(StatusCodes.OK)
)
);
// matches "/admin/user/<user-id>"
Handler1<Integer> completeWithUserId =
new Handler1<Integer>() {
@Override
public RouteResult handle(RequestContext ctx, Integer userId) {
return 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>", as well
path("admin", "user", userId).route(
handleWith1(userId, completeWithUserId)
);
// never matches
path("admin").route( // oops this only matches "/admin"
path("user").route(
completeWithStatus(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
}
// FIXME: remove once #17988 is merged
public static <T> Route handleWith1(RequestVal<T> val, Object o) {
return null;
}
}

View file

@ -3,13 +3,39 @@
Akka HTTP
=========
The Akka HTTP modules implement a full server- and client-side HTTP stack on top of *akka-actor* and *akka-stream*. It's
not a web-framework but rather a more general toolkit for providing and consuming HTTP-based services. While interaction
with a browser is of course also in scope it is not the primary focus of Akka HTTP.
Akka HTTP follows a rather open design and many times offers several different API levels for "doing the same thing".
You get to pick the API level of abstraction that is most suitable for your application.
This means that, if you have trouble achieving something using a high-level API, there's a good chance that you can get
it done with a low-level API, which offers more flexibility but might require you to write more application code.
Akka HTTP is structured into several modules:
akka-http-core
A complete, mostly low-level, server- and client-side implementation of HTTP (incl. WebSockets).
Includes a model of all things HTTP.
akka-http
Higher-level functionality, like (un)marshalling, (de)compression as well as a powerful DSL
for defining HTTP-based APIs on the server-side
akka-http-testkit
A test harness and set of utilities for verifying server-side service implementations
akka-http-jackson
Predefined glue-code for (de)serializing custom types from/to JSON with jackson_
.. toctree::
:maxdepth: 2
introduction
configuration
http-model
server-side/low-level-server-side-api
server-side/websocket-support
routing-dsl/index
client-side/index
client-side/index
.. _jackson: https://github.com/FasterXML/jackson

View file

@ -1,28 +0,0 @@
Introduction
============
The Akka HTTP modules implement a full server- and client-side HTTP stack on top of *akka-actor* and *akka-stream*. It's
not a web-framework but rather a more general toolkit for providing and consuming HTTP-based services. While interaction
with a browser is of course also in scope it is not the primary focus of Akka HTTP.
Akka HTTP follows a rather open design and many times offers several different API levels for "doing the same thing".
You get to pick the API level of abstraction that is most suitable for your application.
This means that, if you have trouble achieving something using a high-level API, there's a good chance that you can get
it done with a low-level API, which offers more flexibility but might require you to write more application code.
Akka HTTP is structured into several modules:
akka-http-core
A complete, mostly low-level, server- and client-side implementation of HTTP (incl. WebSockets)
akka-http
Higher-level functionality, like (un)marshalling, (de)compression as well as a powerful DSL
for defining HTTP-based APIs on the server-side
akka-http-testkit
A test harness and set of utilities for verifying server-side service implementations
akka-http-jackson
Predefined glue-code for (de)serializing custom types from/to JSON with jackson_
.. _jackson: https://github.com/FasterXML/jackson

View file

@ -3,4 +3,64 @@
Directives
==========
TODO
A directive is a wrapper for a route or a list of alternative routes that adds one or more of the following
functionality to its nested route(s):
* it filters the request and lets only matching requests pass (e.g. the `get` directive lets only GET-requests pass)
* it modifies the request or the ``RequestContext`` (e.g. the `path` directives filters on the unmatched path and then
passes an updated ``RequestContext`` unmatched path)
* it modifies the response coming out of the nested route
akka-http provides a set of predefined directives for various tasks. You can access them by either extending from
``akka.http.javadsl.server.AllDirectives`` or by importing them statically with
``import static akka.http.javadsl.server.Directives.*;``.
These classes of directives are currently defined:
BasicDirectives
Contains methods to create routes that complete with a static values or allow specifying :ref:`handlers-java` to
process a request.
CacheConditionDirectives
Contains a single directive ``conditional`` that wraps its inner route with support for Conditional Requests as defined
by `RFC 7234`_.
CodingDirectives
Contains directives to decode compressed requests and encode responses.
CookieDirectives
Contains a single directive ``setCookie`` to aid adding a cookie to a response.
ExecutionDirectives
Contains directives to deal with exceptions that occurred during routing.
FileAndResourceDirectives
Contains directives to serve resources from files on the file system or from the classpath.
HostDirectives
Contains directives to filter on the ``Host`` header of the incoming request.
MethodDirectives
Contains directives to filter on the HTTP method of the incoming request.
MiscDirectives
Contains directives that validate a request by user-defined logic.
:ref:`PathDirectives-java`
Contains directives to match and filter on the URI path of the incoming request.
RangeDirectives
Contains a single directive ``withRangeSupport`` that adds support for retrieving partial responses.
SchemeDirectives
Contains a single directive ``scheme`` to filter requests based on the URI scheme (http vs. https).
WebsocketDirectives
Contains directives to support answering Websocket requests.
.. toctree::
:maxdepth: 1
path-directives
.. _`RFC 7234`: http://tools.ietf.org/html/rfc7234

View file

@ -0,0 +1,95 @@
.. _PathDirectives-java:
PathDirectives
==============
Path directives are the most basic building blocks for routing requests depending on the URI path.
When a request (or rather the respective ``RequestContext`` instance) enters the route structure it has an
"unmatched path" that is identical to the ``request.uri.path``. As it descends the routing tree and passes through one
or more ``pathPrefix`` or ``path`` directives the "unmatched path" progressively gets "eaten into" from the
left until, in most cases, it eventually has been consumed completely.
The two main directives are ``path`` and ``pathPrefix``. The ``path`` directive tries to match the complete remaining
unmatched path against the specified "path matchers", the ``pathPrefix`` directive only matches a prefix and passes the
remaining unmatched path to nested directives. Both directives automatically match a slash from the beginning, so
that matching slashes in a hierarchy of nested ``pathPrefix`` and ``path`` directives is usually not needed.
Path directives take a variable amount of arguments. Each argument must be a ``PathMatcher`` or a string (which is
automatically converted to a path matcher using ``PathMatchers.segment``). In the case of ``path`` and ``pathPrefix``,
if multiple arguments are supplied, a slash is assumed between any of the supplied path matchers. The ``rawPathX``
variants of those directives on the other side do no such preprocessing, so that slashes must be matched manually.
Path Matchers
-------------
A path matcher is a description of a part of a path to match. The simplest path matcher is ``PathMatcher.segment`` which
matches exactly one path segment against the supplied constant string.
Other path matchers defined in ``PathMatchers`` match the end of the path (``PathMatchers.END``), a single slash
(``PathMatchers.SLASH``), or nothing at all (``PathMatchers.NEUTRAL``).
Many path matchers are hybrids that can both match (by using them with one of the PathDirectives) and extract values,
i.e. they are :ref:`request-vals-java`. Extracting a path matcher value (i.e. using it with ``handleWithX``) is only
allowed if it nested inside a path directive that uses that path matcher and so specifies at which position the value
should be extracted from the path.
Predefined path matchers allow extraction of various types of values:
``PathMatchers.segment(String)``
Strings simply match themselves and extract no value.
Note that strings are interpreted as the decoded representation of the path, so if they include a '/' character
this character will match "%2F" in the encoded raw URI!
``PathMatchers.regex``
You can use a regular expression instance as a path matcher, which matches whatever the regex matches and extracts
one ``String`` value. A ``PathMatcher`` created from a regular expression extracts either the complete match (if the
regex doesn't contain a capture group) or the capture group (if the regex contains exactly one capture group).
If the regex contains more than one capture group an ``IllegalArgumentException`` will be thrown.
``PathMatchers.SLASH``
Matches exactly one path-separating slash (``/``) character.
``PathMatchers.END``
Matches the very end of the path, similar to ``$`` in regular expressions.
``PathMatchers.Segment``
Matches if the unmatched path starts with a path segment (i.e. not a slash).
If so the path segment is extracted as a ``String`` instance.
``PathMatchers.Rest``
Matches and extracts the complete remaining unmatched part of the request's URI path as an (encoded!) String.
If you need access to the remaining *decoded* elements of the path use ``RestPath`` instead.
``PathMatchers.intValue``
Efficiently matches a number of decimal digits (unsigned) and extracts their (non-negative) ``Int`` value. The matcher
will not match zero digits or a sequence of digits that would represent an ``Int`` value larger than ``Integer.MAX_VALUE``.
``PathMatchers.longValue``
Efficiently matches a number of decimal digits (unsigned) and extracts their (non-negative) ``Long`` value. The matcher
will not match zero digits or a sequence of digits that would represent an ``Long`` value larger than ``Long.MAX_VALUE``.
``PathMatchers.hexIntValue``
Efficiently matches a number of hex digits and extracts their (non-negative) ``Int`` value. The matcher will not match
zero digits or a sequence of digits that would represent an ``Int`` value larger than ``Integer.MAX_VALUE``.
``PathMatchers.hexLongValue``
Efficiently matches a number of hex digits and extracts their (non-negative) ``Long`` value. The matcher will not
match zero digits or a sequence of digits that would represent an ``Long`` value larger than ``Long.MAX_VALUE``.
``PathMatchers.uuid``
Matches and extracts a ``java.util.UUID`` instance.
``PathMatchers.NEUTRAL``
A matcher that always matches, doesn't consume anything and extracts nothing.
Serves mainly as a neutral element in ``PathMatcher`` composition.
``PathMatchers.segments``
Matches all remaining segments as a list of strings. Note that this can also be "no segments" resulting in the empty
list. If the path has a trailing slash this slash will *not* be matched, i.e. remain unmatched and to be consumed by
potentially nested directives.
Here's a collection of path matching examples:
.. includecode:: ../../../code/docs/http/javadsl/PathDirectiveExampleTest.java
:include: path-examples

View file

@ -59,7 +59,7 @@ route structure, this time representing segments from the URI path.
Handlers in Java 8
------------------
In Java 8 handlers can be provided as function literals. The example from before then looks like this:
In Java 8 handlers can be provided as function literals. The previous example can then be written like this:
.. includecode:: /../../akka-http-tests-java8/src/test/java/docs/http/javadsl/server/HandlerExampleSpec.java
:include: handler2-example-full

View file

@ -3,7 +3,7 @@
High-level Server-Side API
==========================
...
To use the high-level API you need to add a dependency to the ``akka-http-experimental`` module.
.. toctree::
:maxdepth: 1
@ -13,5 +13,5 @@ High-level Server-Side API
directives/index
request-vals/index
handlers
path-matchers
marshalling
json-jackson-support

View file

@ -0,0 +1,19 @@
.. _json-jackson-support-java:
Json Support via Jackson
========================
akka-http provides support to convert application-domain objects from and to JSON using 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.
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.
.. _jackson: https://github.com/FasterXML/jackson
__ @github@/akka-http-tests/src/main/java/akka/http/javadsl/server/examples/petstore/PetStoreExample.java

View file

@ -3,4 +3,41 @@
Marshalling & Unmarshalling
===========================
TODO
"Marshalling" is the process of converting a higher-level (object) structure into some kind of lower-level
representation (and vice versa), often a binary 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 an HttpEntity, which forms the entity body
of an HTTP request or response (depending on whether used on the client or server side).
Marshalling
-----------
On the server-side marshalling is used to convert a application-domain object to a response (entity). Requests can
contain an ``Accept`` header that lists acceptable content types for the client. A marshaller contains the logic to
negotiate the result content types based on the ``Accept`` and the ``AcceptCharset`` headers.
Marshallers can be specified when completing a request with ``RequestContext.completeAs`` or by using the ``BasicDirectives.completeAs``
directives.
These marshallers are provided by akka-http:
* Use :ref:`json-jackson-support-java` to create an marshaller that can convert a POJO to an ``application/json``
response using jackson_.
* Use ``Marshallers.toEntityString``, ``Marshallers.toEntityBytes``, ``Marshallers.toEntityByteString``,
``Marshallers.toEntity``, and ``Marshallers.toResponse`` to create custom marshallers.
Unmarshalling
-------------
On the server-side unmarshalling is used to convert a request (entity) to a application-domain object. This means
unmarshalling to a certain type is represented by a ``RequestVal``. Currently, several options are provided to create
an unmarshalling ``RequestVal``:
* Use :ref:`json-jackson-support-java` to create an unmarshaller that can convert an ``application/json`` request
to a POJO using jackson_.
* Use the predefined ``Unmarshallers.String``, ``Unmarshallers.ByteString``, ``Unmarshallers.ByteArray``,
``Unmarshallers.CharArray`` to convert to those basic types.
* Use ``Unmarshallers.fromMessage`` or ``Unmarshaller.fromEntity`` to create a custom unmarshaller.
.. _jackson: https://github.com/FasterXML/jackson

View file

@ -1,6 +0,0 @@
.. _pathmatcher-dsl-java:
The PathMatcher DSL
===================
TODO

View file

@ -27,11 +27,19 @@ service.
These request values are defined:
* in ``RequestVals``: request values for basic data like URI components, request method, peer address, or the entity data
* in ``Cookies``: request values representing cookies
* in ``FormFields``: request values to access form fields unmarshalled to various primitive Java types
* in ``Headers``:: request values to access request headers or header values
* ``HttpBasicAuthenticator``: an abstract class to implement to create a request value representing a HTTP basic authenticated principal
* in ``Parameters``: request values to access URI paramaters unmarshalled to various primitive Java types
* in ``PathMatchers``: request values to match and access URI path segments
* ``CustomRequestVal``: an abstract class to implement arbitrary custom request values
RequestVals
Contains request values for basic data like URI components, request method, peer address, or the entity data.
Cookies
Contains request values representing cookies.
FormFields
Contains request values to access form fields unmarshalled to various primitive Java types.
Headers
Contains request values to access request headers or header values.
HttpBasicAuthenticator
An abstract class to implement to create a request value representing a HTTP basic authenticated principal.
Parameters
Contains request values to access URI paramaters unmarshalled to various primitive Java types.
PathMatchers
Contains request values to match and access URI path segments.
CustomRequestVal
An abstract class to implement arbitrary custom request values.