Search in sources :

Example 1 with ClientBootstrap

use of software.amazon.awssdk.crt.io.ClientBootstrap in project aws-greengrass-nucleus by aws-greengrass.

the class IPCEventStreamServiceTest method testClientConnection.

@Test
@SuppressWarnings("PMD.CloseResource")
void testClientConnection() throws Exception {
    CountDownLatch connectionLatch = new CountDownLatch(1);
    EventStreamRPCConnection connection = null;
    try (EventLoopGroup elg = new EventLoopGroup(1);
        ClientBootstrap clientBootstrap = new ClientBootstrap(elg, new HostResolver(elg));
        SocketOptions socketOptions = TestUtils.getSocketOptionsForIPC()) {
        String ipcServerSocketPath = Platform.getInstance().prepareIpcFilepathForComponent(mockRootPath);
        final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elg, socketOptions, null, ipcServerSocketPath, DEFAULT_PORT_NUMBER, GreengrassConnectMessageSupplier.connectMessageSupplier("authToken"));
        connection = new EventStreamRPCConnection(config);
        final boolean[] disconnected = { false };
        final int[] disconnectedCode = { -1 };
        // this is a bit cumbersome but does not prevent a convenience wrapper from exposing a sync
        // connect() or a connect() that returns a CompletableFuture that errors
        // this could be wrapped by utility methods to provide a more
        connection.connect(new EventStreamRPCConnection.LifecycleHandler() {

            @Override
            public void onConnect() {
                connectionLatch.countDown();
            }

            @Override
            public void onDisconnect(int errorCode) {
                disconnected[0] = true;
                disconnectedCode[0] = errorCode;
            }

            // This on error is for any errors that is connection level, including problems during connect()
            @Override
            public boolean onError(Throwable t) {
                // hints at handler to disconnect due to this error
                return true;
            }
        });
        assertTrue(connectionLatch.await(2, TimeUnit.SECONDS));
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}
Also used : SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) EventStreamRPCConnection(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) HostResolver(software.amazon.awssdk.crt.io.HostResolver) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) EventStreamRPCConnectionConfig(software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig) Test(org.junit.jupiter.api.Test)

Example 2 with ClientBootstrap

use of software.amazon.awssdk.crt.io.ClientBootstrap in project aws-crt-java by awslabs.

the class ProxyTest method buildDirectMqttConnection.

private MqttClientConnection buildDirectMqttConnection(ProxyTestType testType, ProxyAuthType authType) {
    try (EventLoopGroup eventLoopGroup = new EventLoopGroup(1);
        HostResolver resolver = new HostResolver(eventLoopGroup);
        ClientBootstrap bootstrap = new ClientBootstrap(eventLoopGroup, resolver);
        TlsContext tlsContext = createX509TlsContext(null);
        MqttClient mqttClient = new MqttClient(bootstrap, tlsContext);
        MqttConnectionConfig connectionConfig = new MqttConnectionConfig();
        TlsContext proxyTlsContext = createProxyTlsContext(testType)) {
        HttpProxyOptions proxyOptions = buildProxyOptions(testType, authType, proxyTlsContext);
        String clientId = PROXY_TEST_CLIENTID + (UUID.randomUUID()).toString();
        connectionConfig.setMqttClient(mqttClient);
        connectionConfig.setEndpoint(MQTT_ENDPOINT);
        connectionConfig.setHttpProxyOptions(proxyOptions);
        connectionConfig.setCleanSession(true);
        connectionConfig.setClientId(clientId);
        connectionConfig.setPort(MQTT_DIRECT_PORT);
        connectionConfig.setProtocolOperationTimeoutMs(60000);
        return new MqttClientConnection(connectionConfig);
    }
}
Also used : MqttClient(software.amazon.awssdk.crt.mqtt.MqttClient) HttpProxyOptions(software.amazon.awssdk.crt.http.HttpProxyOptions) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) MqttConnectionConfig(software.amazon.awssdk.crt.mqtt.MqttConnectionConfig) ClientTlsContext(software.amazon.awssdk.crt.io.ClientTlsContext) TlsContext(software.amazon.awssdk.crt.io.TlsContext) HostResolver(software.amazon.awssdk.crt.io.HostResolver)

