Search in sources :

Example 1 with ServerBootstrap

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

the class ServerListenerTest method testBindErrorPropagates.

@Test
public void testBindErrorPropagates() throws ExecutionException, InterruptedException, 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);
    ServerListener listener1 = new ServerListener("127.0.0.1", (short) 8039, socketOptions, null, bootstrap, new ServerListenerHandler() {

        public ServerConnectionHandler onNewConnection(ServerConnection serverConnection, int errorCode) {
            return null;
        }

        public void onConnectionShutdown(ServerConnection serverConnection, int errorCode) {
        }
    });
    assertNotNull(listener1);
    boolean exceptionThrown = false;
    try {
        ServerListener listener2 = new ServerListener("127.0.0.1", (short) 8039, socketOptions, null, bootstrap, new ServerListenerHandler() {

            public ServerConnectionHandler onNewConnection(ServerConnection serverConnection, int errorCode) {
                return null;
            }

            public void onConnectionShutdown(ServerConnection serverConnection, int errorCode) {
            }
        });
    } catch (CrtRuntimeException ex) {
        assertTrue(ex.getMessage().contains("AWS_IO_SOCKET_ADDRESS_IN_USE(1054), Socket address already in use."));
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown);
    listener1.close();
    listener1.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
    bootstrap.close();
    elGroup.close();
    elGroup.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
    socketOptions.close();
}
Also used : EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap) Test(org.junit.Test)

Example 2 with ServerBootstrap

use of software.amazon.awssdk.crt.io.ServerBootstrap 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 3 with ServerBootstrap

use of software.amazon.awssdk.crt.io.ServerBootstrap in project aws-iot-device-sdk-java-v2 by aws.

the class RpcServer method runServer.

/**
 * Runs the server in the constructor supplied event loop group
 */
public void runServer() {
    validateServiceHandler();
    if (!serverRunning.compareAndSet(false, true)) {
        throw new IllegalStateException("Failed to start IpcServer. It's already started or has not completed a prior shutdown!");
    }
    serverBootstrap = new ServerBootstrap(eventLoopGroup);
    tlsContext = tlsContextOptions != null ? new ServerTlsContext(tlsContextOptions) : null;
    listener = new ServerListener(hostname, (short) port, socketOptions, tlsContext, serverBootstrap, new ServerListenerHandler() {

        @Override
        public ServerConnectionHandler onNewConnection(ServerConnection serverConnection, int errorCode) {
            try {
                LOGGER.info("New connection code [" + CRT.awsErrorName(errorCode) + "] for " + serverConnection.getResourceLogDescription());
                final ServiceOperationMappingContinuationHandler operationHandler = new ServiceOperationMappingContinuationHandler(serverConnection, eventStreamRPCServiceHandler);
                return operationHandler;
            } catch (Throwable e) {
                LOGGER.error("Throwable caught in new connection: " + e.getMessage(), e);
                return null;
            }
        }

        @Override
        public void onConnectionShutdown(ServerConnection serverConnection, int errorCode) {
            LOGGER.info("Server connection closed code [" + CRT.awsErrorString(errorCode) + "]: " + serverConnection.getResourceLogDescription());
        }
    });
    boundPort = listener.getBoundPort();
    LOGGER.info("IpcServer started...");
}
Also used : ServerListenerHandler(software.amazon.awssdk.crt.eventstream.ServerListenerHandler) ServerTlsContext(software.amazon.awssdk.crt.io.ServerTlsContext) ServerConnection(software.amazon.awssdk.crt.eventstream.ServerConnection) ServerListener(software.amazon.awssdk.crt.eventstream.ServerListener) ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap)

Example 4 with ServerBootstrap

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

the class ServerBootstrapTest method testCreateDestroy.

@Test
public void testCreateDestroy() throws ExecutionException, InterruptedException {
    EventLoopGroup elg = new EventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap(elg);
    assertNotNull(bootstrap);
    bootstrap.close();
    elg.close();
}
Also used : EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap) Test(org.junit.Test)

Example 5 with ServerBootstrap

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

the class ServerListenerTest method testSetupAndTearDown.

@Test
public void testSetupAndTearDown() throws ExecutionException, InterruptedException, 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);
    ServerListener listener = new ServerListener("127.0.0.1", (short) 8038, socketOptions, null, bootstrap, new ServerListenerHandler() {

        public ServerConnectionHandler onNewConnection(ServerConnection serverConnection, int errorCode) {
            return null;
        }

        public void onConnectionShutdown(ServerConnection serverConnection, int errorCode) {
        }
    });
    listener.close();
    listener.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
    bootstrap.close();
    elGroup.close();
    elGroup.getShutdownCompleteFuture().get(1, TimeUnit.SECONDS);
    socketOptions.close();
}
Also used : EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) ServerBootstrap(software.amazon.awssdk.crt.io.ServerBootstrap) Test(org.junit.Test)

Aggregations

ServerBootstrap (software.amazon.awssdk.crt.io.ServerBootstrap)12 Test (org.junit.Test)11 EventLoopGroup (software.amazon.awssdk.crt.io.EventLoopGroup)11 SocketOptions (software.amazon.awssdk.crt.io.SocketOptions)10 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Condition (java.util.concurrent.locks.Condition)6 Lock (java.util.concurrent.locks.Lock)6 ReentrantLock (java.util.concurrent.locks.ReentrantLock)6 ClientBootstrap (software.amazon.awssdk.crt.io.ClientBootstrap)5 InetSocketAddress (java.net.InetSocketAddress)3 Socket (java.net.Socket)3 SocketAddress (java.net.SocketAddress)3 ByteBuffer (java.nio.ByteBuffer)2 CrtRuntimeException (software.amazon.awssdk.crt.CrtRuntimeException)2 IOException (java.io.IOException)1 StandardCharsets (java.nio.charset.StandardCharsets)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeUnit (java.util.concurrent.TimeUnit)1 TimeoutException (java.util.concurrent.TimeoutException)1