akka.actor.Status Java Examples

The following examples show how to use akka.actor.Status. 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: HttpPushClientActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private CompletionStage<Status.Status> connectViaProxy(final String hostWithoutLookup, final int port) {
    final HttpProxyConfig httpProxyConfig = this.httpPushConfig.getHttpProxyConfig();
    try (final Socket proxySocket = new Socket(httpProxyConfig.getHostname(), httpProxyConfig.getPort())) {
        String proxyConnect = "CONNECT " + hostWithoutLookup + ":" + port + " HTTP/1.1\n";
        proxyConnect += "Host: " + hostWithoutLookup + ":" + port;

        if (!httpProxyConfig.getUsername().isEmpty()) {
            final String proxyUserPass = httpProxyConfig.getUsername() + ":" + httpProxyConfig.getPassword();
            proxyConnect += "\nProxy-Authorization: Basic " +
                    Base64.getEncoder().encodeToString(proxyUserPass.getBytes());
        }
        proxyConnect += "\n\n";
        proxySocket.getOutputStream().write(proxyConnect.getBytes());

        return checkProxyConnection(hostWithoutLookup, port, proxySocket);
    } catch (final Exception error) {
        return statusFailureFuture(new SocketException("Failed to connect to HTTP proxy: " + error.getMessage()));
    }
}
 
Example #2
Source File: KafkaClientActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inTestingState() {
    return super.inTestingState()
            .event(Status.Status.class, (e, d) -> !Objects.equals(getSender(), getSelf()),
                    (status, data) -> handleStatusReportFromChildren(status))
            .event(ClientConnected.class, BaseClientData.class, (event, data) -> {
                final String url = data.getConnection().getUri();
                final String message = "Kafka connection to " + url + " established successfully";
                completeTestConnectionFuture(new Status.Success(message));
                return stay();
            })
            .event(ConnectionFailure.class, BaseClientData.class, (event, data) -> {
                completeTestConnectionFuture(new Status.Failure(event.getFailure().cause()));
                return stay();
            });
}
 
Example #3
Source File: BaseClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void reconnectsInConnectingStateIfFailureResponseReceived() {
    new TestKit(actorSystem) {{
        final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId();
        final Connection connection =
                TestConstants.createConnection(randomConnectionId, new Target[0]);
        final Props props = DummyClientActor.props(connection, getRef(), getRef(), getRef(), delegate);

        final ActorRef dummyClientActor = watch(actorSystem.actorOf(props));

        whenOpeningConnection(dummyClientActor, OpenConnection.of(randomConnectionId, DittoHeaders.empty()),
                getRef());
        andConnectionNotSuccessful(dummyClientActor);

        expectMsgClass(Status.Failure.class);

        thenExpectConnectClientCalled();
        thenExpectConnectClientCalledAfterTimeout(connectivityConfig.getClientConfig().getConnectingMinTimeout());
    }};
}
 
Example #4
Source File: BaseClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void handlesCloseConnectionInConnectingState() {
    new TestKit(actorSystem) {{
        final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId();
        final Connection connection =
                TestConstants.createConnection(randomConnectionId, new Target[0]);
        final Props props = DummyClientActor.props(connection, getRef(), getRef(), getRef(), delegate);

        final ActorRef dummyClientActor = watch(actorSystem.actorOf(props));

        whenOpeningConnection(dummyClientActor, OpenConnection.of(randomConnectionId, DittoHeaders.empty()),
                getRef());
        thenExpectConnectClientCalled();

        andClosingConnection(dummyClientActor, CloseConnection.of(randomConnectionId, DittoHeaders.empty()),
                getRef());
        thenExpectDisconnectClientCalled();
        andDisconnectionSuccessful(dummyClientActor, getRef());

        expectMsg(new Status.Success(BaseClientState.DISCONNECTED));
    }};
}
 