Example 3 with ClientBootstrap

use of software.amazon.awssdk.crt.io.ClientBootstrap in project aws-crt-java by awslabs.

the class ProxyTest method buildProxiedX509CredentialsProvider.

private CredentialsProvider buildProxiedX509CredentialsProvider(ProxyTestType testType, ProxyAuthType authType) {
    try (EventLoopGroup eventLoopGroup = new EventLoopGroup(1);
        HostResolver resolver = new HostResolver(eventLoopGroup);
        ClientBootstrap bootstrap = new ClientBootstrap(eventLoopGroup, resolver);
        TlsContext tlsContext = createX509TlsContext(null);
        TlsContext proxyTlsContext = createProxyTlsContext(testType)) {
        HttpProxyOptions proxyOptions = buildProxyOptions(testType, authType, proxyTlsContext);
        X509CredentialsProvider.X509CredentialsProviderBuilder builder = new X509CredentialsProvider.X509CredentialsProviderBuilder();
        builder.withClientBootstrap(bootstrap).withEndpoint(X509_CREDENTIALS_ENDPOINT).withProxyOptions(proxyOptions).withRoleAlias(X509_CREDENTIALS_ROLE_ALIAS).withThingName(X509_CREDENTIALS_THING_NAME).withTlsContext(tlsContext);
        return builder.build();
    }
}
Also used : HttpProxyOptions(software.amazon.awssdk.crt.http.HttpProxyOptions) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) ClientTlsContext(software.amazon.awssdk.crt.io.ClientTlsContext) TlsContext(software.amazon.awssdk.crt.io.TlsContext) HostResolver(software.amazon.awssdk.crt.io.HostResolver) X509CredentialsProvider(software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider)

Example 4 with ClientBootstrap

use of software.amazon.awssdk.crt.io.ClientBootstrap in project aws-crt-java by awslabs.

the class EventStreamClientConnectionTest method testContinuationMessageWithExtraHeadersHandling.

