Search in sources :

Example 6 with StringWriteChannelListener

use of io.undertow.util.StringWriteChannelListener in project light-4j by networknt.

the class OauthHelper method getToken.

public static TokenResponse getToken(TokenRequest tokenRequest, boolean http2) throws ClientException {
    final AtomicReference<TokenResponse> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI(tokenRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, http2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        String requestBody = getEncodedString(tokenRequest);
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(tokenRequest.getUri());
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
                request.getRequestHeaders().put(Headers.AUTHORIZATION, getBasicAuthHeader(tokenRequest.getClientId(), tokenRequest.getClientSecret()));
                connection.sendRequest(request, new ClientCallback<ClientExchange>() {

                    @Override
                    public void completed(ClientExchange result) {
                        new StringWriteChannelListener(requestBody).setup(result.getRequestChannel());
                        result.setResponseListener(new ClientCallback<ClientExchange>() {

                            @Override
                            public void completed(ClientExchange result) {
                                new StringReadChannelListener(Http2Client.POOL) {

                                    @Override
                                    protected void stringDone(String string) {
                                        logger.debug("getToken response = " + string);
                                        reference.set(handleResponse(string));
                                        latch.countDown();
                                    }

                                    @Override
                                    protected void error(IOException e) {
                                        logger.error("IOException:", e);
                                        latch.countDown();
                                    }
                                }.setup(result.getResponseChannel());
                            }

                            @Override
                            public void failed(IOException e) {
                                logger.error("IOException:", e);
                                latch.countDown();
                            }
                        });
                    }

                    @Override
                    public void failed(IOException e) {
                        logger.error("IOException:", e);
                        latch.countDown();
                    }
                });
            }
        });
        latch.await(4, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    return reference.get();
}
Also used : StringReadChannelListener(io.undertow.util.StringReadChannelListener) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) REDIRECT_URI(com.networknt.client.oauth.TokenRequest.REDIRECT_URI) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException)

Example 7 with StringWriteChannelListener

use of io.undertow.util.StringWriteChannelListener in project undertow by undertow-io.

the class WebSocketClient13TestCase method testTextMessage.

@Test
public void testTextMessage() throws Exception {
    final WebSocketChannel webSocketChannel = WebSocketClient.connectionBuilder(worker, DefaultServer.getBufferPool(), new URI(DefaultServer.getDefaultServerURL())).connect().get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();
    webSocketChannel.getReceiveSetter().set(new AbstractReceiveListener() {

        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
            String data = message.getData();
            result.set(data);
            latch.countDown();
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            super.onError(channel, error);
            error.printStackTrace();
            latch.countDown();
        }
    });
    webSocketChannel.resumeReceives();
    StreamSinkFrameChannel sendChannel = webSocketChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener("Hello World").setup(sendChannel);
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals("Hello World", result.get());
    webSocketChannel.sendClose();
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) Test(org.junit.Test)

Example 8 with StringWriteChannelListener

use of io.undertow.util.StringWriteChannelListener in project undertow by undertow-io.

the class WebSocketClient13TestCase method testTextMessageSecure.

public void testTextMessageSecure(final String urlProtocol) throws Exception {
    UndertowXnioSsl ssl = new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, DefaultServer.getClientSSLContext());
    final WebSocketClient.ConnectionBuilder connectionBuilder = WebSocketClient.connectionBuilder(worker, DefaultServer.getBufferPool(), new URI(urlProtocol + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostSSLPort("default"))).setSsl(ssl);
    IoFuture<WebSocketChannel> future = connectionBuilder.connect();
    future.await(4, TimeUnit.SECONDS);
    final WebSocketChannel webSocketChannel = future.get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();
    webSocketChannel.getReceiveSetter().set(new AbstractReceiveListener() {

        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
            String data = message.getData();
            result.set(data);
            latch.countDown();
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            super.onError(channel, error);
            error.printStackTrace();
            latch.countDown();
        }
    });
    webSocketChannel.resumeReceives();
    StreamSinkFrameChannel sendChannel = webSocketChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener("Hello World").setup(sendChannel);
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals("Hello World", result.get());
    webSocketChannel.sendClose();
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) WebSocketClient(io.undertow.websockets.client.WebSocketClient) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl)

Example 9 with StringWriteChannelListener

use of io.undertow.util.StringWriteChannelListener in project undertow by undertow-io.

the class WebSocketClient13TestCase method testMessageViaProxy.

@Test
@ProxyIgnore
public void testMessageViaProxy() throws Exception {
    final WebSocketChannel webSocketChannel = WebSocketClient.connectionBuilder(worker, DefaultServer.getBufferPool(), new URI(DefaultServer.getDefaultServerURL())).setProxyUri(new URI("http", null, DefaultServer.getHostAddress("default"), DefaultServer.getHostPort("default") + 10, "/proxy", null, null)).connect().get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();
    webSocketChannel.getReceiveSetter().set(new AbstractReceiveListener() {

        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException {
            String data = message.getData();
            result.set(data);
            latch.countDown();
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            super.onError(channel, error);
            error.printStackTrace();
            latch.countDown();
        }
    });
    webSocketChannel.resumeReceives();
    StreamSinkFrameChannel sendChannel = webSocketChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener("Hello World").setup(sendChannel);
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals("Hello World", result.get());
    webSocketChannel.sendClose();
    Assert.assertEquals("CONNECT " + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default"), connectLog.poll());
}
Also used : WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) Test(org.junit.Test) ProxyIgnore(io.undertow.testutils.ProxyIgnore)

