akka.japi.pf.ReceiveBuilder Java Examples

The following examples show how to use akka.japi.pf.ReceiveBuilder. 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: ThingsUpdater.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(ThingEvent.class, this::processThingEvent)
            .match(ThingTag.class, this::processThingTag)
            .match(PolicyReferenceTag.class, this::processPolicyReferenceTag)
            .matchEquals(ShardRegion.getShardRegionStateInstance(), getShardRegionState ->
                    shardRegion.forward(getShardRegionState, getContext()))
            .match(RetrieveStatisticsDetails.class, this::handleRetrieveStatisticsDetails)
            .matchEquals(Clock.REBALANCE_TICK, this::retrieveShardIds)
            .match(ShardRegion.ShardRegionStats.class, this::updateSubscriptions)
            .match(ThingsOutOfSync.class, this::updateThings)
            .match(UpdateThing.class, this::updateThing)
            .match(DistributedPubSubMediator.SubscribeAck.class, subscribeAck ->
                    log.debug("Got <{}>", subscribeAck))
            .matchAny(m -> {
                log.warning("Unknown message: {}", m);
                unhandled(m);
            }).build();
}
 
Example #2
Source File: S3Backup.java    From ts-reaktive with MIT License 6 votes vote down vote up
private Receive startBackup(long offset) {
    query
        .eventsByTag(tag, NoOffset.getInstance())
        // create backups of max [N] elements, or at least every [T] on activity
        // FIXME write a stage that, instead of buffering each chunk into memory, creates sub-streams instead.
        .groupedWithin(eventChunkSize, eventChunkDuration)
        .filter(list -> list.size() > 0)
        .mapAsync(4, list -> s3.store(tag, Vector.ofAll(list)).thenApply(done -> list.get(list.size() - 1).offset()))
        .runWith(Sink.actorRefWithAck(self(), "init", "ack", "done", Failure::new), materializer);
    
    return ReceiveBuilder.create()
        .matchEquals("init", msg -> sender().tell("ack", self()))
        .match(Long.class, l -> pipe(s3.saveOffset(l).thenApply(done -> "ack"), context().dispatcher()).to(sender()))
        .match(Failure.class, msg -> {
            log.error("Stream failed, rethrowing", msg.cause());
            throw new RuntimeException(msg.cause());
        })
        .matchEquals("done", msg -> { throw new IllegalStateException("eventsByTag completed, this should not happen. Killing actor, hoping for restart"); })
        .build();
}
 
Example #3
Source File: ReconnectActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(RetrieveConnectionStatusResponse.class,
                    command -> log.debug("Retrieved connection status response for connection <{}> with status: {}",
                            command.getConnectionEntityId(), command.getConnectionStatus()))
            .match(ConnectionNotAccessibleException.class,
                    exception -> log.debug("Received ConnectionNotAccessibleException for connection <{}> " +
                                    "(most likely, the connection was deleted): {}",
                            exception.getDittoHeaders().getCorrelationId().orElse("<unknown>"),
                            exception.getMessage()))
            .match(DittoRuntimeException.class,
                    exception -> log.debug("Received {} for connection {} : {}",
                            exception.getClass().getSimpleName(),
                            exception.getDittoHeaders().getCorrelationId().orElse("<unknown>"),
                            exception.getMessage()))
            .matchEquals(ReconnectMessages.START_RECONNECT, msg -> handleStartReconnect())
            .matchEquals(ReconnectMessages.END_RECONNECT, msg -> handleEndReconnect())
            .matchAny(m -> {
                log.warning("Unknown message: {}", m);
                unhandled(m);
            }).build();
}
 
