/highlevelserverexample/src/main/java/csc375/highlevelserverexample/HighLevelServerExample.java

https://bitbucket.org/jdblake/csc375-18sp · Java · 68 lines · 50 code · 10 blank · 8 comment · 0 complexity · 214ac7377efceb7aab5b04c46048584c MD5 · raw file

  1. package csc375.highlevelserverexample;
  2. import akka.NotUsed;
  3. import akka.actor.ActorSystem;
  4. import akka.http.javadsl.ConnectHttp;
  5. import akka.http.javadsl.Http;
  6. import akka.http.javadsl.ServerBinding;
  7. import akka.http.javadsl.model.ContentTypes;
  8. import akka.http.javadsl.model.HttpEntities;
  9. import akka.http.javadsl.model.HttpRequest;
  10. import akka.http.javadsl.model.HttpResponse;
  11. import akka.http.javadsl.server.AllDirectives;
  12. import akka.http.javadsl.server.Route;
  13. import akka.stream.ActorMaterializer;
  14. import akka.stream.javadsl.Flow;
  15. import java.io.IOException;
  16. import java.util.concurrent.CompletionStage;
  17. public class HighLevelServerExample extends AllDirectives {
  18. public static void main(String[] args) throws IOException {
  19. // boot up server using the route as defined below
  20. ActorSystem system = ActorSystem.create();
  21. final HighLevelServerExample app = new HighLevelServerExample();
  22. final Http http = Http.get(system);
  23. final ActorMaterializer materializer = ActorMaterializer.create(system);
  24. final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = app.createRoute().flow(system, materializer);
  25. final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow, ConnectHttp.toHost("localhost", 8080), materializer);
  26. System.out.println("Type RETURN to exit");
  27. System.in.read();
  28. binding
  29. .thenCompose(ServerBinding::unbind)
  30. .thenAccept(unbound -> system.terminate());
  31. }
  32. public Route createRoute() {
  33. // This handler generates responses to `/hello?name=XXX` requests
  34. Route helloRoute =
  35. parameterOptional("name", optName -> {
  36. String name = optName.orElse("Mister X");
  37. return complete("Hello " + name + "!");
  38. });
  39. return
  40. // here the complete behavior for this server is defined
  41. // only handle GET requests (short circuits!)
  42. get(() -> route(
  43. // matches the empty path
  44. pathSingleSlash(() ->
  45. // return a constant string with a certain content type
  46. complete(HttpEntities.create(ContentTypes.TEXT_HTML_UTF8, "<html><body>Hello world!</body></html>"))
  47. ),
  48. path("ping", () ->
  49. // return a simple `text/plain` response
  50. complete("PONG!")
  51. ),
  52. path("hello", () ->
  53. // uses the route defined above
  54. helloRoute
  55. )
  56. ));
  57. }
  58. }