Search in sources :

Example 1 with ClientRequest

use of io.undertow.client.ClientRequest in project camel by apache.

the class UndertowProducer method process.

@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    ClientConnection connection = null;
    try {
        final UndertowClient client = UndertowClient.getInstance();
        IoFuture<ClientConnection> connect = client.connect(endpoint.getHttpURI(), worker, pool, options);
        // creating the url to use takes 2-steps
        final String exchangeUri = UndertowHelper.createURL(exchange, getEndpoint());
        final URI uri = UndertowHelper.createURI(exchange, exchangeUri, getEndpoint());
        final String pathAndQuery = URISupport.pathAndQueryOf(uri);
        // what http method to use
        HttpString method = UndertowHelper.createMethod(exchange, endpoint, exchange.getIn().getBody() != null);
        ClientRequest request = new ClientRequest();
        request.setProtocol(Protocols.HTTP_1_1);
        request.setPath(pathAndQuery);
        request.setMethod(method);
        final HeaderMap requestHeaders = request.getRequestHeaders();
        // Set the Host header
        Message message = exchange.getIn();
        final String host = message.getHeader("Host", String.class);
        requestHeaders.put(Headers.HOST, Optional.ofNullable(host).orElseGet(() -> uri.getAuthority()));
        Object body = getRequestBody(request, exchange);
        TypeConverter tc = endpoint.getCamelContext().getTypeConverter();
        ByteBuffer bodyAsByte = tc.tryConvertTo(ByteBuffer.class, body);
        if (body != null) {
            requestHeaders.put(Headers.CONTENT_LENGTH, bodyAsByte.array().length);
        }
        if (getEndpoint().getCookieHandler() != null) {
            Map<String, List<String>> cookieHeaders = getEndpoint().getCookieHandler().loadCookies(exchange, uri);
            for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
                requestHeaders.putAll(new HttpString(entry.getKey()), entry.getValue());
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing http {} method: {}", method, pathAndQuery);
        }
        connection = connect.get();
        connection.sendRequest(request, new UndertowProducerCallback(connection, bodyAsByte, exchange, callback));
    } catch (Exception e) {
        IOHelper.close(connection);
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // use async routing engine
    return false;
}
Also used : Message(org.apache.camel.Message) UndertowClient(io.undertow.client.UndertowClient) HttpString(io.undertow.util.HttpString) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) TypeConverter(org.apache.camel.TypeConverter) HeaderMap(io.undertow.util.HeaderMap) ClientConnection(io.undertow.client.ClientConnection) LinkedList(java.util.LinkedList) List(java.util.List) HashMap(java.util.HashMap) OptionMap(org.xnio.OptionMap) HeaderMap(io.undertow.util.HeaderMap) Map(java.util.Map) ClientRequest(io.undertow.client.ClientRequest) HttpString(io.undertow.util.HttpString)

Example 2 with ClientRequest

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

the class ValidatorHandlerTest method testDeleteWithoutHeader.

@Test
public void testDeleteWithoutHeader() 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("/v1/pets/111").setMethod(Methods.DELETE);
        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(400, statusCode);
    if (statusCode == 400) {
        Status status = Config.getInstance().getMapper().readValue(body, Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR11017", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) 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 3 with ClientRequest

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

the class ValidatorHandlerTest method testInvalidPost.

@Test
public void testInvalidPost() 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 = "{\"name\":\"Pinky\", \"photoUrl\": \"http://www.photo.com/1.jpg\"}";
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
                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(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper().readValue(body, Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) 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 4 with ClientRequest

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

the class ValidatorHandlerTest method testInvalidMethod.

@Test
public void testInvalidMethod() 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("/v1/pets").setMethod(Methods.DELETE);
        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();
    Assert.assertEquals(405, statusCode);
    if (statusCode == 405) {
        Status status = Config.getInstance().getMapper().readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10008", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) ClientConnection(io.undertow.client.ClientConnection) AtomicReference(java.util.concurrent.atomic.AtomicReference) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 5 with ClientRequest

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

the class ValidatorHandlerTest method testValidPostWithoutHeaders.

@Test
public void testValidPostWithoutHeaders() 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("/v1/pets");
                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(400, statusCode);
    if (statusCode == 400) {
        Status status = Config.getInstance().getMapper().readValue(body, Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR11017", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) 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)

Aggregations

ClientRequest (io.undertow.client.ClientRequest)118 ClientConnection (io.undertow.client.ClientConnection)113 CountDownLatch (java.util.concurrent.CountDownLatch)109 ClientResponse (io.undertow.client.ClientResponse)106 URI (java.net.URI)99 Test (org.junit.Test)97 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)42 HttpString (io.undertow.util.HttpString)27 Status (com.networknt.status.Status)17 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)17 UndertowClient (io.undertow.client.UndertowClient)16 SQLException (java.sql.SQLException)12 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)7 ClientCallback (io.undertow.client.ClientCallback)6 ClientExchange (io.undertow.client.ClientExchange)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5