Example #4
Source File: HotswapClientActor.java    From learning-akka with Apache License 2.0 6 votes vote down vote up
public HotswapClientActor(String dbPath) {
    remoteDb = context().actorSelection(dbPath);

    disconnected = ReceiveBuilder.
            match(Request.class, x -> { //can't handle until we know remote system is responding
                remoteDb.tell(new Connected(), self()); //see if the remote actor is up
                stash(); //stash message for later
            }).
            match(Connected.class, x -> { // Okay to start processing messages.
                context().become(online);
                unstash();
            }).build();

    online = ReceiveBuilder.
                    match(Request.class, x -> {
                        remoteDb.forward(x, context()); //forward instead of tell to preserve sender
                    }).
                    build();

    receive(disconnected); //initial state.
}
 
Example #5
Source File: AbstractShardedPersistenceActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Receive createReceiveRecover() {
    // defines how state is updated during recovery
    return handleEvents.orElse(ReceiveBuilder.create()
            // # Snapshot handling
            .match(SnapshotOffer.class, ss -> {
                log.debug("Got SnapshotOffer: {}", ss);
                recoverFromSnapshotOffer(ss);
            })
            // # Recovery timeout
            .match(RecoveryTimedOut.class, rto ->
                    log.warning("RecoveryTimeout occurred during recovery for entity with ID {}", entityId)
            )
            // # Recovery handling
            .match(RecoveryCompleted.class, this::recoveryCompleted)
            .matchAny(m -> log.warning("Unknown recover message: {}", m))
            .build());
}
 
Example #6
Source File: MessageMappingProcessorActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void preEnhancement(final ReceiveBuilder receiveBuilder) {
    receiveBuilder
            // Incoming messages are handled in a separate stream parallelized by this actor's own dispatcher
            .match(ExternalMessage.class, this::handleInboundMessage)
            .match(Acknowledgement.class, acknowledgement ->
                    potentiallyForwardToAckregator(acknowledgement, () ->
                            handleNotExpectedAcknowledgement(acknowledgement))
            )
            .match(ThingCommandResponse.class, response -> {
                final ActorContext context = getContext();
                potentiallyForwardToAckregator(response,
                        () -> handleCommandResponse(response, null, context.getSender()));
            })
            // Outgoing responses and signals go through the signal enrichment stream
            .match(CommandResponse.class, response -> handleCommandResponse(response, null, getSender()))
            .match(Signal.class, signal -> handleSignal(signal, getSender()))
            .match(Status.Failure.class, f -> logger.warning("Got failure with cause {}: {}",
                    f.cause().getClass().getSimpleName(), f.cause().getMessage()));
}
 
Example #7
Source File: AbstractShardedPersistenceActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Start handling messages for an existing entity and schedule maintenance messages to self.
 */
protected void becomeCreatedHandler() {
    final CommandStrategy<C, S, K, Result<E>> commandStrategy = getCreatedStrategy();

    final Receive receive = handleCleanups.orElse(ReceiveBuilder.create()
            .match(commandStrategy.getMatchingClass(), commandStrategy::isDefined, this::handleByCommandStrategy)
            .match(CheckForActivity.class, this::checkForActivity)
            .matchEquals(Control.TAKE_SNAPSHOT, this::takeSnapshotByInterval)
            .match(SaveSnapshotSuccess.class, this::saveSnapshotSuccess)
            .match(SaveSnapshotFailure.class, this::saveSnapshotFailure)
            .matchAny(this::matchAnyAfterInitialization)
            .build());

    getContext().become(receive);

    scheduleCheckForActivity(getActivityCheckConfig().getInactiveInterval());
    scheduleSnapshot();
}
 
Example #8
Source File: ThingsAggregatorProxyActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(RetrieveThings.class, rt -> handleRetrieveThings(rt, rt))
            .match(SudoRetrieveThings.class, srt -> handleSudoRetrieveThings(srt, srt))
            .match(DistributedPubSubMediator.Send.class, send -> {
                final Object msg = send.msg();
                if (msg instanceof RetrieveThings) {
                    handleRetrieveThings((RetrieveThings) msg, send);
                } else if (msg instanceof SudoRetrieveThings) {
                    handleSudoRetrieveThings((SudoRetrieveThings) msg, send);
                } else {
                    log.warning("Got unknown message: {}", send);
                    unhandled(send);
                }
            })
            .matchAny(m -> {
                log.warning("Got unknown message: {}", m);
                unhandled(m);
            })
            .build();
}
 
