Search in sources :

Example 6 with HttpClientConnection

use of org.apache.hc.core5.http.io.HttpClientConnection in project httpcomponents-core by apache.

the class HttpRequester method execute.

public ClassicHttpResponse execute(final HttpHost targetHost, final ClassicHttpRequest request, final HttpResponseInformationCallback informationCallback, final Timeout connectTimeout, final HttpContext context) throws HttpException, IOException {
    Args.notNull(targetHost, "HTTP host");
    Args.notNull(request, "HTTP request");
    final Future<PoolEntry<HttpHost, HttpClientConnection>> leaseFuture = connPool.lease(targetHost, null, connectTimeout, null);
    final PoolEntry<HttpHost, HttpClientConnection> poolEntry;
    final Timeout timeout = Timeout.defaultsToDisabled(connectTimeout);
    try {
        poolEntry = leaseFuture.get(timeout.getDuration(), timeout.getTimeUnit());
    } catch (final InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new InterruptedIOException(ex.getMessage());
    } catch (final ExecutionException ex) {
        throw new HttpException("Unexpected failure leasing connection", ex);
    } catch (final TimeoutException ex) {
        throw new ConnectionRequestTimeoutException("Connection request timeout");
    }
    final PoolEntryHolder connectionHolder = new PoolEntryHolder(poolEntry);
    try {
        HttpClientConnection connection = poolEntry.getConnection();
        if (connection == null) {
            final Socket socket = createSocket(targetHost);
            connection = connectFactory.createConnection(socket);
            poolEntry.assignConnection(connection);
        }
        if (request.getAuthority() == null) {
            request.setAuthority(new URIAuthority(targetHost.getHostName(), targetHost.getPort()));
        }
        final ClassicHttpResponse response = execute(connection, request, informationCallback, context);
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new HttpEntityWrapper(entity) {

                private void releaseConnection() throws IOException {
                    try {
                        final HttpClientConnection localConn = connectionHolder.getConnection();
                        if (localConn != null) {
                            if (requestExecutor.keepAlive(request, response, localConn, context)) {
                                if (super.isStreaming()) {
                                    Closer.close(super.getContent());
                                }
                                connectionHolder.releaseConnection();
                            }
                        }
                    } finally {
                        connectionHolder.discardConnection();
                    }
                }

                private void abortConnection() {
                    connectionHolder.discardConnection();
                }

                @Override
                public boolean isStreaming() {
                    return true;
                }

                @Override
                public InputStream getContent() throws IOException {
                    return new EofSensorInputStream(super.getContent(), new EofSensorWatcher() {

                        @Override
                        public boolean eofDetected(final InputStream wrapped) throws IOException {
                            releaseConnection();
                            return false;
                        }

                        @Override
                        public boolean streamClosed(final InputStream wrapped) throws IOException {
                            releaseConnection();
                            return false;
                        }

                        @Override
                        public boolean streamAbort(final InputStream wrapped) throws IOException {
                            abortConnection();
                            return false;
                        }
                    });
                }

                @Override
                public void writeTo(final OutputStream outStream) throws IOException {
                    try {
                        if (outStream != null) {
                            super.writeTo(outStream);
                        }
                        close();
                    } catch (final IOException | RuntimeException ex) {
                        abortConnection();
                    }
                }

                @Override
                public void close() throws IOException {
                    releaseConnection();
                }
            });
        } else {
            final HttpClientConnection localConn = connectionHolder.getConnection();
            if (!requestExecutor.keepAlive(request, response, localConn, context)) {
                localConn.close();
            }
            connectionHolder.releaseConnection();
        }
        return response;
    } catch (final HttpException | IOException | RuntimeException ex) {
        connectionHolder.discardConnection();
        throw ex;
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) URIAuthority(org.apache.hc.core5.net.URIAuthority) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) OutputStream(java.io.OutputStream) EofSensorWatcher(org.apache.hc.core5.http.io.EofSensorWatcher) HttpEntityWrapper(org.apache.hc.core5.http.io.entity.HttpEntityWrapper) EofSensorInputStream(org.apache.hc.core5.http.io.EofSensorInputStream) HttpHost(org.apache.hc.core5.http.HttpHost) HttpException(org.apache.hc.core5.http.HttpException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) ConnectionRequestTimeoutException(org.apache.hc.core5.http.ConnectionRequestTimeoutException) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) ConnectionRequestTimeoutException(org.apache.hc.core5.http.ConnectionRequestTimeoutException) Timeout(org.apache.hc.core5.util.Timeout) EofSensorInputStream(org.apache.hc.core5.http.io.EofSensorInputStream) InputStream(java.io.InputStream) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) PoolEntry(org.apache.hc.core5.pool.PoolEntry) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket)

Example 7 with HttpClientConnection

use of org.apache.hc.core5.http.io.HttpClientConnection in project httpcomponents-core by apache.

the class HttpRequester method execute.

