/httpquickstart/src/main/java/csc375/httpquickstart/QuickstartServer.java

https://bitbucket.org/jdblake/csc375-18sp · Java · 66 lines · 38 code · 13 blank · 15 comment · 0 complexity · 495dbd362a3c5c4d875c252941ddec05 MD5 · raw file

  1. package csc375.httpquickstart;
  2. import akka.NotUsed;
  3. import akka.actor.ActorRef;
  4. import akka.actor.ActorSystem;
  5. import akka.http.javadsl.ConnectHttp;
  6. import akka.http.javadsl.Http;
  7. import akka.http.javadsl.ServerBinding;
  8. import akka.http.javadsl.model.HttpRequest;
  9. import akka.http.javadsl.model.HttpResponse;
  10. import akka.http.javadsl.server.AllDirectives;
  11. import akka.http.javadsl.server.Route;
  12. import akka.stream.ActorMaterializer;
  13. import akka.stream.javadsl.Flow;
  14. import java.util.concurrent.CompletionStage;
  15. // #main-class
  16. public class QuickstartServer extends AllDirectives {
  17. // set up ActorSystem and other dependencies here
  18. private final UserRoutes userRoutes;
  19. public QuickstartServer(ActorSystem system, ActorRef userRegistryActor) {
  20. userRoutes = new UserRoutes(system, userRegistryActor);
  21. }
  22. //#main-class
  23. public static void main(String[] args) throws Exception {
  24. //#server-bootstrapping
  25. // boot up server using the route as defined below
  26. ActorSystem system = ActorSystem.create("helloAkkaHttpServer");
  27. final Http http = Http.get(system);
  28. final ActorMaterializer materializer = ActorMaterializer.create(system);
  29. //#server-bootstrapping
  30. ActorRef userRegistryActor = system.actorOf(UserRegistryActor.props(), "userRegistryActor");
  31. //#http-server
  32. //In order to access all directives we need an instance where the routes are define.
  33. QuickstartServer app = new QuickstartServer(system, userRegistryActor);
  34. final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = app.createRoute().flow(system, materializer);
  35. final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow,
  36. ConnectHttp.toHost("localhost", 8080), materializer);
  37. System.out.println("Server online at http://localhost:8080/\nPress RETURN to stop...");
  38. System.in.read(); // let it run until user presses return
  39. binding
  40. .thenCompose(ServerBinding::unbind) // trigger unbinding from the port
  41. .thenAccept(unbound -> system.terminate()); // and shutdown when done
  42. //#http-server
  43. }
  44. //#main-class
  45. /**
  46. * Here you can define all the different routes you want to have served by this web server
  47. * Note that routes might be defined in separated classes like the current case
  48. */
  49. protected Route createRoute() {
  50. return userRoutes.routes();
  51. }
  52. }
  53. //#main-class