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

The following examples show how to use akka.stream.javadsl.Source#empty() . 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: DefaultPersistenceStreamingActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void retrieveEmptyStream() {
    new TestKit(actorSystem) {{
        final Source<String, NotUsed> mockedSource = Source.empty();
        final ActorRef underTest = createPersistenceQueriesActor(mockedSource);
        final Command<?> command = createStreamingRequest();

        sendCommand(this, underTest, command);

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

        sourceRef.getSource()
                .runWith(TestSink.probe(actorSystem), materializer())
                .request(1000L)
                .expectComplete();
    }};
}
 
Example 2
Source File: BackgroundSyncStream.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Emit metadata to trigger index update if the persistence snapshot and the search index entry are inconsistent.
 * Precondition: the thing IDs are identical and the search index entry is outside the tolerance window.
 *
 * @param persisted metadata from the snapshot store of the persistence.
 * @param indexed metadata from the search index with the same thing ID.
 * @return source of a metadata if the persistence and search index are inconsistent, or an empty source otherwise.
 */
private Source<Metadata, NotUsed> emitUnlessConsistent(final Metadata persisted, final Metadata indexed) {
    if (persisted.getThingRevision() > indexed.getThingRevision()) {
        return Source.single(indexed).log("RevisionMismatch");
    } else {
        final Optional<PolicyId> persistedPolicyId = persisted.getPolicyId();
        final Optional<PolicyId> indexedPolicyId = indexed.getPolicyId();
        if (!persistedPolicyId.equals(indexedPolicyId)) {
            return Source.single(indexed).log("PolicyIdMismatch");
        } else if (persistedPolicyId.isPresent()) {
            // policy IDs are equal and nonempty; retrieve and compare policy revision
            return retrievePolicyRevisionAndEmitMismatch(persistedPolicyId.get(), indexed);
        } else {
            // policy IDs are empty - the entries are consistent.
            return Source.empty();
        }
    }
}
 
Example 3
Source File: IndexInitializer.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<Success, NotUsed> createIndices(final String collectionName, final List<Index> indices) {
    if (indices.isEmpty()) {
        return Source.empty();
    }

    return Source.from(indices)
            .flatMapConcat(index -> createIndex(collectionName, index));
}
 
Example 4
Source File: IndexInitializer.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<Success, NotUsed> dropIndices(final String collectionName, final List<String> indices) {
    if (indices.isEmpty()) {
        return Source.empty();
    }

    return Source.from(indices)
            .flatMapConcat(index -> dropIndex(collectionName, index));
}
 
Example 5
Source File: MongoNamespacePersistenceOperations.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<List<Throwable>, NotUsed> purgeAllSelections(
        final Iterable<MongoPersistenceOperationsSelection> selections) {

    Source<List<Throwable>, NotUsed> result = Source.empty();

    for (final MongoPersistenceOperationsSelection mongoOpsSelection : selections) {
        final Source<List<Throwable>, NotUsed> purge = purge(mongoOpsSelection);
        result = result.merge(purge);
    }

    return result;
}
 
Example 6
Source File: MongoEntitiesPersistenceOperations.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<List<Throwable>, NotUsed> purgeAllSelections(
        final Collection<MongoPersistenceOperationsSelection> selections) {
    Source<List<Throwable>, NotUsed> result = Source.empty();

    for (MongoPersistenceOperationsSelection mongoOpsSelection : selections) {
        final Source<List<Throwable>, NotUsed> purge = purge(mongoOpsSelection);
        result = result.merge(purge);
    }

    return result;
}
 
Example 7
Source File: EntityPersistenceOperations.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Purge all entities contained in the given {@code entityIds}.
 *
 * @param entityIds the IDs of the entities to delete
 * @return source of any errors during the purge.
 */
default Source<List<Throwable>, NotUsed> purgeEntities(final Collection<EntityId> entityIds) {
    Source<List<Throwable>, NotUsed> result = Source.empty();

    for (final EntityId entityId : entityIds) {
        result = result.merge(purgeEntity(entityId));
    }

    return result;
}
 
