Example #1
0
 @Test
 public void mustProduceTicks() throws Exception {
   final JavaTestKit probe = new JavaTestKit(system);
   Source<String, Cancellable> tickSource =
       Source.tick(
           FiniteDuration.create(1, TimeUnit.SECONDS),
           FiniteDuration.create(500, TimeUnit.MILLISECONDS),
           "tick");
   @SuppressWarnings("unused")
   Cancellable cancellable =
       tickSource
           .to(
               Sink.foreach(
                   new Procedure<String>() {
                     public void apply(String elem) {
                       probe.getRef().tell(elem, ActorRef.noSender());
                     }
                   }))
           .run(materializer);
   probe.expectNoMsg(FiniteDuration.create(600, TimeUnit.MILLISECONDS));
   probe.expectMsgEquals("tick");
   probe.expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS));
   probe.expectMsgEquals("tick");
   probe.expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS));
 }
Example #2
0
  @Test
  public void mustBeAbleToRecover() throws Exception {
    final ManualProbe<Integer> publisherProbe = TestPublisher.manualProbe(true, system);
    final JavaTestKit probe = new JavaTestKit(system);

    final Source<Integer, NotUsed> source =
        Source.fromPublisher(publisherProbe)
            .map(
                elem -> {
                  if (elem == 1) throw new RuntimeException("ex");
                  else return elem;
                })
            .recover(new PFBuilder<Throwable, Integer>().matchAny(ex -> 0).build());

    final CompletionStage<Done> future =
        source.runWith(
            Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer);
    final PublisherProbeSubscription<Integer> s = publisherProbe.expectSubscription();
    s.sendNext(0);
    probe.expectMsgEquals(0);
    s.sendNext(1);
    probe.expectMsgEquals(0);

    future.toCompletableFuture().get(200, TimeUnit.MILLISECONDS);
  }
Example #3
0
  @Test
  public void complexGraph() throws Exception {
    // #complex-graph
    RunnableGraph.fromGraph(
        GraphDSL.create(
            builder -> {
              final Outlet<Integer> A = builder.add(Source.single(0)).out();
              final UniformFanOutShape<Integer, Integer> B = builder.add(Broadcast.create(2));
              final UniformFanInShape<Integer, Integer> C = builder.add(Merge.create(2));
              final FlowShape<Integer, Integer> D =
                  builder.add(Flow.of(Integer.class).map(i -> i + 1));
              final UniformFanOutShape<Integer, Integer> E = builder.add(Balance.create(2));
              final UniformFanInShape<Integer, Integer> F = builder.add(Merge.create(2));
              final Inlet<Integer> G = builder.add(Sink.<Integer>foreach(System.out::println)).in();

              builder.from(F).toFanIn(C);
              builder.from(A).viaFanOut(B).viaFanIn(C).toFanIn(F);
              builder.from(B).via(D).viaFanOut(E).toFanIn(F);
              builder.from(E).toInlet(G);
              return ClosedShape.getInstance();
            }));
    // #complex-graph

    // #complex-graph-alt
    RunnableGraph.fromGraph(
        GraphDSL.create(
            builder -> {
              final SourceShape<Integer> A = builder.add(Source.single(0));
              final UniformFanOutShape<Integer, Integer> B = builder.add(Broadcast.create(2));
              final UniformFanInShape<Integer, Integer> C = builder.add(Merge.create(2));
              final FlowShape<Integer, Integer> D =
                  builder.add(Flow.of(Integer.class).map(i -> i + 1));
              final UniformFanOutShape<Integer, Integer> E = builder.add(Balance.create(2));
              final UniformFanInShape<Integer, Integer> F = builder.add(Merge.create(2));
              final SinkShape<Integer> G = builder.add(Sink.foreach(System.out::println));

              builder.from(F.out()).toInlet(C.in(0));
              builder.from(A).toInlet(B.in());
              builder.from(B.out(0)).toInlet(C.in(1));
              builder.from(C.out()).toInlet(F.in(0));
              builder.from(B.out(1)).via(D).toInlet(E.in());
              builder.from(E.out(0)).toInlet(F.in(1));
              builder.from(E.out(1)).to(G);
              return ClosedShape.getInstance();
            }));
    // #complex-graph-alt
  }
Example #4
0
 @Test
 public void closedGraph() throws Exception {
   // #embed-closed
   final RunnableGraph<NotUsed> closed1 = Source.single(0).to(Sink.foreach(System.out::println));
   final RunnableGraph<NotUsed> closed2 =
       RunnableGraph.fromGraph(
           GraphDSL.create(
               builder -> {
                 final ClosedShape embeddedClosed = builder.add(closed1);
                 return embeddedClosed; // Could return ClosedShape.getInstance()
               }));
   // #embed-closed
 }
Example #5
0
 @Test
 public void mustBeAbleToUseActorRefSource() throws Exception {
   final JavaTestKit probe = new JavaTestKit(system);
   final Source<Integer, ActorRef> actorRefSource = Source.actorRef(10, OverflowStrategy.fail());
   final ActorRef ref =
       actorRefSource
           .to(
               Sink.foreach(
                   new Procedure<Integer>() {
                     public void apply(Integer elem) {
                       probe.getRef().tell(elem, ActorRef.noSender());
                     }
                   }))
           .run(materializer);
   ref.tell(1, ActorRef.noSender());
   probe.expectMsgEquals(1);
   ref.tell(2, ActorRef.noSender());
   probe.expectMsgEquals(2);
 }