Example #5
Source File: AkkaRpcActor.java    From flink with Apache License 2.0 6 votes vote down vote up
private void handleHandshakeMessage(RemoteHandshakeMessage handshakeMessage) {
	if (!isCompatibleVersion(handshakeMessage.getVersion())) {
		sendErrorIfSender(new AkkaHandshakeException(
			String.format(
				"Version mismatch between source (%s) and target (%s) rpc component. Please verify that all components have the same version.",
				handshakeMessage.getVersion(),
				getVersion())));
	} else if (!isGatewaySupported(handshakeMessage.getRpcGateway())) {
		sendErrorIfSender(new AkkaHandshakeException(
			String.format(
				"The rpc endpoint does not support the gateway %s.",
				handshakeMessage.getRpcGateway().getSimpleName())));
	} else {
		getSender().tell(new Status.Success(HandshakeSuccessMessage.INSTANCE), getSelf());
	}
}
 
Example #6
Source File: BaseClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldReconnectIfSocketIsClosed() {
    new TestKit(actorSystem) {{
        final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId();
        final Connection connection =
                TestConstants.createConnection(randomConnectionId, new Target[0])
                        .toBuilder()
                        .uri("amqps://username:[email protected]:65536") // port 65536 does not even exist ;)
                        .build();
        final Props props = DummyClientActor.props(connection, getRef(), getRef(), getRef(), delegate);

        final ActorRef dummyClientActor = watch(actorSystem.actorOf(props));

        whenOpeningConnection(dummyClientActor, OpenConnection.of(randomConnectionId, DittoHeaders.empty()),
                getRef());

        expectMsgClass(Status.Failure.class);

        thenExpectCleanupResourcesCalled();
        Mockito.clearInvocations(delegate);
        thenExpectCleanupResourcesCalledAfterTimeout(
                connectivityConfig.getClientConfig().getConnectingMinTimeout());
        thenExpectNoConnectClientCalled();
    }};
}
 
Example #7
Source File: HttpPushClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void placeholderReplacement() throws Exception {
    final Target target = TestConstants.Targets.TARGET_WITH_PLACEHOLDER
            .withAddress("PATCH:" + TestConstants.Targets.TARGET_WITH_PLACEHOLDER.getAddress());
    connection = connection.toBuilder().setTargets(singletonList(target)).build();

    new TestKit(actorSystem) {{
        // GIVEN: local HTTP connection is connected
        final ActorRef underTest = actorSystem.actorOf(createClientActor(getRef(), getConnection(false)));
        underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getRef());
        expectMsg(new Status.Success(BaseClientState.CONNECTED));

        // WHEN: a thing event is sent to a target with header mapping content-type=application/json
        final ThingModifiedEvent thingModifiedEvent = TestConstants.thingModified(Collections.emptyList());
        final OutboundSignal outboundSignal =
                OutboundSignalFactory.newOutboundSignal(thingModifiedEvent, singletonList(target));
        underTest.tell(outboundSignal, getRef());

        // THEN: a POST-request is forwarded to the path defined in the target
        final HttpRequest thingModifiedRequest = requestQueue.take();
        responseQueue.offer(HttpResponse.create().withStatus(StatusCodes.OK));
        assertThat(thingModifiedRequest.getUri().getPathString()).isEqualTo("/target:ditto/thing@twin");
    }};
}
 
Example #8
Source File: ResponseActor.java    From yahoo-streaming-benchmark with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Object message) throws Exception {
	if (message instanceof QueryState) {
		@SuppressWarnings("unchecked")
		QueryState<K> queryState = (QueryState<K>) message;

		LOG.debug("Received QueryState for key " + queryState.getKey() + ".");

		try {
			V value = keyValueState.getValue(queryState.getTimestamp(), queryState.getKey());

			if (value == null) {
				sender().tell(new StateNotFound<>(queryState.getKey()), getSelf());
			} else {
				sender().tell(new StateFound<>(queryState.getKey(), value), getSelf());
			}
		} catch (WrongKeyPartitionException ex) {
			sender().tell(new Status.Failure(ex), getSelf());
		}

		LOG.debug("Handled QueryState for key " + queryState.getKey() + ".");
	}else {
		throw new RuntimeException("Unknown message " + message);
	}
}
 
Example #9
Source File: FaultyClientActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder()
            .match(CreateConnection.class, cc -> {
                if (allowCreate) {
                    log.info("connection created");
                    this.allowCreate = false;
                    sender().tell(new Status.Success("mock"), getSelf());
                } else {
                    sender().tell(new Status.Failure(new IllegalStateException("error message")),
                            getSelf());
                }
            })
            .match(OpenConnection.class,
                    oc -> sender().tell(new Status.Failure(new IllegalStateException("error message")),
                            getSelf()))
            .match(CloseConnection.class,
                    cc -> sender().tell(new Status.Failure(new IllegalStateException("error message")),
                            getSelf()))
            .match(DeleteConnection.class,
                    dc -> sender().tell(new Status.Failure(new IllegalStateException("error message")),
                            getSelf()))
            .build();
}
 
