Search in sources :

Example 86 with ClientConnection

use of io.undertow.client.ClientConnection in project light-rest-4j by networknt.

the class ValidatorHandlerTest method testDeleteWithHeader.

@Test
public void testDeleteWithHeader() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet/111").setMethod(Methods.DELETE);
        request.getRequestHeaders().put(new HttpString("api_key"), "key");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(body);
        Assert.assertEquals("deletePet", body);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpString(io.undertow.util.HttpString) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) ClientConnection(io.undertow.client.ClientConnection) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Example 87 with ClientConnection

use of io.undertow.client.ClientConnection in project light-rest-4j by networknt.

the class ValidatorHandlerTest method testValidPost.

@Test
public void testValidPost() throws Exception {
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        String post = "{\"id\":0,\"category\":{\"id\":0,\"name\":\"string\"},\"name\":\"doggie\",\"photoUrls\":[\"string\"],\"tags\":[{\"id\":0,\"name\":\"string\"}],\"status\":\"available\"}";
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/v2/pet");
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
                request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                connection.sendRequest(request, client.createClientCallback(reference, latch, post));
            }
        });
        latch.await(10, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(body);
        Assert.assertEquals("addPet", body);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpString(io.undertow.util.HttpString) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) ClientConnection(io.undertow.client.ClientConnection) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 88 with ClientConnection

use of io.undertow.client.ClientConnection in project light-4j by networknt.

the class ConsulClientImpl method unregisterService.

