/src/main/java/tkocsis/akka/example/HttpServerStreamRandomNumbersTest.java

https://gitlab.com/tkocsis/akka-tutorial · Java · 57 lines · 38 code · 11 blank · 8 comment · 0 complexity · 8af4740276cd1108ea5ee83f07dca3bc MD5 · raw file

  1. package tkocsis.akka.example;
  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.*;
  8. import akka.http.javadsl.server.AllDirectives;
  9. import akka.http.javadsl.server.Route;
  10. import akka.stream.ActorMaterializer;
  11. import akka.stream.javadsl.Flow;
  12. import akka.stream.javadsl.Source;
  13. import akka.util.ByteString;
  14. import java.util.Random;
  15. import java.util.concurrent.CompletionStage;
  16. import java.util.stream.Stream;
  17. public class HttpServerStreamRandomNumbersTest extends AllDirectives {
  18. public static void main(String[] args) throws Exception {
  19. // boot up server using the route as defined below
  20. ActorSystem system = ActorSystem.create("routes");
  21. final Http http = Http.get(system);
  22. final ActorMaterializer materializer = ActorMaterializer.create(system);
  23. // In order to access all directives we need an instance where the
  24. // routes are define.
  25. HttpServerStreamRandomNumbersTest app = new HttpServerStreamRandomNumbersTest();
  26. final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = app.createRoute().flow(system, materializer);
  27. final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow,
  28. ConnectHttp.toHost("localhost", 8080), materializer);
  29. System.out.println("Server online at http://localhost:8080/\nPress RETURN to stop...");
  30. System.in.read(); // let it run until user presses return
  31. binding.thenCompose(ServerBinding::unbind) // trigger unbinding from the
  32. // port
  33. .thenAccept(unbound -> system.terminate()); // and shutdown when
  34. // done
  35. }
  36. private Route createRoute() {
  37. final Random rnd = new Random();
  38. // streams are re-usable so we can define it here
  39. // and use it for every request
  40. Source<Integer, NotUsed> numbers = Source.fromIterator(() -> Stream.generate(rnd::nextInt).iterator());
  41. return route(path("random",
  42. () -> get(() -> complete(HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8,
  43. // transform each number to a chunk of bytes
  44. numbers.map(x -> ByteString.fromString(x + "\n")))))));
  45. }
  46. }