@Test
public void testContinuationMessageWithExtraHeadersHandling() throws ExecutionException, InterruptedException, IOException, TimeoutException {
    SocketOptions socketOptions = new SocketOptions();
    socketOptions.connectTimeoutMs = 3000;
    socketOptions.domain = SocketOptions.SocketDomain.IPv4;
    socketOptions.type = SocketOptions.SocketType.STREAM;
    EventLoopGroup elGroup = new EventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap(elGroup);
    ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, null);
    final boolean[] connectionShutdown = { false };
    final String[] receivedOperationName = new String[] { null };
    final String[] receivedContinuationPayload = new String[] { null };
    final List<Header>[] receivedHeadersServer = new List[] { null };
    Header serverStrHeader = Header.createHeader("serverStrHeaderName", "serverStrHeaderValue");
    Header serverIntHeader = Header.createHeader("serverIntHeaderName", 25);
    final byte[] responsePayload = "{ \"message\": \"this is a response message\" }".getBytes(StandardCharsets.UTF_8);
    final ServerConnection[] serverConnections = { null };
    Lock semaphoreLock = new ReentrantLock();
    Condition semaphore = semaphoreLock.newCondition();
    ServerListener listener = new ServerListener("127.0.0.1", (short) 8037, socketOptions, null, bootstrap, new ServerListenerHandler() {

        private ServerConnectionHandler connectionHandler = null;

        public ServerConnectionHandler onNewConnection(ServerConnection serverConnection, int errorCode) {
            serverConnections[0] = serverConnection;
            connectionHandler = new ServerConnectionHandler(serverConnection) {

                @Override
                protected void onProtocolMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) {
                    int responseMessageFlag = MessageFlags.ConnectionAccepted.getByteValue();
                    MessageType acceptResponseType = MessageType.ConnectAck;
                    connection.sendProtocolMessage(null, null, acceptResponseType, responseMessageFlag);
                }

                @Override
                protected ServerConnectionContinuationHandler onIncomingStream(ServerConnectionContinuation continuation, String operationName) {
                    receivedOperationName[0] = operationName;
                    return new ServerConnectionContinuationHandler(continuation) {

                        @Override
                        protected void onContinuationMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) {
                            receivedContinuationPayload[0] = new String(payload, StandardCharsets.UTF_8);
                            receivedHeadersServer[0] = headers;
                            List<Header> responseHeaders = new ArrayList<>();
                            responseHeaders.add(serverStrHeader);
                            responseHeaders.add(serverIntHeader);
                            continuation.sendMessage(responseHeaders, responsePayload, MessageType.ApplicationError, MessageFlags.TerminateStream.getByteValue()).whenComplete((res, ex) -> {
                                connection.closeConnection(0);
                                this.close();
                            });
                        }
                    };
                }
            };
            semaphoreLock.lock();
            semaphore.signal();
            semaphoreLock.unlock();
            return connectionHandler;
        }

        public void onConnectionShutdown(ServerConnection serverConnection, int errorCode) {
            connectionShutdown[0] = true;
        }
    });
    final ClientConnection[] clientConnectionArray = { null };
    final List<Header>[] clientReceivedMessageHeaders = new List[] { null };
    final byte[][] clientReceivedPayload = { null };
    final MessageType[] clientReceivedMessageType = { null };
    final int[] clientReceivedMessageFlags = { -1 };
    final boolean[] clientContinuationClosed = { false };
    CompletableFuture<Void> connectFuture = ClientConnection.connect("127.0.0.1", (short) 8037, socketOptions, null, clientBootstrap, new ClientConnectionHandler() {

        @Override
        protected void onConnectionSetup(ClientConnection connection, int errorCode) {
            clientConnectionArray[0] = connection;
        }

        @Override
        protected void onProtocolMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) {
            semaphoreLock.lock();
            semaphore.signal();
            semaphoreLock.unlock();
        }
    });
    final byte[] connectPayload = "test connect payload".getBytes(StandardCharsets.UTF_8);
    connectFuture.get(1, TimeUnit.SECONDS);
    assertNotNull(clientConnectionArray[0]);
    semaphoreLock.lock();
    semaphore.await(1, TimeUnit.SECONDS);
    assertNotNull(serverConnections[0]);
    clientConnectionArray[0].sendProtocolMessage(null, connectPayload, MessageType.Connect, 0);
    semaphore.await(1, TimeUnit.SECONDS);
    String operationName = "testOperation";
    ClientConnectionContinuation continuation = clientConnectionArray[0].newStream(new ClientConnectionContinuationHandler() {

        @Override
        protected void onContinuationMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) {
            semaphoreLock.lock();
            clientReceivedMessageHeaders[0] = headers;
            clientReceivedMessageType[0] = messageType;
            clientReceivedMessageFlags[0] = messageFlags;
            clientReceivedPayload[0] = payload;
            semaphoreLock.unlock();
        }

        @Override
        protected void onContinuationClosed() {
            semaphoreLock.lock();
            clientContinuationClosed[0] = true;
            semaphore.signal();
            semaphoreLock.unlock();
            super.onContinuationClosed();
        }
    });
    assertNotNull(continuation);
    final byte[] operationPayload = "{\"message\": \"message payload\"}".getBytes(StandardCharsets.UTF_8);
    Header clientStrHeader = Header.createHeader("clientStrHeaderName", "clientStrHeaderValue");
    Header clientIntHeader = Header.createHeader("clientIntHeaderName", 35);
    List<Header> clientHeaders = new ArrayList<>();
    clientHeaders.add(clientStrHeader);
    clientHeaders.add(clientIntHeader);
    continuation.activate(operationName, clientHeaders, operationPayload, MessageType.ApplicationMessage, 0).get(1, TimeUnit.SECONDS);
    semaphore.await(1, TimeUnit.SECONDS);
    assertArrayEquals(responsePayload, clientReceivedPayload[0]);
    assertEquals(MessageType.ApplicationError, clientReceivedMessageType[0]);
    assertEquals(MessageFlags.TerminateStream.getByteValue(), clientReceivedMessageFlags[0]);
    assertNotNull(receivedHeadersServer[0]);
    assertEquals(clientStrHeader.getName(), receivedHeadersServer[0].get(0).getName());
    assertEquals(clientStrHeader.getValueAsString(), receivedHeadersServer[0].get(0).getValueAsString());
    assertEquals(clientIntHeader.getName(), receivedHeadersServer[0].get(1).getName());
    assertEquals(clientIntHeader.getValueAsInt(), receivedHeadersServer[0].get(1).getValueAsInt());
    assertEquals(serverStrHeader.getName(), clientReceivedMessageHeaders[0].get(0).getName());
    assertEquals(serverStrHeader.getValueAsString(), clientReceivedMessageHeaders[0].get(0).getValueAsString());
    assertEquals(serverIntHeader.getName(), clientReceivedMessageHeaders[0].get(1).getName());
    assertEquals(serverIntHeader.getValueAsInt(), clientReceivedMessageHeaders[0].get(1).getValueAsInt());
    assertTrue(clientContinuationClosed[0]);
    clientConnectionArray[0].getClosedFuture().get(1, TimeUnit.SECONDS);
    serverConnections[0].getClosedFuture().get(1, TimeUnit.SECONDS);
    semaphoreLock.unlock();
    assertTrue(connectionShutdown[0]);
    assertNotNull(receivedOperationName[0]);
    assertEquals(operationName, receivedOperationName[0]);
    assertEquals(new String(operationPayload, StandardCharsets.UTF_8), receivedContinuationPayload[0]);
    listener.close();
    listener.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
    bootstrap.close();
    clientBootstrap.close();
    clientBootstrap.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
    elGroup.close();
    elGroup.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
    socketOptions.close();
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) Test(org.junit.Test)

