public void demonstrateAGraphStageWithATimer() throws Exception {
    // tests:
    CompletionStage<Integer> result =
        Source.from(Arrays.asList(1, 2, 3))
            .via(new TimedGate<>(Duration.create(2, "seconds")))
            .takeWithin(Duration.create(250, "millis"))
            .runFold(0, (n, sum) -> n + sum, mat);

    assertEquals(new Integer(1), result.toCompletableFuture().get(3, TimeUnit.SECONDS));
  }
  public void demonstrateACustomMaterializedValue() throws Exception {
    // tests:
    RunnableGraph<CompletionStage<Integer>> flow =
        Source.from(Arrays.asList(1, 2, 3))
            .viaMat(new FirstValue(), Keep.right())
            .to(Sink.ignore());

    CompletionStage<Integer> result = flow.run(mat);

    assertEquals(new Integer(1), result.toCompletableFuture().get(3, TimeUnit.SECONDS));
  }
  @Test
  public void demonstrateASimplerOneToManyStage() throws Exception {
    // tests:
    Graph<FlowShape<Integer, Integer>, NotUsed> duplicator =
        Flow.fromGraph(new Duplicator2<Integer>());

    CompletionStage<Integer> result =
        Source.from(Arrays.asList(1, 2, 3)).via(duplicator).runFold(0, (n, sum) -> n + sum, mat);

    assertEquals(new Integer(12), result.toCompletableFuture().get(3, TimeUnit.SECONDS));
  }
  @Test
  public void partialGraph() throws Exception {
    // #partial-graph
    final Graph<FlowShape<Integer, Integer>, NotUsed> partial =
        GraphDSL.create(
            builder -> {
              final UniformFanOutShape<Integer, Integer> B = builder.add(Broadcast.create(2));
              final UniformFanInShape<Integer, Integer> C = builder.add(Merge.create(2));
              final UniformFanOutShape<Integer, Integer> E = builder.add(Balance.create(2));
              final UniformFanInShape<Integer, Integer> F = builder.add(Merge.create(2));

              builder.from(F.out()).toInlet(C.in(0));
              builder.from(B).viaFanIn(C).toFanIn(F);
              builder
                  .from(B)
                  .via(builder.add(Flow.of(Integer.class).map(i -> i + 1)))
                  .viaFanOut(E)
                  .toFanIn(F);

              return new FlowShape<Integer, Integer>(B.in(), E.out(1));
            });

    // #partial-graph

    // #partial-use
    Source.single(0).via(partial).to(Sink.ignore());
    // #partial-use

    // #partial-flow-dsl
    // Convert the partial graph of FlowShape to a Flow to get
    // access to the fluid DSL (for example to be able to call .filter())
    final Flow<Integer, Integer, NotUsed> flow = Flow.fromGraph(partial);

    // Simple way to create a graph backed Source
    final Source<Integer, NotUsed> source =
        Source.fromGraph(
            GraphDSL.create(
                builder -> {
                  final UniformFanInShape<Integer, Integer> merge = builder.add(Merge.create(2));
                  builder.from(builder.add(Source.single(0))).toFanIn(merge);
                  builder.from(builder.add(Source.from(Arrays.asList(2, 3, 4)))).toFanIn(merge);
                  // Exposing exactly one output port
                  return new SourceShape<Integer>(merge.out());
                }));

    // Building a Sink with a nested Flow, using the fluid DSL
    final Sink<Integer, NotUsed> sink =
        Flow.of(Integer.class).map(i -> i * 2).drop(10).named("nestedFlow").to(Sink.head());

    // Putting all together
    final RunnableGraph<NotUsed> closed = source.via(flow.filter(i -> i > 1)).to(sink);
    // #partial-flow-dsl
  }
  @Test
  public void demonstrateAManyToOneElementGraphStage() throws Exception {

    // tests:
    Graph<FlowShape<Integer, Integer>, NotUsed> evenFilter =
        Flow.fromGraph(new Filter<Integer>(n -> n % 2 == 0));

    CompletionStage<Integer> result =
        Source.from(Arrays.asList(1, 2, 3, 4, 5, 6))
            .via(evenFilter)
            .runFold(0, (elem, sum) -> sum + elem, mat);

    assertEquals(new Integer(12), result.toCompletableFuture().get(3, TimeUnit.SECONDS));
  }
  @Test
  public void demonstrateChainingOfGraphStages() throws Exception {
    Graph<SinkShape<Integer>, CompletionStage<String>> sink =
        Sink.fold("", (acc, n) -> acc + n.toString());

    // #graph-stage-chain
    CompletionStage<String> resultFuture =
        Source.from(Arrays.asList(1, 2, 3, 4, 5))
            .via(new Filter<Integer>((n) -> n % 2 == 0))
            .via(new Duplicator<Integer>())
            .via(new Map<Integer, Integer>((n) -> n / 2))
            .runWith(sink, mat);

    // #graph-stage-chain

    assertEquals("1122", resultFuture.toCompletableFuture().get(3, TimeUnit.SECONDS));
  }
    public void run(final Materializer mat)
        throws TimeoutException, InterruptedException, ExecutionException {
      // #backpressure-by-readline
      final CompletionStage<Done> completion =
          Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
              .map(
                  i -> {
                    System.out.println("map => " + i);
                    return i;
                  })
              .runForeach(
                  i ->
                      System.console()
                          .readLine("Element = %s continue reading? [press enter]\n", i),
                  mat);

      completion.toCompletableFuture().get(1, TimeUnit.SECONDS);
      // #backpressure-by-readline
    }
  @Test
  public void demonstrateOneToOne() throws Exception {
    // tests:
    final Graph<FlowShape<String, Integer>, NotUsed> stringLength =
        Flow.fromGraph(
            new Map<String, Integer>(
                new Function<String, Integer>() {
                  @Override
                  public Integer apply(String str) {
                    return str.length();
                  }
                }));

    CompletionStage<Integer> result =
        Source.from(Arrays.asList("one", "two", "three"))
            .via(stringLength)
            .runFold(0, (sum, n) -> sum + n, mat);

    assertEquals(new Integer(11), result.toCompletableFuture().get(3, TimeUnit.SECONDS));
  }
  @Test
  public void demonstrateAnAsynchronousSideChannel() throws Exception {

    // tests:
    CompletableFuture<Done> switchF = new CompletableFuture<>();
    Graph<FlowShape<Integer, Integer>, NotUsed> killSwitch =
        Flow.fromGraph(new KillSwitch<>(switchF));

    ExecutionContext ec = system.dispatcher();

    CompletionStage<Integer> valueAfterKill = switchF.thenApply(in -> 4);

    CompletionStage<Integer> result =
        Source.from(Arrays.asList(1, 2, 3))
            .concat(Source.fromCompletionStage(valueAfterKill))
            .via(killSwitch)
            .runFold(0, (n, sum) -> n + sum, mat);

    switchF.complete(Done.getInstance());

    assertEquals(new Integer(6), result.toCompletableFuture().get(3, TimeUnit.SECONDS));
  }
  public void demonstrateADetachedGraphStage() throws Exception {
    // tests:
    CompletionStage<Integer> result1 =
        Source.from(Arrays.asList(1, 2, 3))
            .via(new TwoBuffer<>())
            .runFold(0, (acc, n) -> acc + n, mat);

    assertEquals(new Integer(6), result1.toCompletableFuture().get(3, TimeUnit.SECONDS));

    TestSubscriber.ManualProbe<Integer> subscriber = TestSubscriber.manualProbe(system);
    TestPublisher.Probe<Integer> publisher = TestPublisher.probe(0, system);
    RunnableGraph<NotUsed> flow2 =
        Source.fromPublisher(publisher).via(new TwoBuffer<>()).to(Sink.fromSubscriber(subscriber));

    flow2.run(mat);

    Subscription sub = subscriber.expectSubscription();
    // this happens even though the subscriber has not signalled any demand
    publisher.sendNext(1);
    publisher.sendNext(2);

    sub.cancel();
  }