Example #9
Source File: S3Restore.java    From ts-reaktive with MIT License 6 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
        .matchEquals("init", msg -> sender().tell("ack", self()))
        .match(Long.class, (Long o) -> {
            log.debug("Persisting {}", o);
            persist(o, done -> {
                offset = o;
                if (lastSequenceNr() > 1) {
                    deleteMessages(lastSequenceNr() - 1);
                }
                context().system().scheduler().scheduleOnce(updateAccuracy, sender(), "ack", context().dispatcher(), self());
            });
        })
        .match(Failure.class, msg -> {
            log.error("Stream failed, rethrowing", msg.cause());
            throw new RuntimeException(msg.cause());
        })
        .matchEquals("done", msg -> {
            log.debug("Completed, with offset now {}", offset);
            context().stop(self());
        })
        .build();
}
 
Example #10
Source File: SubscriptionActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Receive createZombieBehavior() {
    return ReceiveBuilder.create()
            .match(RequestFromSubscription.class, requestSubscription -> {
                log.withCorrelationId(requestSubscription)
                        .info("Rejecting RequestSubscription[demand={}] as zombie",
                                requestSubscription.getDemand());
                final String errorMessage =
                        "This subscription is considered cancelled. No more messages are processed.";
                final SubscriptionFailed subscriptionFailed = SubscriptionFailed.of(
                        getSubscriptionId(),
                        SubscriptionProtocolErrorException.newBuilder()
                                .message(errorMessage)
                                .build(),
                        requestSubscription.getDittoHeaders()
                );
                getSender().tell(subscriptionFailed, ActorRef.noSender());
            })
            .matchAny(message -> log.info("Ignoring as zombie: <{}>", message))
            .build();
}
 
Example #11
Source File: MessageAggregator.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .matchEquals(TIMEOUT, this::handleTimeout)
            .matchAny(firstMessage -> {
                sender = getSender();
                log.debug("MessageAggregator: Forwarding <{}> to <{}> on behalf of <{}>",
                        firstMessage, initialReceiver, sender);
                initialReceiver.tell(firstMessage, getSelf());
                if (expectedMessages > 0) {
                    getContext().become(listeningBehavior());
                } else {
                    reportAndStop();
                }
            })
            .build();
}
 
Example #12
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Receive getAwaitThingCommandResponseBehavior(final DittoHeaders requestDittoHeaders,
        final AcknowledgementAggregator ackregator,
        final Supplier<DittoRuntimeException> timeoutExceptionSupplier) {

    final Receive awaitThingCommandResponseBehavior = ReceiveBuilder.create()
            .match(ThingModifyCommandResponse.class, commandResponse -> {
                logger.withCorrelationId(commandResponse).debug("Got <{}>.", commandResponse.getType());
                rememberResponseLocationUri(commandResponse);

                ThingModifyCommandResponse<?> enhancedResponse = commandResponse;
                final DittoHeaders dittoHeaders = commandResponse.getDittoHeaders();
                if (null != responseLocationUri) {
                    final Location location = Location.create(responseLocationUri);
                    enhancedResponse = commandResponse.setDittoHeaders(dittoHeaders.toBuilder()
                            .putHeader(location.lowercaseName(), location.value())
                            .build());
                }
                ackregator.addReceivedAcknowledgment(getAcknowledgement(enhancedResponse));
                potentiallyCompleteAcknowledgements(dittoHeaders, ackregator);
            })
            .match(ThingErrorResponse.class, errorResponse -> {
                logger.withCorrelationId(errorResponse).debug("Got error response <{}>.", errorResponse.getType());
                ackregator.addReceivedAcknowledgment(getAcknowledgement(errorResponse));
                potentiallyCompleteAcknowledgements(errorResponse.getDittoHeaders(), ackregator);
            })
            .match(Acknowledgement.class, ack -> {
                final Acknowledgement adjustedAck = ack.setDittoHeaders(getExternalHeaders(ack.getDittoHeaders()));
                ackregator.addReceivedAcknowledgment(adjustedAck);
                potentiallyCompleteAcknowledgements(requestDittoHeaders, ackregator);
            })
            .match(ReceiveTimeout.class, receiveTimeout -> {
                final DittoHeaders externalHeaders = getExternalHeaders(requestDittoHeaders);
                completeAcknowledgements(externalHeaders, ackregator);
            })
            .build();

    return awaitThingCommandResponseBehavior.orElse(getResponseAwaitingBehavior(timeoutExceptionSupplier));
}
 