Example 5 with ClientBootstrap

use of software.amazon.awssdk.crt.io.ClientBootstrap in project aws-crt-java by awslabs.

the class HttpClientConnectionManagerTest method createConnectionManager.

private HttpClientConnectionManager createConnectionManager(URI uri, int numThreads, int numConnections) {
    try (EventLoopGroup eventLoopGroup = new EventLoopGroup(1);
        HostResolver resolver = new HostResolver(eventLoopGroup);
        ClientBootstrap bootstrap = new ClientBootstrap(eventLoopGroup, resolver);
        SocketOptions sockOpts = new SocketOptions();
        TlsContext tlsContext = createHttpClientTlsContext()) {
        HttpClientConnectionManagerOptions options = new HttpClientConnectionManagerOptions();
        options.withClientBootstrap(bootstrap).withSocketOptions(sockOpts).withTlsContext(tlsContext).withUri(uri).withMaxConnections(numConnections);
        return HttpClientConnectionManager.create(options);
    }
}
Also used : EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) HttpClientConnectionManagerOptions(software.amazon.awssdk.crt.http.HttpClientConnectionManagerOptions) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) TlsContext(software.amazon.awssdk.crt.io.TlsContext) HostResolver(software.amazon.awssdk.crt.io.HostResolver)

Aggregations

ClientBootstrap (software.amazon.awssdk.crt.io.ClientBootstrap)25 EventLoopGroup (software.amazon.awssdk.crt.io.EventLoopGroup)24 SocketOptions (software.amazon.awssdk.crt.io.SocketOptions)18 HostResolver (software.amazon.awssdk.crt.io.HostResolver)16 CompletableFuture (java.util.concurrent.CompletableFuture)7 Test (org.junit.Test)7 TlsContext (software.amazon.awssdk.crt.io.TlsContext)7 ExecutionException (java.util.concurrent.ExecutionException)6 EventStreamRPCConnection (software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection)6 EventStreamRPCConnectionConfig (software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig)6 ArrayList (java.util.ArrayList)5 LinkedList (java.util.LinkedList)5 List (java.util.List)5 TimeoutException (java.util.concurrent.TimeoutException)5 Test (org.junit.jupiter.api.Test)5 Header (software.amazon.awssdk.crt.eventstream.Header)5 ServerBootstrap (software.amazon.awssdk.crt.io.ServerBootstrap)5 TestIpcServiceHandler (software.amazon.awssdk.eventstreamrpc.test.TestIpcServiceHandler)5 Condition (java.util.concurrent.locks.Condition)3 Lock (java.util.concurrent.locks.Lock)3