@Override
public void unregisterService(String serviceId, String token) {
    String path = "/v1/agent/service/deregister/" + serviceId;
    ClientConnection connection = null;
    try {
        connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        logger.error("Exeption:", e);
    }
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setMethod(Methods.PUT).setPath(path);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        if (token != null)
            request.getRequestHeaders().put(Constants.CONSUL_TOKEN, token);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
        int statusCode = reference.get().getResponseCode();
        if (statusCode >= 300) {
            System.out.println("body = " + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
            throw new Exception("Failed to unregister on Consul: " + statusCode);
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
    } finally {
        IoUtils.safeClose(connection);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) ClientConnection(io.undertow.client.ClientConnection) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpString(io.undertow.util.HttpString) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientRequest(io.undertow.client.ClientRequest)

Example 89 with ClientConnection

use of io.undertow.client.ClientConnection in project light-4j by networknt.

the class ConsulClientImpl method checkPass.

@Override
public void checkPass(String serviceId, String token) {
    if (logger.isDebugEnabled())
        logger.debug("checkPass serviceId = " + serviceId);
    String path = "/v1/agent/check/pass/" + "service:" + serviceId;
    ClientConnection connection = null;
    try {
        connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        logger.error("Exeption:", e);
    }
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setMethod(Methods.PUT).setPath(path);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        if (token != null)
            request.getRequestHeaders().put(Constants.CONSUL_TOKEN, token);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
        int statusCode = reference.get().getResponseCode();
        if (statusCode >= 300) {
            logger.error("Failed to checkPass on Consul: " + statusCode + ":" + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
            throw new Exception("Failed to checkPass on Consul: " + statusCode + ":" + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
        }
    } catch (Exception e) {
        logger.error("CheckPass request exception", e);
    } finally {
        IoUtils.safeClose(connection);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) ClientConnection(io.undertow.client.ClientConnection) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpString(io.undertow.util.HttpString) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientRequest(io.undertow.client.ClientRequest)

Example 90 with ClientConnection

use of io.undertow.client.ClientConnection in project undertow by undertow-io.

the class Http2EndExchangeTestCase method testHttp2EndExchangeWithBrokenConnection.

@Test
public void testHttp2EndExchangeWithBrokenConnection() throws Exception {
    int port = DefaultServer.getHostPort("default");
    final CountDownLatch requestStartedLatch = new CountDownLatch(1);
    final CompletableFuture<String> testResult = new CompletableFuture<>();
    Undertow server = Undertow.builder().addHttpsListener(port + 1, DefaultServer.getHostAddress("default"), DefaultServer.getServerSslContext()).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setSocketOption(Options.REUSE_ADDRESSES, true).setHandler(new BlockingHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (!exchange.getProtocol().equals(Protocols.HTTP_2_0)) {
                testResult.completeExceptionally(new RuntimeException("Not HTTP/2 request"));
                return;
            }
            requestStartedLatch.countDown();
            log.debug("Received Request");
            // do some pretend work
            Thread.sleep(2000);
            if (exchange.isComplete()) {
                testResult.complete("FAILED, exchange ended in the background");
                return;
            }
            try {
                exchange.getOutputStream().write("Bogus Data".getBytes(StandardCharsets.UTF_8));
                exchange.getOutputStream().flush();
                testResult.complete("FAILED, should not have completed successfully");
                return;
            } catch (IOException expected) {
            }
            if (!exchange.isComplete()) {
                testResult.complete("Failed, should have completed the exchange");
            } else {
                testResult.complete("PASSED");
            }
        }
    })).build();
    server.start();
    try {
        ADDRESS = new URI("https://" + DefaultServer.getHostAddress() + ":" + (port + 1));
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    // Create xnio worker
    final Xnio xnio = Xnio.getInstance();
    final XnioWorker xnioWorker = xnio.createWorker(null, DEFAULT_OPTIONS);
    try {
        final UndertowClient client = createClient();
        final ClientConnection connection = client.connect(ADDRESS, xnioWorker, new UndertowXnioSsl(xnioWorker.getXnio(), OptionMap.EMPTY, DefaultServer.getClientSSLContext()), DefaultServer.getBufferPool(), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
        try {
            connection.getIoThread().execute(new Runnable() {

                @Override
                public void run() {
                    final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
                    request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                    connection.sendRequest(request, new ClientCallback<ClientExchange>() {

                        @Override
                        public void completed(ClientExchange result) {
                            try {
                                log.debug("Callback invoked");
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {
                                        try {
                                            requestStartedLatch.await(10, TimeUnit.SECONDS);
                                            result.getRequestChannel().getIoThread().execute(new Runnable() {

                                                @Override
                                                public void run() {
                                                    IoUtils.safeClose(result.getConnection());
                                                    log.debug("Closed Connection");
                                                }
                                            });
                                        } catch (Exception e) {
                                            testResult.completeExceptionally(e);
                                        }
                                    }
                                }).start();
                            } catch (Exception e) {
                                testResult.completeExceptionally(e);
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            testResult.completeExceptionally(e);
                        }
                    });
                }
            });
            Assert.assertEquals("PASSED", testResult.get(10, TimeUnit.SECONDS));
        } finally {
            IoUtils.safeClose(connection);
        }
    } finally {
        stopWorker(xnioWorker);
        server.stop();
        // sleep 1 s to prevent BindException (Address already in use) when running the CI
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignore) {
        }
    }
}
Also used : ClientExchange(io.undertow.client.ClientExchange) ClientCallback(io.undertow.client.ClientCallback) XnioWorker(org.xnio.XnioWorker) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpServerExchange(io.undertow.server.HttpServerExchange) CompletableFuture(java.util.concurrent.CompletableFuture) BlockingHandler(io.undertow.server.handlers.BlockingHandler) Xnio(org.xnio.Xnio) ClientConnection(io.undertow.client.ClientConnection) ClientRequest(io.undertow.client.ClientRequest) HttpHandler(io.undertow.server.HttpHandler) UndertowClient(io.undertow.client.UndertowClient) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) Undertow(io.undertow.Undertow) Test(org.junit.Test)

Aggregations

ClientConnection (io.undertow.client.ClientConnection)120 ClientRequest (io.undertow.client.ClientRequest)113 CountDownLatch (java.util.concurrent.CountDownLatch)107 ClientResponse (io.undertow.client.ClientResponse)104 URI (java.net.URI)101 Test (org.junit.Test)99 AtomicReference (java.util.concurrent.atomic.AtomicReference)94 Http2Client (com.networknt.client.Http2Client)87 ClientException (com.networknt.exception.ClientException)82 ApiException (com.networknt.exception.ApiException)44 IOException (java.io.IOException)41 HttpString (io.undertow.util.HttpString)25 UndertowClient (io.undertow.client.UndertowClient)18 Status (com.networknt.status.Status)17 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)15 SQLException (java.sql.SQLException)12 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)9 ClientCallback (io.undertow.client.ClientCallback)6 ClientExchange (io.undertow.client.ClientExchange)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5