Example #13
Source File: ConciergeForwarderActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(Signal.class, signal -> forward(signal, getContext()))
            .match(DistributedPubSubMediator.SubscribeAck.class, subscribeAck ->
                    log.debug("Successfully subscribed to distributed pub/sub on topic '{}'",
                            subscribeAck.subscribe().topic())
            )
            .matchAny(m -> log.warning("Got unknown message: {}", m))
            .build();
}
 
Example #14
Source File: AbstractThingProxyActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void addCommandBehaviour(final ReceiveBuilder receiveBuilder) {
    receiveBuilder
            /* DevOps Commands */
            .match(DevOpsCommand.class, command -> {
                LogUtil.enhanceLogWithCorrelationId(getLogger(), command);
                getLogger().debug("Got 'DevOpsCommand' message <{}>, forwarding to local devOpsCommandsActor",
                        command.getType());
                devOpsCommandsActor.forward(command, getContext());
            })
            /* handle RetrieveThings in a special way */
            .match(RetrieveThings.class, rt -> aggregatorProxyActor.forward(rt, getContext()))
            .match(SudoRetrieveThings.class, srt -> aggregatorProxyActor.forward(srt, getContext()))

            .match(QueryThings.class, qt -> {
                final ActorRef responseActor = getContext().actorOf(
                        QueryThingsPerRequestActor.props(qt, aggregatorProxyActor, getSender(),
                                pubSubMediator));
                conciergeForwarder.tell(qt, responseActor);
            })

            /* send all other Commands to Concierge Service */
            .match(Command.class, this::forwardToConciergeService)

            /* Live Signals */
            .match(Signal.class, ProxyActor::isLiveSignal, this::forwardToConciergeService);
}
 
Example #15
Source File: ReplicatedActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
protected Receive master() {
    return ReceiveBuilder.create()
        .match(Query.EventEnvelope.class, e -> {
            log.error("Actor is not in slave mode, but was sent an EventEnvelope: {} from {} \n"
                + "Possibly the same persistenceId was created on several datacenters independently. That will not end well.\n"
                + "The incoming event has been ignored. The proper cause of action is to delete either this or the other aggregate.", e, sender());
            sender().tell(new Failure(new IllegalStateException("Actor is not in slave mode, but was sent an EventEnvelope. "
                + "Possibly the same persistenceId was created on several datacenters independently. That will not end well.")), self());
        })
        .build()
        .orElse(createReceive());    	
}
 
Example #16
Source File: MockConciergeForwarderActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(ActorRef.class, actorRef -> {
                recipient = actorRef;
                getSender().tell(actorRef, getSelf());
            })
            .matchAny(message -> {
                if (recipient != null) {
                    recipient.forward(message, getContext());
                }
            })
            .build();
}
 
