Search in sources :

Example 56 with ClientRequest

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

the class HttpClientConnection method initiateRequest.

private void initiateRequest(HttpClientExchange httpClientExchange) {
    this.requestCount++;
    currentRequest = httpClientExchange;
    pendingResponse = new HttpResponseBuilder();
    ClientRequest request = httpClientExchange.getRequest();
    String connectionString = request.getRequestHeaders().getFirst(Headers.CONNECTION);
    if (connectionString != null) {
        if (Headers.CLOSE.equalToString(connectionString)) {
            state |= CLOSE_REQ;
        } else if (Headers.UPGRADE.equalToString(connectionString)) {
            state |= UPGRADE_REQUESTED;
        }
    } else if (request.getProtocol() != Protocols.HTTP_1_1) {
        state |= CLOSE_REQ;
    }
    if (request.getRequestHeaders().contains(Headers.UPGRADE)) {
        state |= UPGRADE_REQUESTED;
    }
    if (request.getMethod().equals(Methods.CONNECT)) {
        // we treat CONNECT like upgrade requests
        state |= UPGRADE_REQUESTED;
    }
    // setup the client request conduits
    final ConduitStreamSourceChannel sourceChannel = connection.getSourceChannel();
    sourceChannel.setReadListener(clientReadListener);
    sourceChannel.resumeReads();
    ConduitStreamSinkChannel sinkChannel = connection.getSinkChannel();
    StreamSinkConduit conduit = originalSinkConduit;
    HttpRequestConduit httpRequestConduit = new HttpRequestConduit(conduit, bufferPool, request);
    httpClientExchange.setRequestConduit(httpRequestConduit);
    conduit = httpRequestConduit;
    String fixedLengthString = request.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH);
    String transferEncodingString = request.getRequestHeaders().getLast(Headers.TRANSFER_ENCODING);
    boolean hasContent = true;
    if (fixedLengthString != null) {
        try {
            long length = Long.parseLong(fixedLengthString);
            conduit = new ClientFixedLengthStreamSinkConduit(conduit, length, false, false, currentRequest);
            hasContent = length != 0;
        } catch (NumberFormatException e) {
            handleError(e);
            return;
        }
    } else if (transferEncodingString != null) {
        if (!transferEncodingString.toLowerCase(Locale.ENGLISH).contains(Headers.CHUNKED.toString())) {
            handleError(UndertowClientMessages.MESSAGES.unknownTransferEncoding(transferEncodingString));
            return;
        }
        conduit = new ChunkedStreamSinkConduit(conduit, httpClientExchange.getConnection().getBufferPool(), false, false, httpClientExchange.getRequest().getRequestHeaders(), requestFinishListener, httpClientExchange);
    } else {
        conduit = new ClientFixedLengthStreamSinkConduit(conduit, 0, false, false, currentRequest);
        hasContent = false;
    }
    sinkChannel.setConduit(conduit);
    httpClientExchange.invokeReadReadyCallback();
    if (!hasContent) {
        // otherwise it is up to the user
        try {
            sinkChannel.shutdownWrites();
            if (!sinkChannel.flush()) {
                sinkChannel.setWriteListener(ChannelListeners.flushingChannelListener(null, new ChannelExceptionHandler<ConduitStreamSinkChannel>() {

                    @Override
                    public void handleException(ConduitStreamSinkChannel channel, IOException exception) {
                        handleError(exception);
                    }
                }));
                sinkChannel.resumeWrites();
            }
        } catch (Throwable t) {
            handleError(t);
        }
    }
}
Also used : ChunkedStreamSinkConduit(io.undertow.conduits.ChunkedStreamSinkConduit) HttpString(io.undertow.util.HttpString) IOException(java.io.IOException) StreamSinkConduit(org.xnio.conduits.StreamSinkConduit) WriteTimeoutStreamSinkConduit(io.undertow.conduits.WriteTimeoutStreamSinkConduit) BytesSentStreamSinkConduit(io.undertow.conduits.BytesSentStreamSinkConduit) ChunkedStreamSinkConduit(io.undertow.conduits.ChunkedStreamSinkConduit) ChannelExceptionHandler(org.xnio.ChannelExceptionHandler) ConduitStreamSourceChannel(org.xnio.conduits.ConduitStreamSourceChannel) ClientRequest(io.undertow.client.ClientRequest) ConduitStreamSinkChannel(org.xnio.conduits.ConduitStreamSinkChannel)

Example 57 with ClientRequest

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

the class H2CUpgradeContinuationTestCase method sendRequest.

/**
 * Method that sends a GET or POST request adding count number of custom
 * headers and sending contentLength data. GET is used if no content length
 * is passed, POST if contentLength is greater than 0.
 * @param connection The connection to use
 * @param requestCount The number of requests to send
 * @param headersCount The number of custom headers to send
 * @param contentLength The content length to send (POST method used if >0)
 * @throws Exception Some error
 */
