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

The following examples show how to use akka.stream.javadsl.Source#single() . 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: AriCommandResponseKafkaProcessorTest.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test()
void properlyHandleInvalidCommandMessage() {
	final TestKit kafkaProducer = new TestKit(system);
	final TestKit metricsService = new TestKit(system);
	final TestKit callContextProvider = new TestKit(system);

	final ConsumerRecord<String, String> consumerRecord = new ConsumerRecord<>("topic", 0, 0,
			"key", "NOT JSON");
	final Source<ConsumerRecord<String, String>, NotUsed> source = Source.single(consumerRecord);
	final Sink<ProducerRecord<String, String>, NotUsed> sink = Sink.<ProducerRecord<String, String>>ignore()
			.mapMaterializedValue(q -> NotUsed.getInstance());

	AriCommandResponseKafkaProcessor.commandResponseProcessing()
			.on(system)
			.withHandler(requestAndContext -> Http.get(system).singleRequest(requestAndContext._1))
			.withCallContextProvider(callContextProvider.getRef())
			.withMetricsService(metricsService.getRef())
			.from(source)
			.to(sink)
			.run();

	kafkaProducer.expectNoMsg(Duration.apply(250, TimeUnit.MILLISECONDS));
}
 
Example 2
Source File: WebsocketMessageToProducerRecordTranslatorITCase.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
void verifyProcessingPipelineWorksAsExpectedForBogusMessages() {

	final TestKit catchAllProbe = new TestKit(system);

	final Source<Message, NotUsed> source = Source.single(new Strict("invalid message from ws"));
	final Sink<ProducerRecord<String, String>, NotUsed> sink = Sink.actorRef(catchAllProbe.getRef(), new ProducerRecord<String, String>("none", "completed"));

	WebsocketMessageToProducerRecordTranslator.eventProcessing()
			.on(system)
			.withHandler(() -> catchAllProbe.getRef().tell("Application replaced", catchAllProbe.getRef()))
			.withCallContextProvider(catchAllProbe.getRef())
			.withMetricsService(catchAllProbe.getRef())
			.from(source)
			.to(sink)
			.run();

	final ProducerRecord<String, String> completeMsg = catchAllProbe.expectMsgClass(ProducerRecord.class);
	assertThat(completeMsg.topic(), is("none"));
	assertThat(completeMsg.value(), is("completed"));
}
 
Example 3
Source File: DefaultPersistenceStreamingActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void retrieveNonEmptyStream() {
    new TestKit(actorSystem) {{
        final Source<String, NotUsed> mockedSource = Source.single(ID.toString());
        final ActorRef underTest = createPersistenceQueriesActor(mockedSource);
        final Command<?> command = createStreamingRequest();

        sendCommand(this, underTest, command);

        final SourceRef<Object> sourceRef = expectMsgClass(SourceRef.class);

        final Object expectedMessage =
                BatchedEntityIdWithRevisions.of(SimpleEntityIdWithRevision.class,
                        Collections.singletonList(new SimpleEntityIdWithRevision(ID, 0L)));

        sourceRef.getSource()
                .runWith(TestSink.probe(actorSystem), materializer())
                .request(1000L)
                .expectNext(expectedMessage)
                .expectComplete();
    }};
}
 
Example 4
Source File: SearchSource.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Source<Pair<String, JsonObject>, NotUsed> retrieveThingForElement(final String thingId) {
    if (thingIdOnly) {
        final JsonObject idOnlyThingJson = JsonObject.newBuilder().set(Thing.JsonFields.ID, thingId).build();
        return Source.single(Pair.create(thingId, idOnlyThingJson));
    } else {
        return retrieveThing(thingId, fields)
                .map(thingJson -> Pair.create(thingId, thingJson))
                .recoverWithRetries(1,
                        new PFBuilder<Throwable, Graph<SourceShape<Pair<String, JsonObject>>, NotUsed>>()
                                .match(ThingNotAccessibleException.class, thingNotAccessible -> {
                                    // out-of-sync thing detected
                                    final ThingsOutOfSync thingsOutOfSync =
                                            ThingsOutOfSync.of(Collections.singletonList(ThingId.of(thingId)),
                                                    getDittoHeaders());

                                    pubSubMediator.tell(
                                            DistPubSubAccess.publishViaGroup(ThingsOutOfSync.TYPE, thingsOutOfSync),
                                            ActorRef.noSender());
                                    return Source.empty();
                                })
                                .build()
                );
    }
}
 
