Search in sources :

Example 16 with ProtocolException

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;
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) NoHttpResponseException(org.apache.hc.core5.http.NoHttpResponseException) ProtocolException(org.apache.hc.core5.http.ProtocolException) UnsupportedHttpVersionException(org.apache.hc.core5.http.UnsupportedHttpVersionException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 17 with ProtocolException

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;
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) ProtocolException(org.apache.hc.core5.http.ProtocolException) Header(org.apache.hc.core5.http.Header) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest)

Example 18 with ProtocolException

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;
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) ArrayList(java.util.ArrayList) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse)

Example 19 with ProtocolException

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);
}
Also used : Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) CancellationException(java.util.concurrent.CancellationException) MalformedChunkCodingException(org.apache.hc.core5.http.MalformedChunkCodingException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Test(org.junit.Test)

Example 20 with ProtocolException

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);
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) ProtocolException(org.apache.hc.core5.http.ProtocolException) Message(org.apache.hc.core5.http.Message) ContentType(org.apache.hc.core5.http.ContentType) BasicRequestConsumer(org.apache.hc.core5.http.nio.support.BasicRequestConsumer) InetSocketAddress(java.net.InetSocketAddress) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) URISyntaxException(java.net.URISyntaxException) EndpointDetails(org.apache.hc.core5.http.EndpointDetails) URI(java.net.URI) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) File(java.io.File)

Aggregations

ProtocolException (org.apache.hc.core5.http.ProtocolException)28 HttpResponse (org.apache.hc.core5.http.HttpResponse)10 Header (org.apache.hc.core5.http.Header)9 EntityDetails (org.apache.hc.core5.http.EntityDetails)8 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)8 URISyntaxException (java.net.URISyntaxException)6 HttpException (org.apache.hc.core5.http.HttpException)6 HttpRequest (org.apache.hc.core5.http.HttpRequest)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 IOException (java.io.IOException)5 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)5 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)5 ByteBuffer (java.nio.ByteBuffer)4 ArrayList (java.util.ArrayList)4 URIAuthority (org.apache.hc.core5.net.URIAuthority)4 InetSocketAddress (java.net.InetSocketAddress)3 URI (java.net.URI)3 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)3 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)3 Message (org.apache.hc.core5.http.Message)3