Java Code Examples for akka.stream.javadsl.Source#runWith()

The following examples show how to use akka.stream.javadsl.Source#runWith() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoTimestampPersistence.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates the capped collection {@code collectionName} using {@code clientWrapper} if it doesn't exists yet.
 *
 * @param database The database to use.
 * @param collectionName The name of the capped collection that should be created.
 * @param cappedCollectionSizeInBytes The size in bytes of the collection that should be created.
 * @param materializer The actor materializer to pre-materialize the restart source.
 * @return Returns the created or retrieved collection.
 */
private static Source<MongoCollection, NotUsed> createOrGetCappedCollection(
        final MongoDatabase database,
        final String collectionName,
        final long cappedCollectionSizeInBytes,
        final ActorMaterializer materializer) {

    final Source<Success, NotUsed> createCollectionSource =
            repeatableCreateCappedCollectionSource(database, collectionName, cappedCollectionSizeInBytes);

    final Source<MongoCollection, NotUsed> infiniteCollectionSource =
            createCollectionSource.map(success -> database.getCollection(collectionName))
                    .flatMapConcat(Source::repeat);

    final Source<MongoCollection, NotUsed> restartSource =
            RestartSource.withBackoff(BACKOFF_MIN, BACKOFF_MAX, 1.0, () -> infiniteCollectionSource);

    // pre-materialize source with BroadcastHub so that a successfully obtained capped collection is reused
    // until the stream fails, whereupon it gets recreated with backoff.
    return restartSource.runWith(BroadcastHub.of(MongoCollection.class, 1), materializer);
}
 
Example 2
Source File: ResumeSourceTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCancellation() {
    new TestKit(system) {{
        final Source<Integer, NotUsed> underTest = createResumeSource(getRef(), -1);

        underTest.runWith(testSink, mat);

        // start stream with demand
        sinkProbe.request(100L);
        expectMsg(0);
        reply(testSource);

        // send some elements followed by cancellation
        sourceProbe.sendNext(1).sendNext(2);
        sinkProbe.expectNext(1, 2);
        sinkProbe.cancel();
        sourceProbe.expectCancellation();
    }};
}
 
Example 3
Source File: ResumeSourceTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCompletion() {
    // TODO: delete this
    system.eventStream().setLogLevel(Attributes.logLevelDebug());
    new TestKit(system) {{
        final Source<Integer, NotUsed> underTest = createResumeSource(getRef(), -1);

        underTest.runWith(testSink, mat);

        // start stream with demand
        sinkProbe.request(2L);
        expectMsg(0);
        reply(testSource);

        // send some elements followed by completion
        sourceProbe.sendNext(1).sendNext(2);
        sourceProbe.sendComplete();
        sinkProbe.expectNext(1, 2);
        sinkProbe.expectComplete();
    }};
}
 
Example 4
Source File: ResumeSourceTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testFailureAfterMaxRestarts() {
    // disable logging to suppress expected stacktrace
    system.eventStream().setLogLevel(Attributes.logLevelOff());
    new TestKit(system) {{
        final Source<Integer, NotUsed> underTest = createResumeSource(getRef(), 0);

        underTest.runWith(testSink, mat);

        // start stream with demand
        sinkProbe.request(100L);
        expectMsg(0);
        reply(testSource);

        // send some elements followed by failure
        sourceProbe.sendNext(1).sendNext(2);
        sinkProbe.expectNext(1, 2);
        final Throwable error = new IllegalStateException("Expected error");
        sourceProbe.sendError(error);

        // expect stream failed
        assertThat(sinkProbe.expectError()).isInstanceOf(StreamLimitReachedException.class);
    }};
}
 
Example 5
Source File: AkkaApplication.java    From reactive-code-workshop with Apache License 2.0 5 votes vote down vote up
private void dumpSourceToStdOut(Source<?,NotUsed> src) throws InterruptedException, ExecutionException {
    final ActorSystem system = ActorSystem.create("QuickStart");
    final Materializer materializer = ActorMaterializer.create(system);

    final CompletionStage<Done> done = src.runWith(Sink.foreach(a -> System.out.println(a)),materializer);
    done.thenRun(()->system.terminate());

    // Make it happen
    done.toCompletableFuture().get();
}
 
Example 6
Source File: AkkaApplicationTest.java    From reactive-code-workshop with Apache License 2.0 5 votes vote down vote up
private String dumpSourceToString(Source<?,NotUsed> f) throws InterruptedException, ExecutionException {
    final ActorSystem system = ActorSystem.create("QuickStart");
    final Materializer materializer = ActorMaterializer.create(system);

    StringBuilder s = new StringBuilder();
    final CompletionStage<Done> done = f.runWith(Sink.foreach(a -> s.append(a)),materializer);

    done.thenRun(()->system.terminate());
    done.toCompletableFuture().get();

    return s.toString();
}
 