Example 5
Source File: AkkaStreamsDemoTest.java    From reactive-streams-in-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test_a_source() {
    Sink<Object, TestSubscriber.Probe<Object>> sink = TestSink.probe(system);
    Source<Object, NotUsed> sourceUnderTest = Source.single("test");

    sourceUnderTest.runWith(sink, materializer)
            .request(1)
            .expectNext("test")
            .expectComplete();
}
 
Example 6
Source File: PersistenceIdSource.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static Source<Object, NotUsed> checkForErrors(
        final Tuple3<DistributedPubSubMediator.Send, Object, Throwable> triple) {
    if (triple.t2() != null) {
        return Source.single(triple.t2());
    } else {
        final String message = String.format("Error on sending <%s>: %s", triple.t1(), triple.t3());
        return Source.failed(new IllegalStateException(message));
    }
}
 
Example 7
Source File: SearchSource.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<StreamThings, NotUsed> streamThingsFrom(final String lastThingId) {
    if (lastThingId.isEmpty()) {
        return Source.single(streamThings);
    } else {
        return retrieveSortValues(lastThingId).map(streamThings::setSortValues);
    }
}
 
Example 8
Source File: SearchActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static <T> Source<Query, NotUsed> createQuerySource(final Function<T, Query> parser,
        final T command) {

    try {
        return Source.single(parser.apply(command));
    } catch (final Throwable e) {
        return Source.failed(e);
    }
}
 
Example 9
Source File: EnforcementFlow.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<AbstractWriteModel, NotUsed> computeWriteModel(final Metadata metadata,
        @Nullable final SudoRetrieveThingResponse sudoRetrieveThingResponse) {

    if (sudoRetrieveThingResponse == null) {
        return deleteEvent
                ? Source.single(ThingDeleteModel.of(metadata))
                : Source.empty();
    } else {
        final JsonObject thing = sudoRetrieveThingResponse.getEntity().asObject();

        return getEnforcer(metadata, thing)
                .map(entry -> {
                    if (entry.exists()) {
                        try {
                            return EnforcedThingMapper.toWriteModel(thing, entry.getValueOrThrow(),
                                    entry.getRevision(),
                                    maxArraySize);
                        } catch (final JsonRuntimeException e) {
                            log.error(e.getMessage(), e);
                            return ThingDeleteModel.of(metadata);
                        }
                    } else {
                        // no enforcer; delete thing from search index
                        return ThingDeleteModel.of(metadata);
                    }
                });
    }
}
 
Example 10
Source File: EnforcementFlow.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get the enforcer of a thing or an empty source if it does not exist.
 *
 * @param metadata metadata of the thing.
 * @param thing the thing (possibly containing ACL)
 * @return source of an enforcer or an empty source.
 */
private Source<Entry<Enforcer>, NotUsed> getEnforcer(final Metadata metadata, final JsonObject thing) {
    final Optional<JsonObject> acl = thing.getValue(Thing.JsonFields.ACL);
    if (acl.isPresent()) {
        return Source.single(Entry.permanent(AclEnforcer.of(ThingsModelFactory.newAcl(acl.get()))));
    } else {
        return thing.getValue(Thing.JsonFields.POLICY_ID)
                .map(PolicyId::of)
                .map(policyId -> readCachedEnforcer(metadata, getPolicyEntityId(policyId), 0))
                .orElse(ENFORCER_NONEXISTENT);
    }
}
 
