Java Code Examples for akka.actor.Status#Status

The following examples show how to use akka.actor.Status#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> testSSL(final Connection connection, final String hostWithoutLookup,
        final int port) {
    if (httpPushConfig.getHttpProxyConfig().isEnabled()) {
        // don't do a second proxy check
        return statusSuccessFuture("TLS connection to '%s:%d' via Http proxy established successfully.",
                hostWithoutLookup, port);
    } else {
        // check without HTTP proxy
        final SSLContextCreator sslContextCreator =
                SSLContextCreator.fromConnection(connection, DittoHeaders.empty());
        final SSLSocketFactory socketFactory = connection.getCredentials()
                .map(credentials -> credentials.accept(sslContextCreator))
                .orElse(sslContextCreator.withoutClientCertificate()).getSocketFactory();
        try (final SSLSocket socket = (SSLSocket) socketFactory.createSocket(hostWithoutLookup, port)) {
            socket.startHandshake();
            return statusSuccessFuture("TLS connection to '%s:%d' established successfully.",
                    hostWithoutLookup, socket.getPort());
        } catch (final Exception error) {
            return statusFailureFuture(error);
        }
    }
}
 
Example 2
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 3
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 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: BaseClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private CompletionStage<Status.Status> testMessageMappingProcessor() {
    try {
        return tryToConfigureMessageMappingProcessor();
    } catch (final DittoRuntimeException dre) {
        final String logMessage = MessageFormat.format(
                "Got DittoRuntimeException during initialization of MessageMappingProcessor: {0} {1} - desc: {2}",
                dre.getClass().getSimpleName(), dre.getMessage(), dre.getDescription().orElse(""));
        connectionLogger.failure(logMessage);
        log.info(logMessage);
        return CompletableFuture.completedFuture(new Status.Failure(dre));
    }
}
 
Example 6
Source File: BaseClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private CompletionStage<Status.Status> tryToConfigureMessageMappingProcessor() {
    final ActorSystem actorSystem = getContext().getSystem();
    // this one throws DittoRuntimeExceptions when the mapper could not be configured
    MessageMappingProcessor.of(connectionId(), connection().getPayloadMappingDefinition(), actorSystem,
            connectivityConfig, protocolAdapterProvider, log);
    return CompletableFuture.completedFuture(new Status.Success("mapping"));
}
 
Example 7
Source File: RabbitMQClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected CompletionStage<Status.Status> doTestConnection(final Connection connection) {
    // should be smaller than the global testing timeout to be able to send a response
    final Duration createChannelTimeout = clientConfig.getTestingTimeout().dividedBy(10L).multipliedBy(8L);
    final Duration internalReconnectTimeout = clientConfig.getTestingTimeout();
    // does explicitly not test the consumer so we won't consume any messages by accident.
    return connect(connection, createChannelTimeout, internalReconnectTimeout);
}
 
Example 8
Source File: KafkaClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Props getKafkaClientActorProps(final ActorRef ref, final Status.Status status,
        final Connection connection) {
    return KafkaClientActor.props(connection, ref, ref,
            new KafkaPublisherActorFactory() {
                @Override
                public String getActorName() {
                    return "testPublisherActor";
                }

                @Override
                public Props props(final Connection c, final KafkaConnectionFactory factory, final boolean dryRun) {
                    return MockKafkaPublisherActor.props(ref, status);
                }
            });
}
 
Example 9
Source File: HttpPushClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected CompletionStage<Status.Status> startPublisherActor() {
    final CompletableFuture<Status.Status> future = new CompletableFuture<>();
    stopChildActor(httpPublisherActor);
    final Props props = HttpPublisherActor.props(connection(), factory);
    httpPublisherActor = startChildActorConflictFree(HttpPublisherActor.ACTOR_NAME, props);
    future.complete(DONE);
    return future;
}
 
Example 10
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 11
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 12
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 13
Source File: KafkaClientActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected CompletionStage<Status.Status> startPublisherActor() {
    return CompletableFuture.completedFuture(DONE);
}
 