Example 7
Source File: ResumeSourceTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testResumption() {
    new TestKit(system) {{
        final Source<Integer, NotUsed> underTest = createResumeSource(getRef(), -1);

        underTest.runWith(testSink, mat);

        // start stream with demand
        sinkProbe.request(100L);
        expectMsg(0);
        reply(testSource);

        // send some elements followed by failure
        sourceProbe.sendNext(1).sendNext(2);
        sinkProbe.expectNext(1, 2);
        sourceProbe.sendError(new IllegalStateException("1st expected error"));

        // expect new seed equal to final element sent
        expectMsg(2);
        rematerializeSource();
        reply(testSource);

        // fail again without sending any element
        sourceProbe.sendError(new IllegalStateException("2nd expected error"));

        // expect new seed unchanged and not reset
        expectMsg(2);
        rematerializeSource();
        reply(testSource);

        // resume stream until completion
        sourceProbe.sendNext(3).sendNext(4).sendNext(5);
        sourceProbe.sendComplete();
        sinkProbe.expectNext(3, 4, 5);
        sinkProbe.expectComplete();
    }};
}
 
Example 8
Source File: ThingsJournalTestHelper.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private <T> List<T> runBlockingWithReturn(final Source<T, NotUsed> publisher) {
    final CompletionStage<List<T>> done = publisher.runWith(Sink.seq(), mat);
    try {
        return done.toCompletableFuture().get(WAIT_TIMEOUT, TimeUnit.SECONDS);
    } catch (final InterruptedException | ExecutionException | TimeoutException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 9
Source File: PoliciesJournalTestHelper.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private <T> List<T> runBlockingWithReturn(final Source<T, NotUsed> publisher) {
    final CompletionStage<List<T>> done = publisher.runWith(Sink.seq(), mat);
    try {
        return done.toCompletableFuture().get(WAIT_TIMEOUT, TimeUnit.SECONDS);
    } catch (final InterruptedException | ExecutionException | TimeoutException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 10
Source File: AkkaProcProxy.java    From RHub with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected <T> Publisher<T> filter(Processor processor, final Class<T> filterClass) {
    Source src = Source.fromPublisher(processor)
            .filter(o -> filterClass.isAssignableFrom(o.getClass()));
    return (Publisher<T>) src.runWith(Sink.asPublisher(AsPublisher.WITH_FANOUT), mat);
}
 
Example 11
Source File: PortfolioServiceImplTest.java    From reactive-stock-trader with Apache License 2.0 4 votes vote down vote up
@Test
public void ignoreDuplicateTrades() throws Exception {
    PortfolioService service = server.client(PortfolioService.class);
    OpenPortfolioDetails details = new OpenPortfolioDetails("portfolioName");
    val portfolioId = service.openPortfolio().invoke(details).toCompletableFuture().get(5, SECONDS);
    Source<OrderPlaced, ?> source = service.orderPlaced().subscribe().atMostOnceSource();
    TestSubscriber.Probe<OrderPlaced> probe =
            source.runWith(TestSink.probe(server.system()), server.materializer());

    String symbol = "IBM";
    int sharesToBuy = 31;
    OrderDetails buyOrderDetails = OrderDetails.builder()
            .symbol(symbol)
            .shares(sharesToBuy)
            .tradeType(TradeType.BUY)
            .orderType(OrderType.Market.INSTANCE)
            .build();

    val orderId = service.placeOrder(portfolioId).invoke(buyOrderDetails).toCompletableFuture().get(5, SECONDS);

    BigDecimal price = new BigDecimal("123.45");
    OrderResult tradeResult = OrderResult.Fulfilled.builder()
            .portfolioId(portfolioId)
            .orderId(orderId)
            .trade(Trade.builder()
                    .tradeType(TradeType.BUY)
                    .symbol(symbol)
                    .sharePrice(price)
                    .shares(sharesToBuy)
                    .build()
            ).build();

    BrokerStub.orderResultProducerStub.send(tradeResult);
    BrokerStub.orderResultProducerStub.send(tradeResult);


    PortfolioView view = service.getPortfolio(portfolioId).invoke().toCompletableFuture().get(5, SECONDS);
    assertEquals(1, view.getHoldings().size());
    assertEquals(sharesToBuy, view.getHoldings().get(0).getShareCount());

}
 
Example 12
Source File: SubscriptionActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void connect(final ActorRef subscriptionActor, final Source<JsonArray, ?> pageSource,
        final TestKit testKit) {
    final Subscriber<JsonArray> subscriber = SubscriptionActor.asSubscriber(subscriptionActor);
    pageSource.runWith(Sink.fromSubscriber(subscriber), materializer);
    testKit.expectMsgClass(SubscriptionCreated.class);
}
 
Example 13
Source File: AbstractThingSearchPersistenceITBase.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
protected <T> T runBlockingWithReturn(final Source<T, NotUsed> publisher) {
    final CompletionStage<T> done = publisher.runWith(Sink.last(), actorMaterializer);
    return done.toCompletableFuture().join();
}