Example 11
Source File: AriCommandResponseKafkaProcessorTest.java    From ari-proxy with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test()
void handlePlaybackCommand() {

	final TestKit kafkaProducer = new TestKit(system);
	final TestKit metricsService = new TestKit(system);
	final TestKit callContextProvider = new TestKit(system);

	final ConsumerRecord<String, String> consumerRecord = new ConsumerRecord<>("topic", 0, 0,
			"none", "{\n"
			+ "   \"callContext\" : \"CALL_CONTEXT\",\n"
			+ "   \"commandId\" : \"COMMANDID\",\n"
			+ "   \"ariCommand\" : {\n"
			+ "      \"url\" : \"/channels/1533286879.42/play/c4958563-1ba4-4f2f-a60f-626a624bf0e6\",\n"
			+ "      \"method\" : \"POST\",\n"
			+ "      \"body\" : {\"media\": \"sound:hd/register_success\", \"lang\":\"de\"}"
			+ "   }\n"
			+ "}");

	final Source<ConsumerRecord<String, String>, NotUsed> source = Source.single(consumerRecord);
	final Sink<ProducerRecord<String, String>, NotUsed> sink = Sink
			.actorRef(kafkaProducer.getRef(), new ProducerRecord<String, String>("topic", "endMessage"));

	AriCommandResponseKafkaProcessor.commandResponseProcessing()
			.on(system)
			.withHandler(r -> CompletableFuture.supplyAsync(() ->
					HttpResponse.create().withStatus(StatusCodes.OK).withEntity("{ \"key\":\"value\" }"))
			)
			.withCallContextProvider(callContextProvider.getRef())
			.withMetricsService(metricsService.getRef())
			.from(source)
			.to(sink)
			.run();

	final RegisterCallContext registerCallContext = callContextProvider.expectMsgClass(RegisterCallContext.class);
	assertThat(registerCallContext.callContext(), is("CALL_CONTEXT"));
	assertThat(registerCallContext.resourceId(), is("c4958563-1ba4-4f2f-a60f-626a624bf0e6"));
	callContextProvider.reply(new CallContextProvided("CALL CONTEXT"));

	final StopCallSetupTimer stopCallSetupTimer = metricsService.expectMsgClass(StopCallSetupTimer.class);
	assertThat(stopCallSetupTimer.getCallcontext(), is("CALL_CONTEXT"));
	assertThat(stopCallSetupTimer.getApplication(), is("test-app"));

	final ProducerRecord responseRecord = kafkaProducer.expectMsgClass(ProducerRecord.class);
	assertThat(responseRecord.topic(), is("eventsAndResponsesTopic"));
	assertThat(responseRecord.key(), is("CALL_CONTEXT"));

	final ProducerRecord endMsg = kafkaProducer.expectMsgClass(ProducerRecord.class);
	assertThat(endMsg.topic(), is("topic"));
	assertThat(endMsg.value(), is("endMessage"));
}
 
Example 12
Source File: AriCommandResponseKafkaProcessorTest.java    From ari-proxy with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test()
void handleAnswerCommand() {
	final TestKit kafkaProducer = new TestKit(system);
	final TestKit metricsService = new TestKit(system);
	final TestKit callContextProvider = new TestKit(system);

	final ConsumerRecord<String, String> consumerRecord = new ConsumerRecord<>("topic", 0, 0,
			"none", "{\n"
			+ "   \"callContext\" : \"CALL_CONTEXT\",\n"
			+ "   \"ariCommand\" : {\n"
			+ "      \"url\" : \"/channels/1533218784.36/answer\",\n"
			+ "      \"body\" : \"\",\n"
			+ "      \"method\" : \"POST\"\n"
			+ "   }\n"
			+ "}");
	final Source<ConsumerRecord<String, String>, NotUsed> source = Source.single(consumerRecord);
	final Sink<ProducerRecord<String, String>, NotUsed> sink = Sink
			.actorRef(kafkaProducer.getRef(), new ProducerRecord<String, String>("topic", "endMessage"));

	AriCommandResponseKafkaProcessor.commandResponseProcessing()
			.on(system)
			.withHandler(r -> CompletableFuture.supplyAsync(() ->
					HttpResponse.create().withStatus(StatusCodes.NO_CONTENT))
			)
			.withCallContextProvider(callContextProvider.getRef())
			.withMetricsService(metricsService.getRef())
			.from(source)
			.to(sink)
			.run();

	final StopCallSetupTimer stopCallSetupTimer = metricsService.expectMsgClass(StopCallSetupTimer.class);
	assertThat(stopCallSetupTimer.getCallcontext(), is("CALL_CONTEXT"));
	assertThat(stopCallSetupTimer.getApplication(), is("test-app"));

	final ProducerRecord responseRecord = kafkaProducer.expectMsgClass(ProducerRecord.class);
	assertThat(responseRecord.topic(), is("eventsAndResponsesTopic"));
	assertThat(responseRecord.key(), is("CALL_CONTEXT"));

	final ProducerRecord endMsg = kafkaProducer.expectMsgClass(ProducerRecord.class);
	assertThat(endMsg.topic(), is("topic"));
	assertThat(endMsg.value(), is("endMessage"));
}
 