Exemple #11
0
    public void requestExamples() {
      // #ws-holder
      WSRequest request = ws.url("http://example.com");
      // #ws-holder

      // #ws-complex-holder
      WSRequest complexRequest =
          request
              .setHeader("headerKey", "headerValue")
              .setRequestTimeout(1000)
              .setQueryParameter("paramKey", "paramValue");
      // #ws-complex-holder

      // #ws-get
      CompletionStage<WSResponse> responsePromise = complexRequest.get();
      // #ws-get

      String url = "http://example.com";
      // #ws-auth
      ws.url(url).setAuth("user", "password", WSAuthScheme.BASIC).get();
      // #ws-auth

      // #ws-follow-redirects
      ws.url(url).setFollowRedirects(true).get();
      // #ws-follow-redirects

      // #ws-query-parameter
      ws.url(url).setQueryParameter("paramKey", "paramValue");
      // #ws-query-parameter

      // #ws-header
      ws.url(url).setHeader("headerKey", "headerValue").get();
      // #ws-header

      String jsonString = "{\"key1\":\"value1\"}";
      // #ws-header-content-type
      ws.url(url).setHeader("Content-Type", "application/json").post(jsonString);
      // OR
      ws.url(url).setContentType("application/json").post(jsonString);
      // #ws-header-content-type

      // #ws-timeout
      ws.url(url).setRequestTimeout(1000).get();
      // #ws-timeout

      // #ws-post-form-data
      ws.url(url)
          .setContentType("application/x-www-form-urlencoded")
          .post("key1=value1&key2=value2");
      // #ws-post-form-data

      // #ws-post-json
      JsonNode json = Json.newObject().put("key1", "value1").put("key2", "value2");

      ws.url(url).post(json);
      // #ws-post-json

      String value =
          IntStream.range(0, 100).boxed().map(i -> "abcdefghij").reduce("", (a, b) -> a + b);
      ByteString seedValue = ByteString.fromString(value);
      Stream<ByteString> largeSource = IntStream.range(0, 10).boxed().map(i -> seedValue);
      Source<ByteString, ?> largeImage = Source.from(largeSource.collect(Collectors.toList()));
      // #ws-stream-request
      CompletionStage<WSResponse> wsResponse = ws.url(url).setBody(largeImage).execute("PUT");
      // #ws-stream-request
    }
  abstract static class Model {
    // #model
    public static class Author {
      public final String handle;

      public Author(String handle) {
        this.handle = handle;
      }

      // ...

      // #model

      @Override
      public String toString() {
        return "Author(" + handle + ")";
      }

      @Override
      public boolean equals(Object o) {
        if (this == o) {
          return true;
        }
        if (o == null || getClass() != o.getClass()) {
          return false;
        }

        Author author = (Author) o;

        if (handle != null ? !handle.equals(author.handle) : author.handle != null) {
          return false;
        }

        return true;
      }

      @Override
      public int hashCode() {
        return handle != null ? handle.hashCode() : 0;
      }
      // #model
    }
    // #model

    // #model

    public static class Hashtag {
      public final String name;

      public Hashtag(String name) {
        this.name = name;
      }

      // ...
      // #model

      @Override
      public int hashCode() {
        return name.hashCode();
      }

      @Override
      public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        Hashtag other = (Hashtag) obj;
        return name.equals(other.name);
      }

      @Override
      public String toString() {
        return "Hashtag(" + name + ")";
      }
      // #model
    }
    // #model

    // #model

    public static class Tweet {
      public final Author author;
      public final long timestamp;
      public final String body;

      public Tweet(Author author, long timestamp, String body) {
        this.author = author;
        this.timestamp = timestamp;
        this.body = body;
      }

      public Set<Hashtag> hashtags() {
        return Arrays.asList(body.split(" "))
            .stream()
            .filter(a -> a.startsWith("#"))
            .map(a -> new Hashtag(a))
            .collect(Collectors.toSet());
      }

      // ...
      // #model

      @Override
      public String toString() {
        return "Tweet(" + author + "," + timestamp + "," + body + ")";
      }

      // #model
    }
    // #model

    // #model

    public static final Hashtag AKKA = new Hashtag("#akka");
    // #model

    public static final Source<Tweet, NotUsed> tweets =
        Source.from(
            Arrays.asList(
                new Tweet[] {
                  new Tweet(new Author("rolandkuhn"), System.currentTimeMillis(), "#akka rocks!"),
                  new Tweet(new Author("patriknw"), System.currentTimeMillis(), "#akka !"),
                  new Tweet(new Author("bantonsson"), System.currentTimeMillis(), "#akka !"),
                  new Tweet(new Author("drewhk"), System.currentTimeMillis(), "#akka !"),
                  new Tweet(
                      new Author("ktosopl"), System.currentTimeMillis(), "#akka on the rocks!"),
                  new Tweet(new Author("mmartynas"), System.currentTimeMillis(), "wow #akka !"),
                  new Tweet(new Author("akkateam"), System.currentTimeMillis(), "#akka rocks!"),
                  new Tweet(new Author("bananaman"), System.currentTimeMillis(), "#bananas rock!"),
                  new Tweet(new Author("appleman"), System.currentTimeMillis(), "#apples rock!"),
                  new Tweet(
                      new Author("drama"),
                      System.currentTimeMillis(),
                      "we compared #apples to #oranges!")
                }));
  }