Java Code Examples for akka.actor.Status#Failure

The following examples show how to use akka.actor.Status#Failure . 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: BaseClientActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Add meaningful message to status for reporting.
 *
 * @param status status to report.
 * @return status with meaningful message.
 */
private Status.Status getStatusToReport(final Status.Status status, final DittoHeaders dittoHeaders) {
    final Status.Status answerToPublish;
    if (status instanceof Status.Failure) {
        final Status.Failure failure = (Status.Failure) status;
        if (!(failure.cause() instanceof DittoRuntimeException)) {
            final DittoRuntimeException error = ConnectionFailedException.newBuilder(connectionId())
                    .description(describeEventualCause(failure.cause()))
                    .dittoHeaders(dittoHeaders)
                    .build();
            answerToPublish = new Status.Failure(error);
        } else {
            answerToPublish = status;
        }
    } else {
        answerToPublish = status;
    }
    return answerToPublish;
}
 
Example 2
Source File: SubUpdater.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void updateFailure(final Status.Failure failure) {
    log.error(failure.cause(), "updateFailure");

    // try again next clock tick
    localSubscriptionsChanged = true;
    state = State.WAITING;
}
 
Example 3
Source File: BaseClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private State<BaseClientState, BaseClientData> onUnknownEvent(final Object event, final BaseClientData state) {
    Object message = event;
    if (event instanceof Failure) {
        message = ((Failure) event).cause();
    } else if (event instanceof Status.Failure) {
        message = ((Status.Failure) event).cause();
    }

    if (message instanceof Throwable) {
        log.error((Throwable) message, "received Exception {} in state {} - status: {} - sender: {}",
                message,
                stateName(),
                state.getConnectionStatus() + ": " + state.getConnectionStatusDetails().orElse(""),
                getSender());
    } else {
        log.warning("received unknown/unsupported message {} in state {} - status: {} - sender: {}",
                message,
                stateName(),
                state.getConnectionStatus() + ": " + state.getConnectionStatusDetails().orElse(""),
                getSender());
    }

    final ActorRef sender = getSender();
    if (!Objects.equals(sender, getSelf()) && !Objects.equals(sender, getContext().system().deadLetters())) {
        sender.tell(unhandledExceptionForSignalInState(event, stateName()), getSelf());
    }

    return stay();
}
 
Example 4
Source File: RabbitMQClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static Object messageFromConnectionStatus(final Status.Status status) {
    if (status instanceof Status.Failure) {
        final Status.Failure failure = (Status.Failure) status;
        return new ImmutableConnectionFailure(null, failure.cause(), null);
    } else {
        return (ClientConnected) Optional::empty;
    }
}
 
Example 5
Source File: KafkaClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private State<BaseClientState, BaseClientData> handleStatusReportFromChildren(final Status.Status status) {
    if (pendingStatusReportsFromStreams.contains(getSender())) {
        pendingStatusReportsFromStreams.remove(getSender());
        if (status instanceof Status.Failure) {
            final Status.Failure failure = (Status.Failure) status;
            final ConnectionFailure connectionFailure =
                    new ImmutableConnectionFailure(null, failure.cause(), "child failed");
            getSelf().tell(connectionFailure, ActorRef.noSender());
        } else if (pendingStatusReportsFromStreams.isEmpty()) {
            // all children are ready; this client actor is connected.
            getSelf().tell((ClientConnected) () -> null, ActorRef.noSender());
        }
    }
    return stay();
}
 
Example 6
Source File: HttpPushClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTCPConnectionFails() {
    new TestKit(actorSystem) {{
        binding.terminate(Duration.ofMillis(1L)).toCompletableFuture().join();
        final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
        underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
        final Status.Failure failure = expectMsgClass(Status.Failure.class);
        assertThat(failure.cause()).isInstanceOf(ConnectionFailedException.class);
        expectTerminated(underTest);
    }};
}
 
