akka.actor.ReceiveTimeout Java Examples

The following examples show how to use akka.actor.ReceiveTimeout. 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: DevOpsCommandsActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(CommandResponse.class, this::handleCommandResponse)
            .match(DittoRuntimeException.class, this::handleDittoRuntimeException)
            .match(ReceiveTimeout.class, receiveTimeout -> {
                LogUtil.enhanceLogWithCorrelationId(log, getSelf().path().name());
                log.info("Got ReceiveTimeout, answering with all aggregated DevOpsCommandResponses and " +
                        "stopping ourselves ...");
                sendCommandResponsesAndStop();
            })
            .matchAny(m -> {
                LogUtil.enhanceLogWithCorrelationId(log, getSelf().path().name());
                log.warning(UNKNOWN_MESSAGE_TEMPLATE, m);
                unhandled(m);
            }).build();
}
 
Example #2
Source File: SshClientActor.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Object message) throws Throwable {
    if (message instanceof ReceiveTimeout) {
        sshClientService.onSessionCreateTimeout(clientId);
        self().tell(PoisonPill.getInstance(), self());
    } else if (message instanceof SessionCreateResponse) {
        SessionCreateResponse sessionCreateResponse = (SessionCreateResponse)message;
        LOG.info("looking for session actor: {}", sessionCreateResponse.getSessionActorAddress());
        Future<ActorRef> actorRefFuture = context().system()
                .actorSelection(sessionCreateResponse.getSessionActorAddress()).resolveOne(Timeout.apply(2, TimeUnit.SECONDS));
        sshSessionActor = Await.result(actorRefFuture, Duration.apply(2, TimeUnit.SECONDS));
        sshClientService.onSessionCreateReply(sessionCreateResponse.getClientId(), sessionCreateResponse.getSessionId(), sshSessionActor, sessionCreateResponse.getSessionActorAddress());
    } else if (message instanceof SessionDataResponse) {
        SessionDataResponse sessionDataResponse = (SessionDataResponse)message;
        sshClientService.onSessionDataReceived(clientId, sessionDataResponse);
    } else if (message instanceof SessionCloseResponse) {
        SessionCloseResponse sessionCloseResponse = (SessionCloseResponse)message;
        sshClientService.onCloseSessionResponse(clientId, sessionCloseResponse);
        self().tell(PoisonPill.getInstance(), self());
    } else {
        LOG.info("onReceive: {}", message.getClass().getName());
    }
}
 
Example #3
Source File: ThrottleActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder()
        .match(String.class, key -> handleRequest())
        .match(ReceiveTimeout.class, msg -> passivate())
        .match(Stop.class, msg -> context().stop(self()))
        .build();
}
 
Example #4
Source File: AbstractStatefulPersistentActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
        .match(commandType, msg -> canHandleCommand(msg) && idle, msg -> {
            handleCommand(msg);
            idle = false;
        })
        .match(commandType, msg -> canHandleCommand(msg), msg -> {
            // we're awaiting results from another command, so let's wait with this one
            stash();
        })
        .match(CommandHandler.Results.class, msg -> idle, msg -> {
            // If results happen to come in while we're idle, let's accept them anyways
            log.warning("Received unexpected Results object when idle, but accepting anyways: {}", msg);
            handleResults((CommandHandler.Results<E>) msg);
        })
        .match(CommandHandler.Results.class, msg -> {
            handleResults((CommandHandler.Results<E>) msg);
            unstashAll();
            idle = true;
        })
        .match(Failure.class, f -> {
            log.error(f.cause(), "A future piped to this actor has failed, rethrowing.");
            throw (f.cause() instanceof Exception) ? Exception.class.cast(f.cause()) : new Exception(f.cause());
        })
        .matchEquals(ReceiveTimeout.getInstance(), msg -> passivate())
        .match(Stop.class, msg -> context().stop(self()))
        .build();
}
 
Example #5
Source File: RetrieveConnectionStatusAggregatorActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder()
            .match(ResourceStatus.class, this::handleResourceStatus)
            .match(ReceiveTimeout.class, receiveTimeout -> this.handleReceiveTimeout())
            .matchAny(any -> log.info("Cannot handle {}", any.getClass())).build();
}
 
Example #6
Source File: RetrieveConnectionMetricsAggregatorActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder()
            .match(RetrieveConnectionMetricsResponse.class, this::handleRetrieveConnectionMetricsResponse)
            .match(ReceiveTimeout.class, receiveTimeout -> this.handleReceiveTimeout())
            .matchAny(any -> log.info("Cannot handle {}", any.getClass())).build();
}
 