Example #17
Source File: JavaPongActor.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
public PartialFunction receive() {
    return ReceiveBuilder.
            matchEquals("Ping", s ->
                            sender().tell("Pong", ActorRef.noSender())).
            matchAny(x ->
                    sender().tell(
                            new Status.Failure(new Exception("unknown message")), self()
                    )).
            build();
}
 
Example #18
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public AbstractActor.Receive createReceive() {
    return ReceiveBuilder.create()
            .match(Status.Failure.class, failure -> {
                Throwable cause = failure.cause();
                if (cause instanceof JsonRuntimeException) {
                    // wrap JsonRuntimeExceptions
                    cause = new DittoJsonException((RuntimeException) cause);
                }
                if (cause instanceof DittoRuntimeException) {
                    handleDittoRuntimeException((DittoRuntimeException) cause);
                } else if (cause instanceof EntityStreamSizeException) {
                    logger.warning("Got EntityStreamSizeException when a 'Command' was expected which means that" +
                            " the max. allowed http payload size configured in Akka was overstepped in this" +
                            " request.");
                    completeWithResult(
                            HttpResponse.create().withStatus(HttpStatusCode.REQUEST_ENTITY_TOO_LARGE.toInt()));
                } else {
                    logger.error(cause, "Got unknown Status.Failure when a 'Command' was expected.");
                    completeWithResult(
                            HttpResponse.create().withStatus(HttpStatusCode.INTERNAL_SERVER_ERROR.toInt()));
                }
            })
            .match(Whoami.class, this::handleWhoami)
            .match(DittoRuntimeException.class, this::handleDittoRuntimeException)
            .match(ReceiveTimeout.class,
                    receiveTimeout -> handleDittoRuntimeException(GatewayServiceUnavailableException.newBuilder()
                            .dittoHeaders(DittoHeaders.empty())
                            .build()))
            .match(Command.class, command -> !isResponseRequired(command), this::handleCommandWithoutResponse)
            .match(ThingModifyCommand.class, this::handleThingModifyCommand)
            .match(MessageCommand.class, this::handleMessageCommand)
            .match(Command.class, command -> handleCommandWithResponse(command,
                    getResponseAwaitingBehavior(getTimeoutExceptionSupplier(command))))
            .matchAny(m -> {
                logger.warning("Got unknown message, expected a 'Command': {}", m);
                completeWithResult(HttpResponse.create().withStatus(HttpStatusCode.INTERNAL_SERVER_ERROR.toInt()));
            })
            .build();
}
 
Example #19
Source File: RabbitMQConsumerActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(Delivery.class, this::handleDelivery)
            .match(ResourceStatus.class, this::handleAddressStatus)
            .match(RetrieveAddressStatus.class, ram -> getSender().tell(getCurrentSourceStatus(), getSelf()))
            .matchAny(m -> {
                log.warning("Unknown message: {}", m);
                unhandled(m);
            }).build();
}
 
Example #20
Source File: AbstractGraphActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    final SourceQueueWithComplete<T> sourceQueue = getSourceQueue(materializer);

    final ReceiveBuilder receiveBuilder = ReceiveBuilder.create();
    preEnhancement(receiveBuilder);
    return receiveBuilder
            .match(DittoRuntimeException.class, this::handleDittoRuntimeException)
            .match(matchClass, match -> handleMatched(sourceQueue, match))
            .match(Throwable.class, this::handleUnknownThrowable)
            .matchAny(message -> logger.warning("Received unknown message <{}>.", message))
            .build();
}
 
Example #21
Source File: AbstractPersistenceOperationsActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(PurgeNamespace.class, this::purgeNamespace)
            .match(PurgeEntities.class, this::purgeEntities)
            .match(DistributedPubSubMediator.SubscribeAck.class, this::handleSubscribeAck)
            .matchAny(message -> logger.warning("unhandled: <{}>", message))
            .build();
}
 