private void sendRequest(ClientConnection connection, int requestCount, int headersCount, int contentLength) throws Exception {
    final CountDownLatch latch = new CountDownLatch(requestCount);
    final List<ClientResponse> responses = new CopyOnWriteArrayList<>();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < contentLength; i++) {
        sb.append(i % 10);
    }
    final String content = sb.length() > 0 ? sb.toString() : null;
    connection.getIoThread().execute(new Runnable() {

        @Override
        public void run() {
            for (int i = 0; i < requestCount; i++) {
                final ClientRequest request = new ClientRequest().setMethod(contentLength > 0 ? Methods.POST : Methods.GET).setPath(ECHO_PATH);
                request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                if (contentLength > 0) {
                    request.getRequestHeaders().put(Headers.CONTENT_LENGTH, contentLength);
                }
                for (int j = 0; j < headersCount; j++) {
                    request.getRequestHeaders().put(new HttpString(HEADER_PREFFIX + j), HEADER_PREFFIX + j);
                }
                connection.sendRequest(request, createClientCallback(responses, latch, content));
            }
        }
    });
    latch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals("No responses received from server in 10s", requestCount, responses.size());
    for (int i = 0; i < requestCount; i++) {
        Assert.assertEquals("Response " + i + " code was not OK", StatusCodes.OK, responses.get(i).getResponseCode());
        Assert.assertEquals("Incorrect data received for response " + i, contentLength > 0 ? content : "", responses.get(i).getAttachment(RESPONSE_BODY));
        int headersReturned = 0;
        for (HeaderValues header : responses.get(i).getResponseHeaders()) {
            if (header.getFirst().startsWith(HEADER_PREFFIX)) {
                headersReturned += header.size();
            }
        }
        Assert.assertEquals("Incorrect number of headers returned for response " + i, headersCount, headersReturned);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) HeaderValues(io.undertow.util.HeaderValues) HttpString(io.undertow.util.HttpString) CountDownLatch(java.util.concurrent.CountDownLatch) ClientRequest(io.undertow.client.ClientRequest) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HttpString(io.undertow.util.HttpString)

Example 58 with ClientRequest

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

the class Http2ClientTestCase method testHeadRequest.

@Test
public void testHeadRequest() throws Exception {
    // 
    final UndertowClient client = createClient();
    final List<ClientResponse> responses = new CopyOnWriteArrayList<>();
    final CountDownLatch latch = new CountDownLatch(10);
    final ClientConnection connection = client.connect(ADDRESS, worker, new UndertowXnioSsl(worker.getXnio(), OptionMap.EMPTY, DefaultServer.getClientSSLContext()), DefaultServer.getBufferPool(), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
    try {
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    final ClientRequest request = new ClientRequest().setMethod(Methods.HEAD).setPath(MESSAGE);
                    request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                    connection.sendRequest(request, createClientCallback(responses, latch));
                }
            }
        });
        latch.await(10, TimeUnit.SECONDS);
        Assert.assertEquals(10, responses.size());
        for (final ClientResponse response : responses) {
            Assert.assertEquals("", response.getAttachment(RESPONSE_BODY));
        }
    } finally {
        IoUtils.safeClose(connection);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) UndertowClient(io.undertow.client.UndertowClient) ClientConnection(io.undertow.client.ClientConnection) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) CountDownLatch(java.util.concurrent.CountDownLatch) ClientRequest(io.undertow.client.ClientRequest) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.Test)

Example 59 with ClientRequest

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

the class Http2ClientTestCase method testSimpleBasic.

@Test
public void testSimpleBasic() throws Exception {
    // 
    final UndertowClient client = createClient();
    final List<ClientResponse> responses = new CopyOnWriteArrayList<>();
    final CountDownLatch latch = new CountDownLatch(10);
    final ClientConnection connection = client.connect(ADDRESS, worker, new UndertowXnioSsl(worker.getXnio(), OptionMap.EMPTY, DefaultServer.getClientSSLContext()), DefaultServer.getBufferPool(), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
    try {
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
                    request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                    connection.sendRequest(request, createClientCallback(responses, latch));
                }
            }
        });
        latch.await(10, TimeUnit.SECONDS);
        Assert.assertEquals(10, responses.size());
        for (final ClientResponse response : responses) {
            Assert.assertEquals(message, response.getAttachment(RESPONSE_BODY));
        }
    } finally {
        IoUtils.safeClose(connection);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) UndertowClient(io.undertow.client.UndertowClient) ClientConnection(io.undertow.client.ClientConnection) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) CountDownLatch(java.util.concurrent.CountDownLatch) ClientRequest(io.undertow.client.ClientRequest) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.Test)

Example 60 with ClientRequest

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

the class AjpClientTestCase method testSimpleBasic.

@Test
public void testSimpleBasic() throws Exception {
    // 
    final UndertowClient client = createClient();
    final List<ClientResponse> responses = new CopyOnWriteArrayList<>();
    final CountDownLatch latch = new CountDownLatch(10);
    final ClientConnection connection = client.connect(ADDRESS, worker, DefaultServer.getBufferPool(), OptionMap.EMPTY).get();
    try {
        connection.getIoThread().execute(() -> {
            for (int i = 0; i < 10; i++) {
                final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
                request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                connection.sendRequest(request, createClientCallback(responses, latch));
            }
        });
        assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertEquals(10, responses.size());
        for (final ClientResponse response : responses) {
            Assert.assertEquals(message, response.getAttachment(RESPONSE_BODY));
        }
    } finally {
        IoUtils.safeClose(connection);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) UndertowClient(io.undertow.client.UndertowClient) ClientConnection(io.undertow.client.ClientConnection) CountDownLatch(java.util.concurrent.CountDownLatch) ClientRequest(io.undertow.client.ClientRequest) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.Test)

Aggregations

ClientRequest (io.undertow.client.ClientRequest)117 ClientConnection (io.undertow.client.ClientConnection)112 CountDownLatch (java.util.concurrent.CountDownLatch)109 ClientResponse (io.undertow.client.ClientResponse)105 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