Example #6
0
    public void streamFile()
        throws IOException, FileNotFoundException, InterruptedException, ExecutionException {
      String url = "http://example.com";
      // #stream-to-file
      File file = File.createTempFile("stream-to-file-", ".txt");
      FileOutputStream outputStream = new FileOutputStream(file);

      // Make the request
      CompletionStage<StreamedResponse> futureResponse = ws.url(url).setMethod("GET").stream();

      CompletionStage<File> downloadedFile =
          futureResponse.thenCompose(
              res -> {
                Source<ByteString, ?> responseBody = res.getBody();

                // The sink that writes to the output stream
                Sink<ByteString, scala.concurrent.Future<scala.runtime.BoxedUnit>> outputWriter =
                    Sink.<ByteString>foreach(bytes -> outputStream.write(bytes.toArray()));

                // Converts the materialized Scala Future into a Java8 `CompletionStage`
                Sink<ByteString, CompletionStage<?>> convertedOutputWriter =
                    outputWriter.mapMaterializedValue(FutureConverters::toJava);

                // materialize and run the stream
                CompletionStage<File> result =
                    responseBody
                        .runWith(convertedOutputWriter, materializer)
                        .whenComplete(
                            (value, error) -> {
                              // Close the output stream whether there was an error or not
                              try {
                                outputStream.close();
                              } catch (IOException e) {
                              }
                            })
                        .thenApply(v -> file);
                return result;
              });
      // #stream-to-file
      downloadedFile.toCompletableFuture().get();
      file.delete();
    }
Example #7
0
  @Test
  public void mustBeAbleToUseDropWhile() throws Exception {
    final JavaTestKit probe = new JavaTestKit(system);
    final Source<Integer, NotUsed> source =
        Source.from(Arrays.asList(0, 1, 2, 3))
            .dropWhile(
                new Predicate<Integer>() {
                  public boolean test(Integer elem) {
                    return elem < 2;
                  }
                });

    final CompletionStage<Done> future =
        source.runWith(
            Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer);

    probe.expectMsgEquals(2);
    probe.expectMsgEquals(3);
    future.toCompletableFuture().get(200, TimeUnit.MILLISECONDS);
  }
  @Test
  public void demonstrateFilterAndMap() {
    final SilenceSystemOut.System System = SilenceSystemOut.get();

    // #first-sample

    // #authors-filter-map
    final Source<Author, NotUsed> authors =
        tweets.filter(t -> t.hashtags().contains(AKKA)).map(t -> t.author);
    // #first-sample
    // #authors-filter-map

    new Object() {
      // #authors-collect
      JavaPartialFunction<Tweet, Author> collectFunction =
          new JavaPartialFunction<Tweet, Author>() {
            public Author apply(Tweet t, boolean isCheck) {
              if (t.hashtags().contains(AKKA)) {
                if (isCheck) return null; // to spare the expensive or side-effecting code
                return t.author;
              } else {
                throw noMatch();
              }
            }
          };

      final Source<Author, NotUsed> authors = tweets.collect(collectFunction);
      // #authors-collect
    };

    // #first-sample

    // #authors-foreachsink-println
    authors.runWith(Sink.foreach(a -> System.out.println(a)), mat);
    // #first-sample
    // #authors-foreachsink-println

    // #authors-foreach-println
    authors.runForeach(a -> System.out.println(a), mat);
    // #authors-foreach-println
  }
Example #9
0
  @Test
  public void mustBeAbleToCombine() throws Exception {
    final JavaTestKit probe = new JavaTestKit(system);
    final Source<Integer, NotUsed> source1 = Source.from(Arrays.asList(0, 1));
    final Source<Integer, NotUsed> source2 = Source.from(Arrays.asList(2, 3));

    final Source<Integer, NotUsed> source =
        Source.combine(
            source1,
            source2,
            new ArrayList<Source<Integer, ?>>(),
            width -> Merge.<Integer>create(width));

    final CompletionStage<Done> future =
        source.runWith(
            Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer);

    probe.expectMsgAllOf(0, 1, 2, 3);

    future.toCompletableFuture().get(200, TimeUnit.MILLISECONDS);
  }
Example #10
0
  @Test
  public void mustBeAbleToUseIntersperse() throws Exception {
    final JavaTestKit probe = new JavaTestKit(system);
    final Source<String, NotUsed> source =
        Source.from(Arrays.asList("0", "1", "2", "3")).intersperse("[", ",", "]");

    final CompletionStage<Done> future =
        source.runWith(
            Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer);

    probe.expectMsgEquals("[");
    probe.expectMsgEquals("0");
    probe.expectMsgEquals(",");
    probe.expectMsgEquals("1");
    probe.expectMsgEquals(",");
    probe.expectMsgEquals("2");
    probe.expectMsgEquals(",");
    probe.expectMsgEquals("3");
    probe.expectMsgEquals("]");
    future.toCompletableFuture().get(200, TimeUnit.MILLISECONDS);
  }