public <T> T execute(final HttpClientConnection connection, final ClassicHttpRequest request, final HttpContext context, final HttpClientResponseHandler<T> responseHandler) throws HttpException, IOException {
    try (final ClassicHttpResponse response = execute(connection, request, context)) {
        final T result = responseHandler.handleResponse(response);
        EntityUtils.consume(response.getEntity());
        final boolean keepAlive = requestExecutor.keepAlive(request, response, connection, context);
        if (!keepAlive) {
            connection.close();
        }
        return result;
    } catch (final HttpException | IOException | RuntimeException ex) {
        connection.close(CloseMode.IMMEDIATE);
        throw ex;
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException)

Example 8 with HttpClientConnection

use of org.apache.hc.core5.http.io.HttpClientConnection in project httpcomponents-core by apache.

the class TestHttpRequestExecutor method testInvalidInput.

@Test
public void testInvalidInput() throws Exception {
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.GET, "/");
    final ClassicHttpResponse response = new BasicClassicHttpResponse(200, "OK");
    final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
    final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.execute(null, conn, context);
    });
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.execute(request, null, context);
    });
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.execute(request, conn, null);
    });
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.preProcess(null, httprocessor, context);
    });
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.preProcess(request, null, context);
    });
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.preProcess(request, httprocessor, null);
    });
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.postProcess(null, httprocessor, context);
    });
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.postProcess(response, null, context);
    });
    Assertions.assertThrows(NullPointerException.class, () -> {
        final HttpRequestExecutor executor = new HttpRequestExecutor();
        executor.postProcess(response, httprocessor, null);
    });
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 9 with HttpClientConnection

use of org.apache.hc.core5.http.io.HttpClientConnection in project httpcomponents-core by apache.

the class TestHttpRequestExecutor method testBasicExecution.

@Test
public void testBasicExecution() throws Exception {
    final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);
    final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
    final HttpRequestExecutor executor = new HttpRequestExecutor();
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.GET, "/");
    executor.preProcess(request, httprocessor, context);
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.when(conn.receiveResponseHeader()).thenReturn(new BasicClassicHttpResponse(200, "OK"));
    final ClassicHttpResponse response = executor.execute(request, conn, context);
    Mockito.verify(conn).sendRequestHeader(request);
    Mockito.verify(conn).flush();
    Mockito.verify(conn).receiveResponseHeader();
    Mockito.verify(conn).receiveResponseEntity(response);
    executor.postProcess(response, httprocessor, context);
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
    Assertions.assertSame(request, context.getRequest());
    Assertions.assertSame(response, context.getResponse());
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 10 with HttpClientConnection

use of org.apache.hc.core5.http.io.HttpClientConnection in project httpcomponents-core by apache.

the class TestHttpRequestExecutor method testExecutionEntityEnclosingRequestWithExpectContinueFailure.

@Test
public void testExecutionEntityEnclosingRequestWithExpectContinueFailure() throws Exception {
    final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);
    final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
    final HttpRequestExecutor executor = new HttpRequestExecutor();
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/");
    request.addHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE);
    final HttpEntity entity = Mockito.mock(HttpEntity.class);
    request.setEntity(entity);
    executor.preProcess(request, httprocessor, context);
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.when(conn.receiveResponseHeader()).thenReturn(new BasicClassicHttpResponse(402, "OK"));
    Mockito.when(conn.isDataAvailable(ArgumentMatchers.any(Timeout.class))).thenReturn(Boolean.TRUE);
    final ClassicHttpResponse response = executor.execute(request, conn, context);
    Mockito.verify(conn).sendRequestHeader(request);
    Mockito.verify(conn, Mockito.never()).sendRequestEntity(request);
    Mockito.verify(conn).terminateRequest(request);
    Mockito.verify(conn, Mockito.times(2)).flush();
    Mockito.verify(conn).isDataAvailable(Timeout.ofMilliseconds(3000));
    Mockito.verify(conn).receiveResponseHeader();
    Mockito.verify(conn).receiveResponseEntity(response);
    executor.postProcess(response, httprocessor, context);
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) Timeout(org.apache.hc.core5.util.Timeout) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Aggregations

HttpClientConnection (org.apache.hc.core5.http.io.HttpClientConnection)16 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)14 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)12 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)12 HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)12 Test (org.junit.jupiter.api.Test)12 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)10 HttpProcessor (org.apache.hc.core5.http.protocol.HttpProcessor)10 HttpEntity (org.apache.hc.core5.http.HttpEntity)7 Timeout (org.apache.hc.core5.util.Timeout)6 IOException (java.io.IOException)4 HttpException (org.apache.hc.core5.http.HttpException)3 HttpHost (org.apache.hc.core5.http.HttpHost)3 InterruptedIOException (java.io.InterruptedIOException)2 HttpResponse (org.apache.hc.core5.http.HttpResponse)2 HttpRequestExecutor (org.apache.hc.core5.http.impl.io.HttpRequestExecutor)2 HttpResponseInformationCallback (org.apache.hc.core5.http.io.HttpResponseInformationCallback)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Socket (java.net.Socket)1