use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class RequestValidateHost method process.
@Override
public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
Args.notNull(request, "HTTP request");
final Header header = request.getHeader(HttpHeaders.HOST);
if (header != null) {
final URIAuthority authority;
try {
authority = URIAuthority.create(header.getValue());
} catch (final URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
request.setAuthority(authority);
} else {
final ProtocolVersion version = request.getVersion() != null ? request.getVersion() : HttpVersion.HTTP_1_1;
if (version.greaterEquals(HttpVersion.HTTP_1_1)) {
throw new ProtocolException("Host header is absent");
}
}
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class H2FileServerExample method main.
public static void main(final String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
// Document root directory
final File docRoot = new File(args[0]);
int port = 8080;
if (args.length >= 2) {
port = Integer.parseInt(args[1]);
}
final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
final HttpAsyncServer server = H2ServerBootstrap.bootstrap().setIOReactorConfig(config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
}).register("*", new AsyncServerRequestHandler<Message<HttpRequest, Void>>() {
@Override
public AsyncRequestConsumer<Message<HttpRequest, Void>> prepare(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
return new BasicRequestConsumer<>(entityDetails != null ? new DiscardingEntityConsumer<>() : null);
}
@Override
public void handle(final Message<HttpRequest, Void> message, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
final HttpRequest request = message.getHead();
final URI requestUri;
try {
requestUri = request.getUri();
} catch (final URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
final String path = requestUri.getPath();
final File file = new File(docRoot, path);
if (!file.exists()) {
System.out.println("File " + file.getPath() + " not found");
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_NOT_FOUND).setEntity("<html><body><h1>File" + file.getPath() + " not found</h1></body></html>", ContentType.TEXT_HTML).build(), context);
} else if (!file.canRead() || file.isDirectory()) {
System.out.println("Cannot read file " + file.getPath());
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_FORBIDDEN).setEntity("<html><body><h1>Access denied</h1></body></html>", ContentType.TEXT_HTML).build(), context);
} else {
final ContentType contentType;
final String filename = TextUtils.toLowerCase(file.getName());
if (filename.endsWith(".txt")) {
contentType = ContentType.TEXT_PLAIN;
} else if (filename.endsWith(".html") || filename.endsWith(".htm")) {
contentType = ContentType.TEXT_HTML;
} else if (filename.endsWith(".xml")) {
contentType = ContentType.TEXT_XML;
} else {
contentType = ContentType.DEFAULT_BINARY;
}
final HttpCoreContext coreContext = HttpCoreContext.adapt(context);
final EndpointDetails endpoint = coreContext.getEndpointDetails();
System.out.println(endpoint + ": serving file " + file.getPath());
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity(AsyncEntityProducers.create(file, contentType)).build(), context);
}
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP server shutting down");
server.close(CloseMode.GRACEFUL);
}));
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
final ListenerEndpoint listenerEndpoint = future.get();
System.out.print("Listening on " + listenerEndpoint.getAddress());
server.awaitShutdown(TimeValue.ofDays(Long.MAX_VALUE));
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class AbstractH2StreamMultiplexer method onException.
public final void onException(final Exception cause) {
try {
for (; ; ) {
final AsyncPingHandler pingHandler = pingHandlers.poll();
if (pingHandler != null) {
pingHandler.failed(cause);
} else {
break;
}
}
for (; ; ) {
final Command command = ioSession.poll();
if (command != null) {
if (command instanceof ExecutableCommand) {
((ExecutableCommand) command).failed(new ConnectionClosedException());
} else {
command.cancel();
}
} else {
break;
}
}
for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
final Map.Entry<Integer, H2Stream> entry = it.next();
final H2Stream stream = entry.getValue();
stream.reset(cause);
}
streamMap.clear();
if (!(cause instanceof ConnectionClosedException)) {
if (connState.compareTo(ConnectionHandshake.GRACEFUL_SHUTDOWN) <= 0) {
final H2Error errorCode;
if (cause instanceof H2ConnectionException) {
errorCode = H2Error.getByCode(((H2ConnectionException) cause).getCode());
} else if (cause instanceof ProtocolException) {
errorCode = H2Error.PROTOCOL_ERROR;
} else {
errorCode = H2Error.INTERNAL_ERROR;
}
final RawFrame goAway = frameFactory.createGoAway(processedRemoteStreamId, errorCode, cause.getMessage());
commitFrame(goAway);
}
}
} catch (final IOException ignore) {
} finally {
connState = ConnectionHandshake.SHUTDOWN;
final CloseMode closeMode;
if (cause instanceof ConnectionClosedException) {
closeMode = CloseMode.GRACEFUL;
} else if (cause instanceof IOException) {
closeMode = CloseMode.IMMEDIATE;
} else {
closeMode = CloseMode.GRACEFUL;
}
ioSession.close(closeMode);
}
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class ClientPushH2StreamHandler method consumePromise.
@Override
public void consumePromise(final List<Header> headers) throws HttpException, IOException {
if (requestState == MessageState.HEADERS) {
request = DefaultH2RequestConverter.INSTANCE.convert(headers);
try {
exchangeHandler = pushHandlerFactory != null ? pushHandlerFactory.create(request, context) : null;
} catch (final ProtocolException ex) {
exchangeHandler = new NoopAsyncPushHandler();
throw new H2StreamResetException(H2Error.PROTOCOL_ERROR, ex.getMessage());
}
if (exchangeHandler == null) {
exchangeHandler = new NoopAsyncPushHandler();
throw new H2StreamResetException(H2Error.REFUSED_STREAM, "Stream refused");
}
context.setProtocolVersion(HttpVersion.HTTP_2);
context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
httpProcessor.process(request, null, context);
connMetrics.incrementRequestCount();
this.requestState = MessageState.COMPLETE;
} else {
throw new H2ConnectionException(H2Error.PROTOCOL_ERROR, "Unexpected promise");
}
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class ClientPushH2StreamHandler method consumeHeader.
@Override
public void consumeHeader(final List<Header> headers, final boolean endStream) throws HttpException, IOException {
if (responseState == MessageState.HEADERS) {
Asserts.notNull(request, "Request");
Asserts.notNull(exchangeHandler, "Exchange handler");
final HttpResponse response = DefaultH2ResponseConverter.INSTANCE.convert(headers);
final EntityDetails entityDetails = endStream ? null : new IncomingEntityDetails(request, -1);
context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
httpProcessor.process(response, entityDetails, context);
connMetrics.incrementResponseCount();
exchangeHandler.consumePromise(request, response, entityDetails, context);
if (endStream) {
responseState = MessageState.COMPLETE;
exchangeHandler.streamEnd(null);
} else {
responseState = MessageState.BODY;
}
} else {
throw new ProtocolException("Unexpected message headers");
}
}
Aggregations