Example 7
Source File: HttpPushClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTLSConnectionFails() {
    // GIVEN: server has a self-signed certificate
    connection = getHttpConnectionBuilderToLocalBinding(true, binding.localAddress().getPort()).build();
    final ClientCertificateCredentials credentials = ClientCertificateCredentials.newBuilder()
            .clientKey(TestConstants.Certificates.CLIENT_SELF_SIGNED_KEY)
            .clientCertificate(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
            .build();
    final SSLContext sslContext = SSLContextCreator.fromConnection(connection, DittoHeaders.empty())
            .clientCertificate(credentials);
    final HttpsConnectionContext invalidHttpsContext = ConnectionContext.https(sslContext);

    final int port = binding.localAddress().getPort();
    binding.terminate(Duration.ofMillis(1L)).toCompletableFuture().join();
    binding = Http.get(actorSystem)
            .bindAndHandle(handler,
                    ConnectHttp.toHostHttps("127.0.0.1", port).withCustomHttpsContext(invalidHttpsContext),
                    mat)
            .toCompletableFuture()
            .join();

    new TestKit(actorSystem) {{
        // WHEN: the connection is tested
        final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
        underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());

        // THEN: the test fails
        final Status.Failure failure = expectMsgClass(Status.Failure.class);
        assertThat(failure.cause()).isInstanceOf(DittoRuntimeException.class);
        assertThat(((DittoRuntimeException) failure.cause()).getDescription().orElse(""))
                .contains("unable to find valid certification path");
        expectTerminated(underTest);
    }};
}
 
Example 8
Source File: AbstractMqttClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTestConnectionFails() {
    new TestKit(actorSystem) {{
        final Props props = createFailingClientActor(getRef());
        final ActorRef mqttClientActor = actorSystem.actorOf(props);

        mqttClientActor.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());

        final Status.Failure failure = expectMsgClass(Status.Failure.class);
        assertThat(failure.cause()).isInstanceOf(ConnectionFailedException.class);

        expectDisconnectCalled();
    }};
}
 
Example 9
Source File: AkkademyDb.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
private void handleGetRequest(GetRequest getRequest) {
    log.info("Received Get request: {}", getRequest);
    Object value = map.get(getRequest.key);
    Object response = (value != null)
            ? value
            : new Status.Failure(new KeyNotFoundException(getRequest.key));
    sender().tell(response, self());
}
 
Example 10
Source File: EventStoreEventStore.java    From rock-paper-scissors-in-java with MIT License 5 votes vote down vote up
@Override
public void onReceive(Object message) throws Exception {
    if (message instanceof WriteEventsCompleted) {
        final WriteEventsCompleted completed = (WriteEventsCompleted) message;
        log.info("range: {}, position: {}", completed.numbersRange(), completed.position());
    } else if (message instanceof Status.Failure) {
        final Status.Failure failure = ((Status.Failure) message);
        final EsException exception = (EsException) failure.cause();
        log.error(exception, exception.toString());
    } else {
        unhandled(message);
    }
}
 
Example 11
Source File: ImmutableConnectionFailure.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Status.Failure getFailure() {
    return new Status.Failure(cause);
}
 
Example 12
Source File: AmqpConsumerActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void messageConsumerFailed(final Status.Failure failure) {
    // escalate to parent
    final ConnectionFailure connectionFailed = new ImmutableConnectionFailure(getSelf(), failure.cause(),
            "Failed to recreate closed message consumer");
    getContext().getParent().tell(connectionFailed, getSelf());
}
 