Example #7
Source File: RetrieveConnectionLogsAggregatorActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder()
            .match(RetrieveConnectionLogsResponse.class, this::handleRetrieveConnectionLogsResponse)
            .match(ReceiveTimeout.class, receiveTimeout -> this.handleReceiveTimeout())
            .matchAny(any -> log.info("Cannot handle {}", any.getClass())).build();
}
 
Example #8
Source File: ThingUpdater.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return shutdownBehaviour.createReceive()
            .match(ThingEvent.class, this::processThingEvent)
            .match(ThingTag.class, this::processThingTag)
            .match(PolicyReferenceTag.class, this::processPolicyReferenceTag)
            .match(UpdateThing.class, this::updateThing)
            .match(UpdateThingResponse.class, this::processUpdateThingResponse)
            .match(ReceiveTimeout.class, this::stopThisActor)
            .matchAny(m -> {
                log.warning("Unknown message in 'eventProcessing' behavior: {}", m);
                unhandled(m);
            })
            .build();
}
 
Example #9
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void handleReceiveTimeout(final Supplier<DittoRuntimeException> timeoutExceptionSupplier) {
    final DittoRuntimeException timeoutException = timeoutExceptionSupplier.get();
    logger.withCorrelationId(timeoutException)
            .info("Got <{}> when a response was expected after timeout <{}>.", ReceiveTimeout.class.getSimpleName(),
                    getContext().getReceiveTimeout());
    handleDittoRuntimeException(timeoutException);
}
 
Example #10
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 #11
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 #12
Source File: AcknowledgementForwarderActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder()
            .match(Acknowledgement.class, this::handleAcknowledgement)
            .match(ReceiveTimeout.class, this::handleReceiveTimeout)
            .matchAny(m -> log.warning("Received unexpected message: <{}>", m))
            .build();
}
 
Example #13
Source File: AcknowledgementAggregatorActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder()
            .match(ThingCommandResponse.class, this::handleThingCommandResponse)
            .match(Acknowledgement.class, this::handleAcknowledgement)
            .match(ReceiveTimeout.class, this::handleReceiveTimeout)
            .matchAny(m -> log.warning("Received unexpected message: <{}>", m))
            .build();
}
 
Example #14
Source File: SubscriptionActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void idleTimeout(final ReceiveTimeout receiveTimeout) {
    // usually a user error
    log.info("Stopping due to idle timeout");
    final String subscriptionId = getSubscriptionId();
    final SubscriptionTimeoutException error = SubscriptionTimeoutException.of(subscriptionId, dittoHeaders);
    final SubscriptionFailed subscriptionFailed = SubscriptionFailed.of(subscriptionId, error, dittoHeaders);
    if (subscription == null) {
        sender.tell(getSubscriptionCreated(), ActorRef.noSender());
    }
    sender.tell(subscriptionFailed, ActorRef.noSender());
    becomeZombie();
}
 
Example #15
Source File: SubscriptionActor.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(CancelSubscription.class, this::cancelSubscription)
            .match(SubscriptionHasNextPage.class, this::subscriptionHasNext)
            .match(SubscriptionComplete.class, this::subscriptionComplete)
            .match(SubscriptionFailed.class, this::subscriptionFailed)
            .match(Subscription.class, this::onSubscribe)
            .matchEquals(ReceiveTimeout.getInstance(), this::idleTimeout)
            .build();
}
 
Example #16
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 #17
Source File: AcknowledgementForwarderActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void handleReceiveTimeout(final ReceiveTimeout receiveTimeout) {
    log.withCorrelationId(correlationId)
            .debug("Timed out waiting for requested acknowledgements, stopping myself ...");
    getContext().stop(getSelf());
}
 