Example #10
Source File: HiveMqtt5ClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSubscribeFails() {
    new TestKit(actorSystem) {{
        final MockHiveMqtt5ClientFactory clientFactory = mockHiveMqtt5ClientFactory
                .withTestProbe(getRef())
                .withFailingSubscribe();

        final Props props =
                HiveMqtt5ClientActor.props(connection, getRef(), clientFactory, mockConnectionActor.ref());
        final ActorRef mqttClientActor = actorSystem.actorOf(props, "mqttClientActor-testSubscribeFails");

        mqttClientActor.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), getRef());
        expectMsgClass(Status.Failure.class);

        mqttClientActor.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), getRef());
        expectMsg(DISCONNECTED_SUCCESS);
    }};
}
 
Example #11
Source File: BaseClientActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates the handler for messages in testing state. Overwrite and extend by additional matchers.
 *
 * @return an FSM function builder
 */
protected FSMStateFunctionBuilder<BaseClientState, BaseClientData> inTestingState() {
    return matchEvent(Status.Status.class, (e, d) -> Objects.equals(getSender(), getSelf()),
            (status, data) -> {
                log.info("{} status: <{}>", stateName(), status);
                data.getSessionSenders().forEach(sender ->
                        sender.first().tell(getStatusToReport(status, sender.second()), getSelf()));
                return stop();
            })
            .eventEquals(StateTimeout(), BaseClientData.class, (stats, data) -> {
                log.info("test timed out.");
                data.getSessionSenders().forEach(sender -> {
                    final DittoRuntimeException error = ConnectionFailedException.newBuilder(connectionId())
                            .description(String.format("Failed to open requested connection within <%d> seconds!",
                                    clientConfig.getTestingTimeout().getSeconds()))
                            .dittoHeaders(sender.second())
                            .build();
                    sender.first().tell(new Status.Failure(error), getSelf());
                });
                return stop();
            });
}
 
Example #12
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 #13
Source File: AmqpClientActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected CompletionStage<Status.Status> startPublisherActor() {
    final CompletableFuture<Status.Status> future = new CompletableFuture<>();
    stopChildActor(amqpPublisherActor);
    final String namePrefix = AmqpPublisherActor.ACTOR_NAME_PREFIX;
    if (jmsSession != null) {
        final Props props = AmqpPublisherActor.props(connection(), jmsSession,
                connectivityConfig.getConnectionConfig());
        amqpPublisherActor = startChildActorConflictFree(namePrefix, props);
        future.complete(DONE);
    } else {
        future.completeExceptionally(ConnectionFailedException
                .newBuilder(connectionId())
                .message("Could not start publisher actor due to missing JMS session or connection!")
                .build());
    }
    return future;
}
 
Example #14
Source File: JMSConnectionHandlingActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private void createMessageConsumer(final AmqpConsumerActor.CreateMessageConsumer command) {
    final Throwable error;
    if (currentSession != null) {
        // create required consumer
        final ConsumerData consumerData = command.getConsumerData();
        final ConsumerData newConsumerData =
                createJmsConsumer(currentSession, new HashMap<>(), consumerData.getSource(),
                        consumerData.getAddress(), consumerData.getAddressWithIndex());
        if (newConsumerData != null) {
            final Object response = command.toResponse(newConsumerData.getMessageConsumer());
            getSender().tell(response, getSelf());
            error = null;
        } else {
            error = new IllegalStateException("Failed to create message consumer");
        }
    } else {
        error = new IllegalStateException("No session");
    }
    if (error != null) {
        getSender().tell(new Status.Failure(error), getSelf());
    }
}
 