Example 8
Source File: PolicyEventForwarder.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Source<PolicyReferenceTag, NotUsed> mapDumpResult(final Object dumpResult) {
    if (dumpResult instanceof Map) {
        return persistence.getPolicyReferenceTags((Map<PolicyId, Long>) dumpResult);
    } else {
        if (dumpResult instanceof Throwable) {
            log.error((Throwable) dumpResult, "dump failed");
        } else {
            log.warning("Unexpected dump result: <{}>", dumpResult);
        }
        return Source.empty();
    }
}
 
Example 9
Source File: BackgroundSyncStream.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<Metadata, NotUsed> filterForInconsistency(final Pair<Metadata, Metadata> pair) {
    final Metadata persisted = pair.first();
    final Metadata indexed = pair.second();
    final int comparison = compareMetadata(persisted, indexed);
    final Instant toleranceCutOff = Instant.now().minus(toleranceWindow);
    if (comparison < 0) {
        // persisted thing is not in search index; trigger update if the snapshot is not too recent
        return isInsideToleranceWindow(persisted, toleranceCutOff)
                ? Source.empty()
                : Source.single(persisted).log("PersistedAndNotIndexed");
    } else if (comparison > 0) {
        // indexed thing is not persisted; trigger update if the index entry is not too recent
        return isInsideToleranceWindow(indexed, toleranceCutOff)
                ? Source.empty()
                : Source.single(indexed).log("NotPersistedAndIndexed");
    } else {
        // IDs match
        if (indexed.getThingId().isDummy()) {
            // sanity check: entry should not be dummy
            return Source.failed(new IllegalStateException("Unexpected double-dummy entry: " + pair));
        } else if (isInsideToleranceWindow(indexed, toleranceCutOff)) {
            // ignore entries within tolerance window
            return Source.empty();
        } else {
            return emitUnlessConsistent(persisted, indexed);
        }
    }
}
 
Example 10
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 11
Source File: MessageMappingProcessorActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Source<Signal<?>, ?> mapInboundMessage(final ExternalMessage externalMessage) {
    final String correlationId = externalMessage.getHeaders().get(DittoHeaderDefinition.CORRELATION_ID.getKey());
    ConnectionLogUtil.enhanceLogWithCorrelationIdAndConnectionId(logger, correlationId, connectionId);
    logger.debug("Handling ExternalMessage: {}", externalMessage);
    try {
        return mapExternalMessageToSignal(externalMessage);
    } catch (final Exception e) {
        handleInboundException(e, externalMessage, null, getAuthorizationContext(externalMessage).orElse(null));
        return Source.empty();
    }
}
 
Example 12
Source File: AriEventProcessing.java    From ari-proxy with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Source<ProducerRecord<String, String>, NotUsed> generateProducerRecordFromEvent(
		String kafkaCommandsTopic,
		String kafkaEventsAndResponsesTopic,
		Message message,
		ActorRef callContextProvider,
		LoggingAdapter log,
		Runnable applicationReplacedHandler) {

	final JsonNode messageBody = Try.of(() -> reader.readTree(message.asTextMessage().getStrictText())).getOrElseThrow(t -> new RuntimeException(t));

	final String eventTypeString = getValueFromMessageByPath(message, "/type").getOrElseThrow(t -> t);
	final AriMessageType ariMessageType = AriMessageType.fromType(eventTypeString);

	if (AriMessageType.APPLICATION_REPLACED.equals(ariMessageType)) {
		log.info("Got APPLICATION_REPLACED event, shutting down...");
		applicationReplacedHandler.run();
		return Source.empty();
	}

	return ariMessageType.extractResourceIdFromBody(messageBody)
			.map(resourceIdTry -> resourceIdTry
					.flatMap(id -> getCallContext(
							id,
							callContextProvider,
							AriMessageType.STASIS_START.equals(ariMessageType)
									? ProviderPolicy.CREATE_IF_MISSING
									: ProviderPolicy.LOOKUP_ONLY
					))
					.flatMap(callContext -> createSource(
							kafkaCommandsTopic,
							kafkaEventsAndResponsesTopic,
							ariMessageType,
							log,
							callContext,
							messageBody
					))
			)
			.toTry()
			.flatMap(Function.identity())
			.getOrElseThrow(t -> new RuntimeException(t));
}