Example 13
Source File: WebsocketMessageToProducerRecordTranslatorITCase.java    From ari-proxy with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
@DisplayName("A websocket message shall be converted into a kafka producer record while also recording metrics")
void verifyProsessingPipelineWorksAsExpected() {
	final TestKit callcontextProvider = new TestKit(system);
	final TestKit metricsService = new TestKit(system);
	final TestKit kafkaProducer = new TestKit(system);
	final TestKit applicationReplacedHandler = new TestKit(system);

	final Strict stasisStartEvent = new Strict(StasisEvents.stasisStartEvent);

	final String resourceId = "1532965104.0";

	final Source<Message, NotUsed> source = Source.single(stasisStartEvent);

	final Sink<ProducerRecord<String, String>, NotUsed> sink = Sink.actorRef(kafkaProducer.getRef(), new ProducerRecord<String, String>("none", "completed"));

	WebsocketMessageToProducerRecordTranslator.eventProcessing()
			.on(system)
			.withHandler(() -> applicationReplacedHandler.getRef().tell("Application replaced", ActorRef.noSender()))
			.withCallContextProvider(callcontextProvider.getRef())
			.withMetricsService(metricsService.getRef())
			.from(source)
			.to(sink)
			.run();

	final ProvideCallContext provideCallContextForMetrics = callcontextProvider.expectMsgClass(ProvideCallContext.class);
	assertThat(provideCallContextForMetrics.resourceId(), is(resourceId));
	assertThat(provideCallContextForMetrics.policy(), is(ProviderPolicy.CREATE_IF_MISSING));
	callcontextProvider.reply(CALL_CONTEXT_PROVIDED);

	kafkaProducer.expectMsgClass(ProducerRecord.class);

	final IncreaseCounter eventTypeCounter = metricsService.expectMsgClass(IncreaseCounter.class);
	assertThat(eventTypeCounter.getName(), CoreMatchers.is(AriMessageType.STASIS_START.name()));

	final IncreaseCounter callsStartedCounter = metricsService.expectMsgClass(IncreaseCounter.class);
	assertThat(callsStartedCounter.getName(), is("CallsStarted"));

	final ProvideCallContext provideCallContextForRouting = callcontextProvider.expectMsgClass(ProvideCallContext.class);
	assertThat(provideCallContextForRouting.resourceId(), is(resourceId));
	assertThat(provideCallContextForRouting.policy(), is(ProviderPolicy.CREATE_IF_MISSING));
	callcontextProvider.reply(CALL_CONTEXT_PROVIDED);

	final StartCallSetupTimer startCallSetupTimer = metricsService.expectMsgClass(StartCallSetupTimer.class);
	assertThat(startCallSetupTimer.getCallContext(), is(CALL_CONTEXT_PROVIDED.callContext()));

	final ProducerRecord completedRecord = kafkaProducer.expectMsgClass(ProducerRecord.class);
	assertThat(completedRecord.topic(), is("none"));
	assertThat(completedRecord.value(), is("completed"));
}
 
Example 14
Source File: MongoReadJournal.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private Source<MongoCollection<Document>, NotUsed> getJournal() {
    return Source.single(mongoClient.getDefaultDatabase().getCollection(journalCollection));
}
 
Example 15
Source File: MongoReadJournal.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private Source<MongoCollection<Document>, NotUsed> getSnapshotStore() {
    return Source.single(mongoClient.getDefaultDatabase().getCollection(snapsCollection));
}