use of org.apache.hc.core5.http.ConnectionReuseStrategy in project httpcomponents-core by apache.
the class Http1IntegrationTest method testTruncatedChunk.
@Test
public void testTruncatedChunk() throws Exception {
final InetSocketAddress serverEndpoint = server.start(new InternalServerHttp1EventHandlerFactory(HttpProcessors.server(), (request, context) -> new MessageExchangeHandler<String>(new StringAsyncEntityConsumer()) {
@Override
protected void handle(final Message<HttpRequest, String> request, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws IOException, HttpException {
responseTrigger.submitResponse(new BasicResponseProducer(new StringAsyncEntityProducer("useful stuff")), context);
}
}, Http1Config.DEFAULT, CharCodingConfig.DEFAULT, DefaultConnectionReuseStrategy.INSTANCE, scheme == URIScheme.HTTPS ? SSLTestContexts.createServerSSLContext() : null, null, null) {
@Override
protected ServerHttp1StreamDuplexer createServerHttp1StreamDuplexer(final ProtocolIOSession ioSession, final HttpProcessor httpProcessor, final HandlerFactory<AsyncServerExchangeHandler> exchangeHandlerFactory, final Http1Config http1Config, final CharCodingConfig connectionConfig, final ConnectionReuseStrategy connectionReuseStrategy, final NHttpMessageParser<HttpRequest> incomingMessageParser, final NHttpMessageWriter<HttpResponse> outgoingMessageWriter, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final Http1StreamListener streamListener) {
return new ServerHttp1StreamDuplexer(ioSession, httpProcessor, exchangeHandlerFactory, scheme.id, http1Config, connectionConfig, connectionReuseStrategy, incomingMessageParser, outgoingMessageWriter, incomingContentStrategy, outgoingContentStrategy, streamListener) {
@Override
protected ContentEncoder createContentEncoder(final long len, final WritableByteChannel channel, final SessionOutputBuffer buffer, final BasicHttpTransportMetrics metrics) throws HttpException {
if (len == ContentLengthStrategy.CHUNKED) {
return new BrokenChunkEncoder(channel, buffer, metrics);
} else {
return super.createContentEncoder(len, channel, buffer, metrics);
}
}
};
}
});
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final AsyncRequestProducer requestProducer = new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello"));
final StringAsyncEntityConsumer entityConsumer = new StringAsyncEntityConsumer() {
@Override
public void releaseResources() {
// Do not clear internal content buffer
}
};
final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(entityConsumer);
final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(requestProducer, responseConsumer, null);
final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()));
final Throwable cause = exception.getCause();
Assertions.assertTrue(cause instanceof MalformedChunkCodingException);
Assertions.assertEquals("garbage", entityConsumer.generateContent());
}
use of org.apache.hc.core5.http.ConnectionReuseStrategy in project httpcomponents-core by apache.
the class ClientHttp1StreamDuplexer method execute.
@Override
void execute(final RequestExecutionCommand executionCommand) throws HttpException, IOException {
final AsyncClientExchangeHandler exchangeHandler = executionCommand.getExchangeHandler();
final HttpCoreContext context = HttpCoreContext.adapt(executionCommand.getContext());
context.setAttribute(HttpCoreContext.SSL_SESSION, getSSLSession());
context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, getEndpointDetails());
final ClientHttp1StreamHandler handler = new ClientHttp1StreamHandler(outputChannel, httpProcessor, http1Config, connectionReuseStrategy, exchangeHandler, context);
pipeline.add(handler);
outgoing = handler;
if (handler.isOutputReady()) {
handler.produceOutput();
}
}
use of org.apache.hc.core5.http.ConnectionReuseStrategy in project httpcomponents-core by apache.
the class DefaultConnectionReuseStrategy method keepAlive.
// see interface ConnectionReuseStrategy
@Override
public boolean keepAlive(final HttpRequest request, final HttpResponse response, final HttpContext context) {
Args.notNull(response, "HTTP response");
if (request != null) {
final Iterator<String> ti = new BasicTokenIterator(request.headerIterator(HttpHeaders.CONNECTION));
while (ti.hasNext()) {
final String token = ti.next();
if (HeaderElements.CLOSE.equalsIgnoreCase(token)) {
return false;
}
}
}
// returns content as part of a HTTP 204 response.
if (response.getCode() == HttpStatus.SC_NO_CONTENT) {
final Header clh = response.getFirstHeader(HttpHeaders.CONTENT_LENGTH);
if (clh != null) {
try {
final long contentLen = Long.parseLong(clh.getValue());
if (contentLen > 0) {
return false;
}
} catch (final NumberFormatException ex) {
// fall through
}
}
if (response.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
return false;
}
}
// Check for a self-terminating entity. If the end of the entity will
// be indicated by closing the connection, there is no keep-alive.
final Header teh = response.getFirstHeader(HttpHeaders.TRANSFER_ENCODING);
if (teh != null) {
if (!HeaderElements.CHUNKED_ENCODING.equalsIgnoreCase(teh.getValue())) {
return false;
}
} else {
final String method = request != null ? request.getMethod() : null;
if (MessageSupport.canResponseHaveBody(method, response) && response.countHeaders(HttpHeaders.CONTENT_LENGTH) != 1) {
return false;
}
}
// Check for the "Connection" header. If that is absent, check for
// the "Proxy-Connection" header. The latter is an unspecified and
// broken but unfortunately common extension of HTTP.
Iterator<Header> headerIterator = response.headerIterator(HttpHeaders.CONNECTION);
if (!headerIterator.hasNext()) {
headerIterator = response.headerIterator("Proxy-Connection");
}
final ProtocolVersion ver = response.getVersion() != null ? response.getVersion() : context.getProtocolVersion();
if (headerIterator.hasNext()) {
if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
final Iterator<String> it = new BasicTokenIterator(headerIterator);
while (it.hasNext()) {
final String token = it.next();
if (HeaderElements.CLOSE.equalsIgnoreCase(token)) {
return false;
}
}
return true;
}
final Iterator<String> it = new BasicTokenIterator(headerIterator);
while (it.hasNext()) {
final String token = it.next();
if (HeaderElements.KEEP_ALIVE.equalsIgnoreCase(token)) {
return true;
}
}
return false;
}
return ver.greaterEquals(HttpVersion.HTTP_1_1);
}
use of org.apache.hc.core5.http.ConnectionReuseStrategy in project commons-vfs by apache.
the class Http5FileProvider method createHttpClientBuilder.
/**
* Create an {@link HttpClientBuilder} object. Invoked by {@link #createHttpClient(Http5FileSystemConfigBuilder, GenericFileName, FileSystemOptions)}.
*
* @param builder Configuration options builder for HTTP4 provider
* @param rootName The root path
* @param fileSystemOptions The FileSystem options
* @return an {@link HttpClientBuilder} object
* @throws FileSystemException if an error occurs
*/
protected HttpClientBuilder createHttpClientBuilder(final Http5FileSystemConfigBuilder builder, final GenericFileName rootName, final FileSystemOptions fileSystemOptions) throws FileSystemException {
final List<Header> defaultHeaders = new ArrayList<>();
defaultHeaders.add(new BasicHeader(HttpHeaders.USER_AGENT, builder.getUserAgent(fileSystemOptions)));
final ConnectionReuseStrategy connectionReuseStrategy = builder.isKeepAlive(fileSystemOptions) ? DefaultConnectionReuseStrategy.INSTANCE : (request, response, context) -> false;
final HttpClientBuilder httpClientBuilder = HttpClients.custom().setRoutePlanner(createHttpRoutePlanner(builder, fileSystemOptions)).setConnectionManager(createConnectionManager(builder, fileSystemOptions)).setConnectionReuseStrategy(connectionReuseStrategy).setDefaultRequestConfig(createDefaultRequestConfig(builder, fileSystemOptions)).setDefaultHeaders(defaultHeaders).setDefaultCookieStore(createDefaultCookieStore(builder, fileSystemOptions));
if (!builder.getFollowRedirect(fileSystemOptions)) {
httpClientBuilder.disableRedirectHandling();
}
return httpClientBuilder;
}
use of org.apache.hc.core5.http.ConnectionReuseStrategy in project httpcomponents-core by apache.
the class ServerHttp1StreamDuplexer method terminateExchange.
void terminateExchange(final HttpException ex) throws HttpException, IOException {
suspendSessionInput();
final ServerHttp1StreamHandler streamHandler;
final HttpCoreContext context = HttpCoreContext.create();
context.setAttribute(HttpCoreContext.SSL_SESSION, getSSLSession());
context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, getEndpointDetails());
if (outgoing == null) {
streamHandler = new ServerHttp1StreamHandler(outputChannel, httpProcessor, connectionReuseStrategy, exchangeHandlerFactory, context);
outgoing = streamHandler;
} else {
streamHandler = new ServerHttp1StreamHandler(new DelayedOutputChannel(outputChannel), httpProcessor, connectionReuseStrategy, exchangeHandlerFactory, context);
pipeline.add(streamHandler);
}
streamHandler.terminateExchange(ex);
incoming = null;
}
Aggregations