Example 14
Source File: HiveMqtt3ClientActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected CompletionStage<Status.Status> startPublisherActor() {
    publisherActor = startPublisherActor(connection(), getClient());
    return CompletableFuture.completedFuture(DONE);
}
 
Example 15
Source File: HiveMqtt3ClientActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected CompletionStage<Status.Status> startConsumerActors(final ClientConnected clientConnected) {
    startHiveMqConsumers(getSubscriptionHandler()::handleMqttConsumer);
    return getSubscriptionHandler().getCompletionStage();
}
 
Example 16
Source File: RabbitMQClientActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected CompletionStage<Status.Status> startPublisherActor() {
    return CompletableFuture.completedFuture(DONE);
}
 
Example 17
Source File: HiveMqtt3ClientActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected CompletionStage<Status.Status> doTestConnection(final Connection connection) {

    final MqttSpecificConfig mqttSpecificConfig = MqttSpecificConfig.fromConnection(connection);
    final String mqttClientId = resolveMqttClientId(connection.getId(), mqttSpecificConfig);
    // attention: do not use reconnect, otherwise the future never returns
    final Mqtt3Client testClient;
    try {
        testClient = clientFactory.newClient(connection, mqttClientId, false);
    } catch (final Exception e) {
        return CompletableFuture.completedFuture(new Status.Failure(e.getCause()));
    }
    final HiveMqtt3SubscriptionHandler testSubscriptions =
            new HiveMqtt3SubscriptionHandler(connection, testClient, log);
    return testClient
            .toAsync()
            .connectWith()
            .cleanSession(CLEAN_SESSION)
            .send()
            .thenApply(connAck -> {
                final String url = connection.getUri();
                final String message = "MQTT connection to " + url + " established successfully.";
                log.info(message);
                return (Status.Status) new Status.Success(message);
            })
            .thenCompose(status -> {
                startPublisherActor(connection(), testClient);
                return CompletableFuture.completedFuture(new Status.Success("publisher started"));
            })
            .thenCompose(s -> {
                testSubscriptions.handleConnected();
                startHiveMqConsumers(testSubscriptions::handleMqttConsumer);
                return testSubscriptions.getCompletionStage();
            })
            .exceptionally(cause -> {
                log.info("Connection test to {} failed: {}", connection.getUri(), cause.getMessage());
                connectionLogger.failure("Connection test failed: {0}", cause.getMessage());
                return new Status.Failure(cause);
            })
            .whenComplete((s, t) -> {
                if (t == null) {
                    connectionLogger.success("Connection test for was successful.");
                    log.info("Connection test for {} was successful.", connectionId());
                }
                stopCommandConsumers(testSubscriptions);
                stopChildActor(publisherActor);
                safelyDisconnectClient(testClient);
            });
}
 
Example 18
Source File: HiveMqtt5SubscriptionHandler.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
CompletionStage<Status.Status> getCompletionStage() {
    return subscriptionsDone;
}
 
Example 19
Source File: BaseClientActor.java    From ditto with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Subclasses should start their publisher actor in the implementation of this method and report success or
 * failure in the returned {@link CompletionStage}. {@code BaseClientActor} calls this method when the client is
 * connected.
 *
 * @return a completion stage that completes either successfully when the publisher actor was started
 * successfully or exceptionally when the publisher actor could not be started successfully
 */
protected abstract CompletionStage<Status.Status> startPublisherActor();
 
Example 20
Source File: BaseClientActor.java    From ditto with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Handles {@link TestConnection} commands by returning a CompletionState of {@link akka.actor.Status.Status Status}
 * which may be {@link akka.actor.Status.Success Success} or {@link akka.actor.Status.Failure Failure}.
 *
 * @param connection the Connection to test
 * @return the CompletionStage with the test result
 */
protected abstract CompletionStage<Status.Status> doTestConnection(Connection connection);