use of org.apache.hc.core5.http.ProtocolException in project cxf by apache.
the class AsyncHTTPConduitFactory method setupNIOClient.
public synchronized void setupNIOClient(HTTPClientPolicy clientPolicy) {
if (client != null) {
return;
}
final IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(ioThreadCount).setSelectInterval(TimeValue.ofMilliseconds(selectInterval)).setSoLinger(TimeValue.ofMilliseconds(soLinger)).setSoTimeout(Timeout.ofMilliseconds(soTimeout)).setSoKeepAlive(soKeepalive).setTcpNoDelay(tcpNoDelay).build();
final Registry<TlsStrategy> tlsStrategy = RegistryBuilder.<TlsStrategy>create().register("https", DefaultClientTlsStrategy.getSystemDefault()).build();
connectionManager = new PoolingAsyncClientConnectionManager(tlsStrategy, PoolConcurrencyPolicy.STRICT, PoolReusePolicy.LIFO, TimeValue.ofMilliseconds(connectionTTL), DefaultSchemePortResolver.INSTANCE, SystemDefaultDnsResolver.INSTANCE);
connectionManager.setDefaultMaxPerRoute(maxPerRoute);
connectionManager.setMaxTotal(maxConnections);
final RedirectStrategy redirectStrategy = new RedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return null;
}
};
final HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom().setConnectionManager(connectionManager).setRedirectStrategy(redirectStrategy).setDefaultCookieStore(new BasicCookieStore() {
private static final long serialVersionUID = 1L;
public void addCookie(Cookie cookie) {
}
});
adaptClientBuilder(httpAsyncClientBuilder);
client = httpAsyncClientBuilder.setIOReactorConfig(config).build();
// Start the client thread
client.start();
// Always start the idle checker thread to validate pending requests and
// use the ConnectionMaxIdle to close the idle connection
new CloseIdleConnectionThread(connectionManager, client).start();
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class ReactiveRandomProcessor method processRequest.
@Override
public void processRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context, final Publisher<ByteBuffer> requestBody, final Callback<Publisher<ByteBuffer>> responseBodyCallback) throws HttpException, IOException {
final String method = request.getMethod();
if (!"GET".equalsIgnoreCase(method) && !"HEAD".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method) && !"PUT".equalsIgnoreCase(method)) {
throw new MethodNotSupportedException(method + " not supported by " + getClass().getName());
}
final URI uri;
try {
uri = request.getUri();
} catch (final URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
final String path = uri.getPath();
final int slash = path.lastIndexOf('/');
if (slash != -1) {
final String payload = path.substring(slash + 1);
final long n;
if (!payload.isEmpty()) {
try {
n = Long.parseLong(payload);
} catch (final NumberFormatException ex) {
throw new ProtocolException("Invalid request path: " + path);
}
} else {
// random length, but make sure at least something is sent
n = 1 + (int) (Math.random() * 79.0);
}
if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
responseChannel.sendInformation(new BasicHttpResponse(100), context);
}
final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
final Flowable<ByteBuffer> stream = ReactiveTestUtils.produceStream(n);
final String hash = ReactiveTestUtils.getStreamHash(n);
response.addHeader("response-hash-code", hash);
final BasicEntityDetails basicEntityDetails = new BasicEntityDetails(n, ContentType.APPLICATION_OCTET_STREAM);
responseChannel.sendResponse(response, basicEntityDetails, context);
responseBodyCallback.execute(stream);
} else {
throw new ProtocolException("Invalid request path: " + path);
}
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class ClientH2StreamHandler method consumeHeader.
@Override
public void consumeHeader(final List<Header> headers, final boolean endStream) throws HttpException, IOException {
if (done.get()) {
throw new ProtocolException("Unexpected message headers");
}
switch(responseState) {
case HEADERS:
final HttpResponse response = DefaultH2ResponseConverter.INSTANCE.convert(headers);
final int status = response.getCode();
if (status < HttpStatus.SC_INFORMATIONAL) {
throw new ProtocolException("Invalid response: " + new StatusLine(response));
}
if (status > HttpStatus.SC_CONTINUE && status < HttpStatus.SC_SUCCESS) {
exchangeHandler.consumeInformation(response, context);
}
if (requestState == MessageState.ACK) {
if (status == HttpStatus.SC_CONTINUE || status >= HttpStatus.SC_SUCCESS) {
requestState = MessageState.BODY;
exchangeHandler.produce(dataChannel);
}
}
if (status < HttpStatus.SC_SUCCESS) {
return;
}
final EntityDetails entityDetails = endStream ? null : new IncomingEntityDetails(response, -1);
context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
httpProcessor.process(response, entityDetails, context);
connMetrics.incrementResponseCount();
exchangeHandler.consumeResponse(response, entityDetails, context);
responseState = endStream ? MessageState.COMPLETE : MessageState.BODY;
break;
case BODY:
responseState = MessageState.COMPLETE;
exchangeHandler.streamEnd(headers);
break;
default:
throw new ProtocolException("Unexpected message headers");
}
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class H2MultiplexingRequester method execute.
private void execute(final AsyncClientExchangeHandler exchangeHandler, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final CancellableDependency cancellableDependency, final Timeout timeout, final HttpContext context) {
Args.notNull(exchangeHandler, "Exchange handler");
Args.notNull(timeout, "Timeout");
Args.notNull(context, "Context");
try {
exchangeHandler.produceRequest((request, entityDetails, httpContext) -> {
final String scheme = request.getScheme();
final URIAuthority authority = request.getAuthority();
if (authority == null) {
throw new ProtocolException("Request authority not specified");
}
final HttpHost target = new HttpHost(scheme, authority);
connPool.getSession(target, timeout, new FutureCallback<IOSession>() {
@Override
public void completed(final IOSession ioSession) {
ioSession.enqueue(new RequestExecutionCommand(new AsyncClientExchangeHandler() {
@Override
public void releaseResources() {
exchangeHandler.releaseResources();
}
@Override
public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
channel.sendRequest(request, entityDetails, httpContext);
}
@Override
public int available() {
return exchangeHandler.available();
}
@Override
public void produce(final DataStreamChannel channel) throws IOException {
exchangeHandler.produce(channel);
}
@Override
public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
exchangeHandler.consumeInformation(response, httpContext);
}
@Override
public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
exchangeHandler.consumeResponse(response, entityDetails, httpContext);
}
@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
exchangeHandler.updateCapacity(capacityChannel);
}
@Override
public void consume(final ByteBuffer src) throws IOException {
exchangeHandler.consume(src);
}
@Override
public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
exchangeHandler.streamEnd(trailers);
}
@Override
public void cancel() {
exchangeHandler.cancel();
}
@Override
public void failed(final Exception cause) {
exchangeHandler.failed(cause);
}
}, pushHandlerFactory, cancellableDependency, context), Command.Priority.NORMAL);
if (!ioSession.isOpen()) {
exchangeHandler.failed(new ConnectionClosedException());
}
}
@Override
public void failed(final Exception ex) {
exchangeHandler.failed(ex);
}
@Override
public void cancelled() {
exchangeHandler.cancel();
}
});
}, context);
} catch (final IOException | HttpException ex) {
exchangeHandler.failed(ex);
}
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class DefaultH2ResponseConverter method convert.
@Override
public List<Header> convert(final HttpResponse message) throws HttpException {
final int code = message.getCode();
if (code < 100 || code >= 600) {
throw new ProtocolException("Response status %s is invalid", code);
}
final List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader(H2PseudoResponseHeaders.STATUS, Integer.toString(code), false));
for (final Iterator<Header> it = message.headerIterator(); it.hasNext(); ) {
final Header header = it.next();
final String name = header.getName();
final String value = header.getValue();
if (name.startsWith(":")) {
throw new ProtocolException("Header name '%s' is invalid", name);
}
if (name.equalsIgnoreCase(HttpHeaders.CONNECTION) || name.equalsIgnoreCase(HttpHeaders.KEEP_ALIVE) || name.equalsIgnoreCase(HttpHeaders.TRANSFER_ENCODING) || name.equalsIgnoreCase(HttpHeaders.UPGRADE)) {
throw new ProtocolException("Header '%s: %s' is illegal for HTTP/2 messages", header.getName(), header.getValue());
}
headers.add(new BasicHeader(TextUtils.toLowerCase(name), value));
}
return headers;
}
Aggregations