Example 13
Source File: AbstractBaseClientActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testTLSConnectionWithoutCertificateCheck() {
    // GIVEN: server has a self-signed certificate (bind port number is random; connection port number is ignored)
    final Connection serverConnection = getHttpConnectionBuilderToLocalBinding(true, 443).build();
    final ClientCertificateCredentials credentials = ClientCertificateCredentials.newBuilder()
            .clientKey(TestConstants.Certificates.CLIENT_SELF_SIGNED_KEY)
            .clientCertificate(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
            .build();
    final SSLContext sslContext = SSLContextCreator.fromConnection(serverConnection, DittoHeaders.empty())
            .clientCertificate(credentials);
    final HttpsConnectionContext invalidHttpsContext = ConnectionContext.https(sslContext);

    final ActorSystem actorSystem = getActorSystem();
    final ServerBinding binding = Http.get(actorSystem)
            .bindAndHandle(Flow.fromSinkAndSource(Sink.ignore(), Source.empty()),
                    ConnectHttp.toHostHttps("127.0.0.1", 0).withCustomHttpsContext(invalidHttpsContext),
                    ActorMaterializer.create(actorSystem))
            .toCompletableFuture()
            .join();

    new TestKit(actorSystem) {{
        // WHEN: the connection is tested against a client actor that really tries to connect to the local port
        final Connection secureConnection = getConnection(true);
        final Connection insecureConnection = secureConnection.toBuilder()
                .uri(Uri.create(secureConnection.getUri()).port(binding.localAddress().getPort()).toString())
                .validateCertificate(false)
                .failoverEnabled(false)
                .build();
        final ActorRef underTest = watch(actorSystem.actorOf(
                DefaultClientActorPropsFactory.getInstance()
                        .getActorPropsForType(insecureConnection, getRef(), getRef())
        ));
        underTest.tell(TestConnection.of(insecureConnection, DittoHeaders.empty()), getRef());

        // THEN: the test should succeed, or it should fail with a different reason than SSL validation
        final Object response = expectMsgClass(Duration.ofSeconds(5), Object.class);
        if (response instanceof Status.Failure) {
            final DittoRuntimeException error =
                    (DittoRuntimeException) getEventualCause(((Status.Failure) response).cause());
            assertThat(error.getMessage())
                    .describedAs("error message")
                    .doesNotContain("unable to find valid certification path");
            assertThat(error.getDescription().orElse(""))
                    .describedAs("error description")
                    .doesNotContain("unable to find valid certification path");
        } else {
            assertThat(response).isInstanceOf(Status.Success.class);
        }
        expectTerminated(underTest);
    }};
}
 
Example 14
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testConsumerRecreationFailureWhenConnected() throws JMSException {
    new TestKit(actorSystem) {{
        final Props props =
                AmqpClientActor.propsForTests(singleConsumerConnection(), getRef(), getRef(),
                        (ac, el) -> mockConnection);
        final TestActorRef<AmqpClientActor> amqpClientActorRef = TestActorRef.apply(props, actorSystem);
        final AmqpClientActor amqpClientActor = amqpClientActorRef.underlyingActor();

        amqpClientActorRef.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
        expectMsg(CONNECTED_SUCCESS);

        // GIVEN: JMS session fails, but the JMS connection can create a new functional session
        final Session mockSession2 = Mockito.mock(Session.class);
        final MessageConsumer mockConsumer2 = Mockito.mock(JmsMessageConsumer.class);
        when(mockSession.createConsumer(any()))
                .thenThrow(new IllegalStateException("expected exception"));
        doReturn(mockSession2).when(mockConnection).createSession(anyInt());
        doReturn(mockConsumer2).when(mockSession2).createConsumer(any());

        // WHEN: consumer is closed and cannot be recreated
        final ActorRef amqpConsumerActor = amqpClientActor.context().children().toStream()
                .find(child -> child.path().name().startsWith(AmqpConsumerActor.ACTOR_NAME_PREFIX))
                .get();
        final Throwable error = new IllegalStateException("Forcibly detached");
        final Status.Failure failure = new Status.Failure(new AskTimeoutException("Consumer creation timeout"));
        amqpClientActor.connectionListener.onConsumerClosed(mockConsumer, error);
        verify(mockSession, atLeastOnce()).createConsumer(any());
        amqpConsumerActor.tell(failure, amqpConsumerActor);

        // THEN: connection gets restarted
        verify(mockConnection).createSession(anyInt());
        final ArgumentCaptor<MessageListener> captor = ArgumentCaptor.forClass(MessageListener.class);
        verify(mockConsumer2, timeout(1000).atLeastOnce()).setMessageListener(captor.capture());
        final MessageListener messageListener = captor.getValue();

        // THEN: recreated connection is working
        messageListener.onMessage(mockMessage());
        expectMsgClass(Command.class);
    }};
}
 
Example 15
Source File: ConnectionFailure.java    From ditto with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * @return the Failure containing the cause.
 */
Status.Failure getFailure();