Example 10 with StringWriteChannelListener

use of io.undertow.util.StringWriteChannelListener in project undertow by undertow-io.

the class JsrWebsocketExtensionTestCase method testExtensionsHeaders.

@Test
public void testExtensionsHeaders() throws Exception {
    final String SEC_WEBSOCKET_EXTENSIONS = "permessage-deflate; client_no_context_takeover; client_max_window_bits";
    // List format
    final String SEC_WEBSOCKET_EXTENSIONS_EXPECTED = "[permessage-deflate; client_no_context_takeover]";
    List<WebSocketExtension> extensions = WebSocketExtension.parse(SEC_WEBSOCKET_EXTENSIONS);
    final WebSocketClientNegotiation negotiation = new WebSocketClientNegotiation(null, extensions);
    Set<ExtensionHandshake> extensionHandshakes = new HashSet<>();
    extensionHandshakes.add(new PerMessageDeflateHandshake(true));
    final WebSocketChannel clientChannel = WebSocketClient.connect(DefaultServer.getWorker(), null, DefaultServer.getBufferPool(), OptionMap.EMPTY, new URI(DefaultServer.getDefaultServerURL()), WebSocketVersion.V13, negotiation, extensionHandshakes).get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> result = new AtomicReference<>();
    clientChannel.getReceiveSetter().set(new AbstractReceiveListener() {

        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
            String data = message.getData();
            WebSocketLogger.ROOT_LOGGER.info("onFullTextMessage - Client - Received: " + data.getBytes().length + " bytes . Data: " + data);
            result.set(data);
            latch.countDown();
        }

        @Override
        protected void onFullCloseMessage(WebSocketChannel channel, BufferedBinaryMessage message) {
            message.getData().close();
            WebSocketLogger.ROOT_LOGGER.info("onFullCloseMessage");
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            WebSocketLogger.ROOT_LOGGER.info("onError");
            super.onError(channel, error);
            error.printStackTrace();
            latch.countDown();
        }
    });
    clientChannel.resumeReceives();
    StreamSinkFrameChannel sendChannel = clientChannel.send(WebSocketFrameType.TEXT);
    new StringWriteChannelListener("Hello, World!").setup(sendChannel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertEquals("Hello, World!", result.get());
    clientChannel.sendClose();
    assertEquals(SEC_WEBSOCKET_EXTENSIONS_EXPECTED, debug.getResponseExtensions().toString());
}
Also used : WebSocketExtension(io.undertow.websockets.WebSocketExtension) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) StreamSinkFrameChannel(io.undertow.websockets.core.StreamSinkFrameChannel) URI(java.net.URI) BufferedTextMessage(io.undertow.websockets.core.BufferedTextMessage) WebSocketClientNegotiation(io.undertow.websockets.client.WebSocketClientNegotiation) PerMessageDeflateHandshake(io.undertow.websockets.extensions.PerMessageDeflateHandshake) AbstractReceiveListener(io.undertow.websockets.core.AbstractReceiveListener) ExtensionHandshake(io.undertow.websockets.extensions.ExtensionHandshake) BufferedBinaryMessage(io.undertow.websockets.core.BufferedBinaryMessage) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) HashSet(java.util.HashSet) Test(org.junit.Test) BinaryEndpointTest(io.undertow.websockets.jsr.test.BinaryEndpointTest)

Aggregations

StringWriteChannelListener (io.undertow.util.StringWriteChannelListener)20 IOException (java.io.IOException)19 CountDownLatch (java.util.concurrent.CountDownLatch)13 Test (org.junit.Test)11 URI (java.net.URI)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 AbstractReceiveListener (io.undertow.websockets.core.AbstractReceiveListener)8 BufferedTextMessage (io.undertow.websockets.core.BufferedTextMessage)8 StreamSinkFrameChannel (io.undertow.websockets.core.StreamSinkFrameChannel)8 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)8 StringReadChannelListener (io.undertow.util.StringReadChannelListener)6 ClientCallback (io.undertow.client.ClientCallback)5 ClientExchange (io.undertow.client.ClientExchange)5 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)4 OutputStream (java.io.OutputStream)4 ClientConnection (io.undertow.client.ClientConnection)3 ClientRequest (io.undertow.client.ClientRequest)3 UndertowClient (io.undertow.client.UndertowClient)3 HttpHandler (io.undertow.server.HttpHandler)3 HttpServerExchange (io.undertow.server.HttpServerExchange)3