Search in sources :

Example 1 with EndpointDetails

use of org.apache.hc.core5.http.EndpointDetails in project httpcomponents-core by apache.

the class BHttpConnectionBase method getEndpointDetails.

@Override
public EndpointDetails getEndpointDetails() {
    if (endpointDetails == null) {
        final SocketHolder socketHolder = this.socketHolderRef.get();
        if (socketHolder != null) {
            @SuppressWarnings("resource") final Socket socket = socketHolder.getSocket();
            Timeout socketTimeout;
            try {
                socketTimeout = Timeout.ofMilliseconds(socket.getSoTimeout());
            } catch (final SocketException e) {
                socketTimeout = Timeout.DISABLED;
            }
            endpointDetails = new BasicEndpointDetails(socket.getRemoteSocketAddress(), socket.getLocalSocketAddress(), this.connMetrics, socketTimeout);
        }
    }
    return endpointDetails;
}
Also used : SocketException(java.net.SocketException) Timeout(org.apache.hc.core5.util.Timeout) BasicEndpointDetails(org.apache.hc.core5.http.impl.BasicEndpointDetails) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 2 with EndpointDetails

use of org.apache.hc.core5.http.EndpointDetails in project httpcomponents-core by apache.

the class H2IntegrationTest method testRequestWithInvalidConnectionHeader.

@Test
public void testRequestWithInvalidConnectionHeader() throws Exception {
    server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<IOSession> sessionFuture = client.requestSession(new HttpHost("localhost", serverEndpoint.getPort()), TIMEOUT, null);
    final IOSession session = sessionFuture.get();
    final ClientSessionEndpoint streamEndpoint = new ClientSessionEndpoint(session);
    final HttpRequest request = new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/hello"));
    request.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
    final HttpCoreContext coreContext = HttpCoreContext.create();
    final Future<Message<HttpResponse, String>> future = streamEndpoint.execute(new BasicRequestProducer(request, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), coreContext, null);
    final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()));
    assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class));
    final EndpointDetails endpointDetails = coreContext.getEndpointDetails();
    assertThat(endpointDetails.getRequestCount(), CoreMatchers.equalTo(0L));
}
Also used : 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) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) EndpointDetails(org.apache.hc.core5.http.EndpointDetails) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) IOSession(org.apache.hc.core5.reactor.IOSession) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 3 with EndpointDetails

use of org.apache.hc.core5.http.EndpointDetails 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)

Example 4 with EndpointDetails

use of org.apache.hc.core5.http.EndpointDetails 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));
}
Also used : Message(org.apache.hc.core5.http.Message) ContentType(org.apache.hc.core5.http.ContentType) HttpConnection(org.apache.hc.core5.http.HttpConnection) BasicRequestConsumer(org.apache.hc.core5.http.nio.support.BasicRequestConsumer) InetSocketAddress(java.net.InetSocketAddress) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpRequest(org.apache.hc.core5.http.HttpRequest) ProtocolException(org.apache.hc.core5.http.ProtocolException) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) EndpointDetails(org.apache.hc.core5.http.EndpointDetails) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) 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) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) File(java.io.File)

Aggregations

InetSocketAddress (java.net.InetSocketAddress)3 EndpointDetails (org.apache.hc.core5.http.EndpointDetails)3 HttpRequest (org.apache.hc.core5.http.HttpRequest)3 Message (org.apache.hc.core5.http.Message)3 ProtocolException (org.apache.hc.core5.http.ProtocolException)3 HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)3 File (java.io.File)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 ContentType (org.apache.hc.core5.http.ContentType)2 EntityDetails (org.apache.hc.core5.http.EntityDetails)2 HttpAsyncServer (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer)2 AsyncServerRequestHandler (org.apache.hc.core5.http.nio.AsyncServerRequestHandler)2 DiscardingEntityConsumer (org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer)2 BasicRequestConsumer (org.apache.hc.core5.http.nio.support.BasicRequestConsumer)2 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)2 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)2 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)2 Socket (java.net.Socket)1 SocketException (java.net.SocketException)1