Example #22
Source File: AbstractBackgroundStreamingActorWithConfigWithStatusReport.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Receive sleeping() {
    final ReceiveBuilder sleepingReceiveBuilder = ReceiveBuilder.create();
    preEnhanceSleepingBehavior(sleepingReceiveBuilder);
    return sleepingReceiveBuilder.match(WokeUp.class, this::wokeUp)
            .match(Event.class, this::addCustomEventToLog)
            .match(RetrieveHealth.class, this::retrieveHealth)
            .match(Shutdown.class, this::shutdownStream)
            .build()
            .orElse(retrieveConfigBehavior())
            .orElse(modifyConfigBehavior());
}
 
Example #23
Source File: Chatroom.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
@Override
public PartialFunction<Object, BoxedUnit> receive() {
    return ReceiveBuilder.
            match(Messages.JoinChatroom.class, x -> sender().tell(joinChatroom(x), self())).
            match(Messages.PostToChatroom.class, msg -> joinedUsers.forEach(x -> x.actor.tell(msg, self()))).
            matchAny(o -> System.out.println("received unknown message")).build();
}
 
Example #24
Source File: StatusSupplierActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(SimpleCommand.class, command -> SIMPLE_COMMAND_RETRIEVE_STATUS.equals(command.getCommandName()),
                    command -> {
                        log.info("Sending the status of this system as requested..");
                        final SimpleCommandResponse response = SimpleCommandResponse.of(
                                command.getCorrelationId().orElse("?"), Status.provideStaticStatus());
                        getSender().tell(response, getSelf());
                    })
            .match(SimpleCommand.class, command -> SIMPLE_COMMAND_RETRIEVE_HEALTH.equals(command.getCommandName()),
                    command -> {
                        final ActorRef sender = getSender();
                        final ActorRef self = getSelf();
                        PatternsCS.ask(getContext().system().actorSelection("/user/" + rootActorName + "/" +
                                        AbstractHealthCheckingActor.ACTOR_NAME),
                                RetrieveHealth.newInstance(), Timeout.apply(2, TimeUnit.SECONDS))
                                .thenAccept(health -> {
                                    log.info("Sending the health of this system as requested: {}", health);
                                    sender.tell(health, self);
                                })
                                .exceptionally(throwable -> {
                                    sender.tell(
                                            StatusInfo.fromStatus(StatusInfo.Status.DOWN, throwable.getMessage()),
                                            self);
                                    return null;
                                });
                    })
            .match(SimpleCommand.class, command -> {
                log.warning("Unsupported SimpleCommand with name '{}': {}", command.getCommandName(),
                        command);
            })
            .matchAny(m -> {
                log.warning("Unknown message: {}", m);
                unhandled(m);
            }).build();
}
 
Example #25
Source File: RabbitMQPublisherActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void preEnhancement(final ReceiveBuilder receiveBuilder) {
    receiveBuilder
            .match(ChannelCreated.class, channelCreated -> {
                this.channelActor = channelCreated.channel();

                final Set<String> exchanges = targets.stream()
                        .map(t -> toPublishTarget(t.getAddress()))
                        .map(RabbitMQTarget::getExchange)
                        .collect(Collectors.toSet());
                final ChannelMessage channelMessage = ChannelMessage.apply(channel -> {
                    exchanges.forEach(exchange -> {
                        log.debug("Checking for existence of exchange <{}>", exchange);
                        try {
                            channel.exchangeDeclarePassive(exchange);
                        } catch (final IOException e) {
                            log.warning("Failed to declare exchange <{}> passively", exchange);
                            targets.stream()
                                    .filter(t ->
                                            exchange.equals(toPublishTarget(t.getAddress()).getExchange())
                                    )
                                    .findFirst()
                                    .ifPresent(target ->
                                            resourceStatusMap.put(
                                                    target,
                                                    ConnectivityModelFactory.newTargetStatus(
                                                            InstanceIdentifierSupplier.getInstance().get(),
                                                            ConnectivityStatus.FAILED,
                                                            target.getAddress(),
                                                            "Exchange '" + exchange + "' was missing at " +
                                                                    Instant.now())));
                        }
                    });
                    return null;
                }, false);
                channelCreated.channel().tell(channelMessage, getSelf());
            });
}
 
