use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class DefaultBHttpClientConnection method receiveResponseHeader.
@Override
public ClassicHttpResponse receiveResponseHeader() throws HttpException, IOException {
final SocketHolder socketHolder = ensureOpen();
final ClassicHttpResponse response = this.responseParser.parse(this.inBuffer, socketHolder.getInputStream());
if (response == null) {
throw new NoHttpResponseException("The target server failed to respond");
}
final ProtocolVersion transportVersion = response.getVersion();
if (transportVersion != null && transportVersion.greaterEquals(HttpVersion.HTTP_2)) {
throw new UnsupportedHttpVersionException(transportVersion);
}
this.version = transportVersion;
onResponseReceived(response);
final int status = response.getCode();
if (status < HttpStatus.SC_INFORMATIONAL) {
throw new ProtocolException("Invalid response: " + status);
}
if (response.getCode() >= HttpStatus.SC_SUCCESS) {
incrementResponseCount();
}
return response;
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class DefaultH2RequestConverter method convert.
@Override
public HttpRequest convert(final List<Header> headers) throws HttpException {
String method = null;
String scheme = null;
String authority = null;
String path = null;
final List<Header> messageHeaders = new ArrayList<>();
for (int i = 0; i < headers.size(); i++) {
final Header header = headers.get(i);
final String name = header.getName();
final String value = header.getValue();
for (int n = 0; n < name.length(); n++) {
final char ch = name.charAt(n);
if (Character.isAlphabetic(ch) && !Character.isLowerCase(ch)) {
throw new ProtocolException("Header name '%s' is invalid (header name contains uppercase characters)", name);
}
}
if (name.startsWith(":")) {
if (!messageHeaders.isEmpty()) {
throw new ProtocolException("Invalid sequence of headers (pseudo-headers must precede message headers)");
}
switch(name) {
case H2PseudoRequestHeaders.METHOD:
if (method != null) {
throw new ProtocolException("Multiple '%s' request headers are illegal", name);
}
method = value;
break;
case H2PseudoRequestHeaders.SCHEME:
if (scheme != null) {
throw new ProtocolException("Multiple '%s' request headers are illegal", name);
}
scheme = value;
break;
case H2PseudoRequestHeaders.PATH:
if (path != null) {
throw new ProtocolException("Multiple '%s' request headers are illegal", name);
}
path = value;
break;
case H2PseudoRequestHeaders.AUTHORITY:
authority = value;
break;
default:
throw new ProtocolException("Unsupported request header '%s'", name);
}
} else {
if (name.equalsIgnoreCase(HttpHeaders.CONNECTION) || name.equalsIgnoreCase(HttpHeaders.KEEP_ALIVE) || name.equalsIgnoreCase(HttpHeaders.PROXY_CONNECTION) || name.equalsIgnoreCase(HttpHeaders.TRANSFER_ENCODING) || name.equalsIgnoreCase(HttpHeaders.HOST) || name.equalsIgnoreCase(HttpHeaders.UPGRADE)) {
throw new ProtocolException("Header '%s: %s' is illegal for HTTP/2 messages", header.getName(), header.getValue());
}
if (name.equalsIgnoreCase(HttpHeaders.TE) && !value.equalsIgnoreCase("trailers")) {
throw new ProtocolException("Header '%s: %s' is illegal for HTTP/2 messages", header.getName(), header.getValue());
}
messageHeaders.add(header);
}
}
if (method == null) {
throw new ProtocolException("Mandatory request header '%s' not found", H2PseudoRequestHeaders.METHOD);
}
if (Method.CONNECT.isSame(method)) {
if (authority == null) {
throw new ProtocolException("Header '%s' is mandatory for CONNECT request", H2PseudoRequestHeaders.AUTHORITY);
}
if (scheme != null) {
throw new ProtocolException("Header '%s' must not be set for CONNECT request", H2PseudoRequestHeaders.SCHEME);
}
if (path != null) {
throw new ProtocolException("Header '%s' must not be set for CONNECT request", H2PseudoRequestHeaders.PATH);
}
} else {
if (scheme == null) {
throw new ProtocolException("Mandatory request header '%s' not found", H2PseudoRequestHeaders.SCHEME);
}
if (path == null) {
throw new ProtocolException("Mandatory request header '%s' not found", H2PseudoRequestHeaders.PATH);
}
}
final HttpRequest httpRequest = new BasicHttpRequest(method, path);
httpRequest.setVersion(HttpVersion.HTTP_2);
httpRequest.setScheme(scheme);
try {
httpRequest.setAuthority(URIAuthority.create(authority));
} catch (final URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
httpRequest.setPath(path);
for (int i = 0; i < messageHeaders.size(); i++) {
httpRequest.addHeader(messageHeaders.get(i));
}
return httpRequest;
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class DefaultH2ResponseConverter method convert.
@Override
public HttpResponse convert(final List<Header> headers) throws HttpException {
String statusText = null;
final List<Header> messageHeaders = new ArrayList<>();
for (int i = 0; i < headers.size(); i++) {
final Header header = headers.get(i);
final String name = header.getName();
final String value = header.getValue();
for (int n = 0; n < name.length(); n++) {
final char ch = name.charAt(n);
if (Character.isAlphabetic(ch) && !Character.isLowerCase(ch)) {
throw new ProtocolException("Header name '%s' is invalid (header name contains uppercase characters)", name);
}
}
if (name.startsWith(":")) {
if (!messageHeaders.isEmpty()) {
throw new ProtocolException("Invalid sequence of headers (pseudo-headers must precede message headers)");
}
if (name.equals(H2PseudoResponseHeaders.STATUS)) {
if (statusText != null) {
throw new ProtocolException("Multiple '%s' response headers are illegal", name);
}
statusText = value;
} else {
throw new ProtocolException("Unsupported response header '%s'", name);
}
} else {
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());
}
messageHeaders.add(header);
}
}
if (statusText == null) {
throw new ProtocolException("Mandatory response header '%s' not found", H2PseudoResponseHeaders.STATUS);
}
final int statusCode;
try {
statusCode = Integer.parseInt(statusText);
} catch (final NumberFormatException ex) {
throw new ProtocolException("Invalid response status: " + statusText);
}
final HttpResponse response = new BasicHttpResponse(statusCode, null);
response.setVersion(HttpVersion.HTTP_2);
for (int i = 0; i < messageHeaders.size(); i++) {
response.addHeader(messageHeaders.get(i));
}
return response;
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class Http1IntegrationTest method testProtocolException.
@Test
public void testProtocolException() throws Exception {
server.register("/boom", () -> new AsyncServerExchangeHandler() {
private final StringAsyncEntityProducer entityProducer = new StringAsyncEntityProducer("Everyting is OK");
@Override
public void releaseResources() {
entityProducer.releaseResources();
}
@Override
public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
final String requestUri = request.getRequestUri();
if (requestUri.endsWith("boom")) {
throw new ProtocolException("Boom!!!");
}
responseChannel.sendResponse(new BasicHttpResponse(200), entityProducer, context);
}
@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
capacityChannel.update(Integer.MAX_VALUE);
}
@Override
public void consume(final ByteBuffer src) throws IOException {
}
@Override
public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
// empty
}
@Override
public int available() {
return entityProducer.available();
}
@Override
public void produce(final DataStreamChannel channel) throws IOException {
entityProducer.produce(channel);
}
@Override
public void failed(final Exception cause) {
releaseResources();
}
});
final InetSocketAddress serverEndpoint = server.start();
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
final Future<Message<HttpResponse, String>> future = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/boom")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> result = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
Assertions.assertNotNull(result);
final HttpResponse response1 = result.getHead();
final String entity1 = result.getBody();
Assertions.assertNotNull(response1);
Assertions.assertEquals(HttpStatus.SC_BAD_REQUEST, response1.getCode());
Assertions.assertEquals("Boom!!!", entity1);
}
use of org.apache.hc.core5.http.ProtocolException in project httpcomponents-core by apache.
the class AsyncFileServerExample method main.
/**
* Example command line args: {@code "c:\temp" 8080}
*/
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 = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).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()) {
final String msg = "File " + file.getPath() + " not found";
println(msg);
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_NOT_FOUND).setEntity("<html><body><h1>" + msg + "</h1></body></html>", ContentType.TEXT_HTML).build(), context);
} else if (!file.canRead() || file.isDirectory()) {
final String msg = "Cannot read file " + file.getPath();
println(msg);
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_FORBIDDEN).setEntity("<html><body><h1>" + msg + "</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();
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(() -> {
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();
println("Listening on " + listenerEndpoint.getAddress());
server.awaitShutdown(TimeValue.MAX_VALUE);
}
Aggregations