Example #15
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 #16
Source File: BaseClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void doesNotReconnectIfConnectionSuccessful() {
    new TestKit(actorSystem) {{
        final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId();
        final Connection connection =
                TestConstants.createConnection(randomConnectionId, new Target[0]);
        final Props props = DummyClientActor.props(connection, getRef(), getRef(), getRef(), delegate);

        final ActorRef dummyClientActor = watch(actorSystem.actorOf(props));

        whenOpeningConnection(dummyClientActor, OpenConnection.of(randomConnectionId, DittoHeaders.empty()),
                getRef());
        thenExpectConnectClientCalled();
        Mockito.clearInvocations(delegate);
        andConnectionSuccessful(dummyClientActor, getRef());

        expectMsgClass(Status.Success.class);
        thenExpectNoConnectClientCalledAfterTimeout(connectivityConfig.getClientConfig().getConnectingMinTimeout());
    }};
}
 
Example #17
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 #18
Source File: KafkaClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTestConnection() {
    new TestKit(actorSystem) {{
        final Props props = getKafkaClientActorProps(getRef(), connection);
        final ActorRef kafkaClientActor = actorSystem.actorOf(props);

        kafkaClientActor.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
        expectMsg(new Status.Success("successfully connected + initialized mapper"));
    }};
}
 
Example #19
Source File: HiveMqtt5SubscriptionHandler.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void subscribeIfReady() {
    if (!isConnected) {
        log.debug("Not connected, not subscribing.");
    } else if (!allConsumersReady()) {
        log.debug("Consumers are not initialized, not subscribing.");
    } else {
        log.info("Client connected and all consumers ready, subscribing now.");
        CompletableFuture
                .allOf(mqtt5Subscribe.entrySet().stream()
                        .map(e -> {
                            final Source source = e.getKey();
                            final Mqtt5Subscribe theMqtt5Subscribe = e.getValue();
                            final ActorRef consumerActorRef = consumerActors.get(source);
                            if (consumerActorRef == null) {
                                return failedFuture(new IllegalStateException("no consumer"));
                            } else {
                                return subscribe(source, theMqtt5Subscribe, consumerActorRef);
                            }
                        })
                        .toArray(CompletableFuture[]::new))
                .whenComplete((result, t) -> {
                    if (t == null) {
                        log.debug("All subscriptions created successfully.");
                        subscriptionsDone.complete(new Status.Success("successfully subscribed"));
                    } else {
                        log.info("Subscribe failed due to: {}", t.getMessage());
                        subscriptionsDone.completeExceptionally(t);
                    }
                });
    }
}
 
Example #20
Source File: KafkaClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected CompletionStage<Status.Status> doTestConnection(final Connection connection) {
    if (testConnectionFuture != null) {
        final Exception error =
                new IllegalStateException("Can't test new connection since a test is already running.");
        return CompletableFuture.completedFuture(new Status.Failure(error));
    }
    testConnectionFuture = new CompletableFuture<>();
    connectClient(true);
    return testConnectionFuture;
}
 
Example #21
Source File: TellTest.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
@Test
public void itShouldParseArticleTest() throws Exception{
    Future f = ask(tellDemoActor, new ParseArticle(("http://www.google.com")), timeout);
    cacheProbe.expectMsgClass(GetRequest.class);
    cacheProbe.reply(new Status.Failure(new Exception("no cache")));

    httpClientProbe.expectMsgClass(String.class);
    httpClientProbe.reply(new HttpResponse(Articles.article1));

    String result = (String) Await.result(f, timeout.duration());
    assert(result.contains("I’ve been writing a lot in emacs lately"));
    assert(!result.contains("<body>"));
}
 
Example #22
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 #23
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testStartConnectionFails() throws JMSException {
    new TestKit(actorSystem) {{
        doThrow(JMS_EXCEPTION).when(mockConnection).start();
        final Props props =
                AmqpClientActor.propsForTests(connection, getRef(),
                        getRef(), (ac, el) -> mockConnection);
        final ActorRef amqpClientActor = actorSystem.actorOf(props);

        amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
        expectMsg(new Status.Failure(SESSION_EXCEPTION));
    }};
}
 
