2015-07-10 19:10:29 +02:00
|
|
|
/*
|
2016-02-23 12:58:39 +01:00
|
|
|
* Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
|
2015-07-10 19:10:29 +02:00
|
|
|
*/
|
|
|
|
|
|
2015-07-17 15:30:14 +02:00
|
|
|
package docs.http.javadsl.server;
|
2015-07-10 19:10:29 +02:00
|
|
|
|
|
|
|
|
//#high-level-server-example
|
|
|
|
|
import akka.actor.ActorSystem;
|
2015-09-29 20:58:47 +02:00
|
|
|
import akka.http.javadsl.model.ContentTypes;
|
2015-07-10 19:10:29 +02:00
|
|
|
import akka.http.javadsl.model.MediaTypes;
|
|
|
|
|
import akka.http.javadsl.server.*;
|
|
|
|
|
import akka.http.javadsl.server.values.Parameters;
|
|
|
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
|
|
|
|
|
// 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();
|
2016-01-17 15:48:52 +01:00
|
|
|
system.terminate();
|
2015-07-10 19:10:29 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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");
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
public Route createRoute() {
|
|
|
|
|
// This handler generates responses to `/hello?name=XXX` requests
|
|
|
|
|
Route helloRoute =
|
2015-07-13 16:46:07 +02:00
|
|
|
handleWith1(name,
|
2015-07-10 19:10:29 +02:00
|
|
|
// in Java 8 the following becomes simply
|
|
|
|
|
// (ctx, name) -> ctx.complete("Hello " + name + "!")
|
|
|
|
|
new Handler1<String>() {
|
|
|
|
|
@Override
|
2015-07-13 16:46:07 +02:00
|
|
|
public RouteResult apply(RequestContext ctx, String name) {
|
2015-07-10 19:10:29 +02:00
|
|
|
return ctx.complete("Hello " + name + "!");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
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
|
2015-12-01 23:07:56 +01:00
|
|
|
complete(ContentTypes.TEXT_HTML_UTF8,
|
2015-07-10 19:10:29 +02:00
|
|
|
"<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
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
//#high-level-server-example
|