Example #18
Source File: QueryThingsPerRequestActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder()
            .match(ReceiveTimeout.class, receiveTimeout -> {
                log.debug("Got ReceiveTimeout");
                stopMyself();
            })
            .match(QueryThingsResponse.class, qtr -> {
                LogUtil.enhanceLogWithCorrelationId(log, qtr);
                queryThingsResponse = qtr;

                log.debug("Received QueryThingsResponse: {}", qtr);

                queryThingsResponseThingIds = qtr.getSearchResult()
                        .stream()
                        .map(val -> val.asObject().getValue(Thing.JsonFields.ID).orElse(null))
                        .map(ThingId::of)
                        .collect(Collectors.toList());

                if (queryThingsResponseThingIds.isEmpty()) {
                    // shortcut - for no search results we don't have to lookup the things
                    originatingSender.tell(qtr, getSelf());
                    stopMyself();
                } else {
                    final Optional<JsonFieldSelector> selectedFieldsWithThingId = getSelectedFieldsWithThingId();
                    final RetrieveThings retrieveThings = RetrieveThings.getBuilder(queryThingsResponseThingIds)
                            .dittoHeaders(qtr.getDittoHeaders())
                            .selectedFields(selectedFieldsWithThingId)
                            .build();
                    // delegate to the ThingsAggregatorProxyActor which receives the results via a cluster stream:
                    aggregatorProxyActor.tell(retrieveThings, getSelf());
                }
            })
            .match(RetrieveThingsResponse.class, rtr -> {
                LogUtil.enhanceLogWithCorrelationId(log, rtr);
                log.debug("Received RetrieveThingsResponse: {}", rtr);

                if (queryThingsResponse != null) {
                    final JsonArray rtrEntity = rtr.getEntity(rtr.getImplementedSchemaVersion()).asArray();
                    final JsonArray retrievedEntitiesWithFieldSelection = getEntitiesWithSelectedFields(rtrEntity);
                    final SearchResult resultWithRetrievedItems = SearchModelFactory.newSearchResultBuilder()
                            .addAll(retrievedEntitiesWithFieldSelection)
                            .nextPageOffset(queryThingsResponse.getSearchResult().getNextPageOffset().orElse(null))
                            .cursor(queryThingsResponse.getSearchResult().getCursor().orElse(null))
                            .build();
                    final QueryThingsResponse theQueryThingsResponse =
                            QueryThingsResponse.of(resultWithRetrievedItems, rtr.getDittoHeaders());
                    originatingSender.tell(theQueryThingsResponse, getSelf());
                    notifyOutOfSyncThings(rtrEntity);
                } else {
                    log.warning("Did not receive a QueryThingsResponse when a RetrieveThingsResponse occurred: {}",
                            rtr);
                }

                stopMyself();
            })
            .matchAny(any -> {
                // all other messages (e.g. DittoRuntimeExceptions) are directly returned to the sender:
                originatingSender.tell(any, getSender());
                stopMyself();
            })
            .build();
}
 
Example #19
Source File: ThingUpdater.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void stopThisActor(final ReceiveTimeout receiveTimeout) {
    log.debug("stopping ThingUpdater <{}> due to <{}>", thingId, receiveTimeout);
    getContext().getParent().tell(new ShardRegion.Passivate(PoisonPill.getInstance()), getSelf());
}
 
Example #20
Source File: AcknowledgementAggregatorActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void handleReceiveTimeout(final ReceiveTimeout receiveTimeout) {
    log.withCorrelationId(correlationId).info("Timed out waiting for all requested acknowledgements, " +
            "completing Acknowledgements with timeouts...");
    completeAcknowledgements(null, requestCommandHeaders);
}
 
Example #21
Source File: MaterializerActor.java    From ts-reaktive with MIT License 4 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
        .match(ReceiveTimeout.class, msg -> {
            recordOffsetMetric();
        })
        .match(CancelReimport.class, msg -> {
            cancelReimport();
        })
        .match(Reimport.class, msg -> {
            reimport(msg.entityIds);
        })
        .match(QueryProgress.class, msg -> {
            sendProgress();
        })
        .matchEquals("reimportComplete", msg -> {
            log.info("Re-import completed.");
            this.ongoingReimport = none();
            reimportProgress.set(null);
        })
        .match(StartWorker.class, msg -> {
            materializeEvents(msg.worker);
        })
        .match(CreateWorker.class, msg -> {
            createWorker(msg.timestamp, msg.endTimestamp);
        })
        .matchEquals("init", msg -> getSender().tell("ack", self()))
        .match(WorkerProgress.class, p -> {
            persist(workers.onWorkerProgress(p.worker, p.timestamp), evt -> {
                applyEvent(evt);
                context().system().scheduler().scheduleOnce(
                    updateAccuracy, sender(), "ack", context().dispatcher(), self());
                if ((lastSequenceNr() > 1) && ((lastSequenceNr() % deleteMessagesAfter) == 0)) {
                    log.debug("Deleting up to {}", lastSequenceNr() - 1);
                    deleteMessages(lastSequenceNr() - 1);
                }
            });
        })
        .match(DeleteMessagesSuccess.class, msg -> {
            log.debug("Delete messages completed.");
        })
        .match(DeleteMessagesFailure.class, msg -> {
            log.error(msg.cause(), "Delete messages failed at offsets " + workers
                + ", rethrowing");
            throw (Exception) msg.cause();
        })
        .match(WorkerFailure.class, failure -> {
            metrics.getStreams().decrement();
            log.error(failure.cause, "Stream " + failure.worker + " failed at offset "
                + workers + ", restarting in " + restartDelay);
            onWorkerStopped(failure.worker);
        })
        .match(WorkerDone.class, msg -> {
            metrics.getStreams().decrement();
            log.debug("Completed {}, now offset is: {}", msg.worker, workers);
            onWorkerStopped(msg.worker);
        })
        .matchEquals("reset", msg -> { // for compatibility
            reset();
        })
        .match(Reset.class, msg -> {
            reset();
        })
        .build();
}