Example #24
Source File: AmqpConsumerActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Receive createReceive() {
    return ReceiveBuilder.create()
            .match(RestartMessageConsumer.class, this::handleRestartMessageConsumer)
            .match(JmsMessage.class, this::handleJmsMessage)
            .match(ResourceStatus.class, this::handleAddressStatus)
            .match(RetrieveAddressStatus.class, ras -> getSender().tell(getCurrentSourceStatus(), getSelf()))
            .match(ConsumerClosedStatusReport.class, this::matchesOwnConsumer, this::handleConsumerClosed)
            .match(CreateMessageConsumerResponse.class, this::messageConsumerCreated)
            .match(Status.Failure.class, this::messageConsumerFailed)
            .matchAny(m -> {
                log.warning("Unknown message: {}", m);
                unhandled(m);
            }).build();
}
 
Example #25
Source File: AmqpClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected CompletionStage<Status.Status> startConsumerActors(final ClientConnected clientConnected) {
    if (clientConnected instanceof JmsConnected) {
        final JmsConnected c = (JmsConnected) clientConnected;
        final ActorRef jmsActor = getConnectConnectionHandler(connection());
        startCommandConsumers(c.consumerList, jmsActor);
    }
    return CompletableFuture.completedFuture(new Status.Success(Done.getInstance()));
}
 
Example #26
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 #27
Source File: FSMClientActorTest.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
@Test
public void itShouldFlushMessagesInConnectedAndPending() throws Exception {
    TestActorRef<FSMClientActor> fsmClientRef =
            TestActorRef.create(system, Props.create(FSMClientActor.class, dbRef.path().toString()));

    fsmClientRef.tell(new SetRequest("testkey", "testvalue", probe.ref()), probe.ref());

    assert(fsmClientRef.underlyingActor().stateName() == State.CONNECTED_AND_PENDING);

    fsmClientRef.tell(new FlushMsg(), probe.ref());

    probe.expectMsgClass(Status.Success.class);
    assert(fsmClientRef.underlyingActor().stateName() == State.CONNECTED);
}
 
Example #28
Source File: HttpPushClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private CompletionStage<Status.Status> checkProxyConnection(final String hostWithoutLookup, final int port,
        final Socket proxySocket) throws InterruptedException, java.util.concurrent.ExecutionException {
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        return executor.submit(() -> {
            byte[] tmpBuffer = new byte[512];
            final InputStream socketInput = proxySocket.getInputStream();
            int len = socketInput.read(tmpBuffer, 0, tmpBuffer.length);
            if (len == 0) {
                socketInput.close();
                return statusFailureFuture(new SocketException("Invalid response from proxy"));
            }

            final String proxyResponse = new String(tmpBuffer, 0, len, StandardCharsets.UTF_8);
            if (proxyResponse.startsWith("HTTP/1.1 200")) {
                socketInput.close();
                return statusSuccessFuture("Connection to '%s:%d' via HTTP proxy established successfully.",
                        hostWithoutLookup, port);
            } else {
                ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId());
                log.info("Could not connect to <{}> via Http Proxy <{}>", hostWithoutLookup + ":" + port,
                        proxySocket.getInetAddress());
                socketInput.close();
                return statusFailureFuture(new SocketException("Failed to create Socket via HTTP proxy: " +
                        proxyResponse));
            }
        }).get(PROXY_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (final TimeoutException timedOut) {
        return statusFailureFuture(
                new SocketException("Failed to create Socket via HTTP proxy within timeout"));
    } finally {
        executor.shutdown();
    }
}
 
Example #29
Source File: AkkaRpcActor.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void sendSyncResponse(Object response, String methodName) {
	if (isRemoteSender(getSender())) {
		Either<SerializedValue<?>, AkkaRpcException> serializedResult = serializeRemoteResultAndVerifySize(response, methodName);

		if (serializedResult.isLeft()) {
			getSender().tell(new Status.Success(serializedResult.left()), getSelf());
		} else {
			getSender().tell(new Status.Failure(serializedResult.right()), getSelf());
		}
	} else {
		getSender().tell(new Status.Success(response), getSelf());
	}
}
 
Example #30
Source File: AkkaRpcActor.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Handle asynchronous {@link Callable}. This method simply executes the given {@link Callable}
 * in the context of the actor thread.
 *
 * @param callAsync Call async message
 */
private void handleCallAsync(CallAsync callAsync) {
	try {
		Object result = callAsync.getCallable().call();

		getSender().tell(new Status.Success(result), getSelf());
	} catch (Throwable e) {
		getSender().tell(new Status.Failure(e), getSelf());
	}
}