Example #26
Source File: SubscriptionManager.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(RequestFromSubscription.class, this::requestSubscription)
            .match(CreateSubscription.class, this::createSubscription)
            .match(CancelSubscription.class, this::cancelSubscription)
            .build();
}
 
Example #27
Source File: AbstractShardedPersistenceActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Instantiate the actor.
 *
 * @param entityId the entity ID.
 * @param snapshotAdapter the entity's snapshot adapter.
 */
protected AbstractShardedPersistenceActor(final I entityId, final SnapshotAdapter<S> snapshotAdapter) {
    this.entityId = entityId;
    this.snapshotAdapter = snapshotAdapter;
    entity = null;

    lastSnapshotRevision = 0L;
    confirmedSnapshotRevision = 0L;

    handleEvents = ReceiveBuilder.create()
            .match(getEventClass(), event -> entity = getEventStrategy().handle(event, entity, getRevisionNumber()))
            .build();

    handleCleanups = super.createReceive();
}
 
Example #28
Source File: AbstractPersistenceSupervisor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void becomeCorrupted() {
    getContext().setReceiveTimeout(getCorruptedReceiveTimeout());
    getContext().become(ReceiveBuilder.create()
            .match(ReceiveTimeout.class, timeout -> passivate(Control.PASSIVATE))
            .matchAny(this::replyUnavailableException)
            .build());
}
 
Example #29
Source File: SafeRecovery.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a Receive for recovery such that exceptions are logged as warnings
 * and not thrown. Recovery messages causing exceptions have no effect.
 *
 * @param log The Akka logger to write warnings to.
 * @param receiveRecover The Receive to wrap around.
 *
 * @return the created Receive.
 */
public static AbstractActor.Receive wrapReceive(
        @Nullable final DiagnosticLoggingAdapter log,
        @Nonnull final AbstractActor.Receive receiveRecover) {
    return ReceiveBuilder.create().matchAny(x -> {
        try {
            receiveRecover.onMessage().apply(x);
        } catch (final Exception error) {
            if (log != null) {
                log.warning("Failed to recover from the following message (it is ignored): {}", x);
            }
        }
    }).build();
}
 
Example #30
Source File: EventAndResponsePublisher.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Receive connected(final CharSequence connectionCorrelationId) {
    unstashAll();

    return ReceiveBuilder.create()
            .match(SessionedJsonifiable.class, j -> buffer.size() >= backpressureBufferSize,
                    this::handleBackpressureFor)
            .match(SessionedJsonifiable.class, jsonifiable -> {
                if (buffer.isEmpty() && totalDemand() > 0) {
                    onNext(jsonifiable);
                } else {
                    buffer.add(jsonifiable);
                    deliverBuf();
                }
            })
            .match(CloseStreamExceptionally.class, closeStreamExceptionally -> {
                final DittoRuntimeException reason = closeStreamExceptionally.getReason();
                logger.withCorrelationId(closeStreamExceptionally.getConnectionCorrelationId())
                        .info("Closing stream exceptionally because of <{}>.", reason);
                if (0 < totalDemand()) {
                    onNext(SessionedJsonifiable.error(reason));
                }
                onErrorThenStop(reason);
            })
            .match(ActorPublisherMessage.Request.class, request -> {
                logger.withCorrelationId(connectionCorrelationId).debug("Got new demand: {}", request);
                deliverBuf();
            })
            .match(ActorPublisherMessage.Cancel.class, cancel -> getContext().stop(getSelf()))
            .matchAny(any -> logger.withCorrelationId(connectionCorrelationId)
                    .warning("Got unknown message during connected phase: '{}'", any))
            .build();
}