Search in sources :

Example 11 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint in project httpcomponents-core by apache.

the class Http1AuthenticationTest method testGetRequestAuthentication.

@Test
public void testGetRequestAuthentication() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTP);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost("localhost", address.getPort());
    final HttpRequest request1 = new BasicHttpRequest(Method.GET, target, "/stuff");
    final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message1, CoreMatchers.notNullValue());
    final HttpResponse response1 = message1.getHead();
    assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_UNAUTHORIZED));
    final String body1 = message1.getBody();
    assertThat(body1, CoreMatchers.equalTo("You shall not pass!!!"));
    final HttpRequest request2 = new BasicHttpRequest(Method.GET, target, "/stuff");
    request2.setHeader(HttpHeaders.AUTHORIZATION, "let me pass");
    final Future<Message<HttpResponse, String>> resultFuture2 = requester.execute(new BasicRequestProducer(request2, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message2, CoreMatchers.notNullValue());
    final HttpResponse response2 = message2.getHead();
    assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body2 = message2.getBody();
    assertThat(body2, CoreMatchers.equalTo(""));
}
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) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) Test(org.junit.Test)

Example 12 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint in project commons-vfs by apache.

the class NHttpFileServer method start.

private NHttpFileServer start() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, InterruptedException, ExecutionException {
    final AsyncServerBootstrap bootstrap = AsyncServerBootstrap.bootstrap();
    SSLContext sslContext = null;
    if (port == 8443 || port == 443) {
        // Initialize SSL context
        final URL url = NHttpFileServer.class.getResource("/test.keystore");
        if (url == null) {
            println("Keystore not found");
            System.exit(1);
        }
        println("Loading keystore " + url);
        sslContext = SSLContexts.custom().loadKeyMaterial(url, "nopassword".toCharArray(), "nopassword".toCharArray()).build();
        bootstrap.setTlsStrategy(new BasicServerTlsStrategy(sslContext, new FixedPortStrategy(port)));
    }
    // @formatter:off
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    // @formatter:on
    server = bootstrap.setIOReactorConfig(config).register("*", new HttpFileHandler(docRoot)).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> close()));
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port));
    listenerEndpoint = future.get();
    println("Serving " + docRoot + " on " + listenerEndpoint.getAddress() + (sslContext == null ? "" : " with " + sslContext.getProvider() + " " + sslContext.getProtocol()));
    return this;
}
Also used : IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) FixedPortStrategy(org.apache.hc.core5.http.nio.ssl.FixedPortStrategy) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) InetSocketAddress(java.net.InetSocketAddress) BasicServerTlsStrategy(org.apache.hc.core5.http.nio.ssl.BasicServerTlsStrategy) SSLContext(javax.net.ssl.SSLContext) AsyncServerBootstrap(org.apache.hc.core5.http.impl.bootstrap.AsyncServerBootstrap) URL(java.net.URL)

Example 13 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint in project californium by eclipse.

the class HttpServer method start.

/**
 * Start http server.
 */
public void start() {
    if (proxyServerFilter != null && server == null) {
        bootstrap.addFilterBefore(StandardFilter.MAIN_HANDLER.name(), "proxy", new AsyncFilterHandler() {

            @Override
            public AsyncDataConsumer handle(HttpRequest request, EntityDetails entityDetails, HttpContext context, org.apache.hc.core5.http.nio.AsyncFilterChain.ResponseTrigger responseTrigger, AsyncFilterChain chain) throws HttpException, IOException {
                try {
                    URI uri = request.getUri();
                    if (uri.getScheme() != null && !virtualHosts.contains(uri.getHost())) {
                        LOGGER.warn("proxy filter {}", uri);
                        return proxyServerFilter.handle(request, entityDetails, context, responseTrigger, chain);
                    }
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                return chain.proceed(request, entityDetails, context, responseTrigger);
            }
        });
    }
    server = bootstrap.create();
    LOGGER.info("HttpServer listening on {} started.", StringUtil.toLog(httpInterface));
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            LOGGER.info("HTTP server shutting down");
            HttpServer.this.stop();
        }
    });
    server.start();
    final Future<ListenerEndpoint> future = server.listen(httpInterface, URIScheme.HTTP);
    try {
        final ListenerEndpoint listenerEndpoint = future.get();
        LOGGER.info("Listening on {}", listenerEndpoint.getAddress());
    } catch (InterruptedException ex) {
        LOGGER.info("interrupted", ex);
    } catch (ExecutionException ex) {
        LOGGER.error("unexpected error:", ex);
    }
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) AsyncFilterHandler(org.apache.hc.core5.http.nio.AsyncFilterHandler) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) AsyncFilterChain(org.apache.hc.core5.http.nio.AsyncFilterChain) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) EntityDetails(org.apache.hc.core5.http.EntityDetails) AsyncDataConsumer(org.apache.hc.core5.http.nio.AsyncDataConsumer) HttpException(org.apache.hc.core5.http.HttpException) ExecutionException(java.util.concurrent.ExecutionException)

Example 14 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint in project httpcomponents-core by apache.

the class HttpAsyncServer method listen.

/**
 * @since 5.1
 */
public Future<ListenerEndpoint> listen(final SocketAddress address, final URIScheme scheme, final Object attachment, final FutureCallback<ListenerEndpoint> callback) {
    final InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
    final EndpointParameters parameters = new EndpointParameters(scheme.id, canonicalName != null ? canonicalName : "localhost", inetSocketAddress.getPort(), attachment);
    return super.listen(address, parameters, callback);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) EndpointParameters(org.apache.hc.core5.reactor.EndpointParameters)

Example 15 with ListenerEndpoint

use of org.apache.hc.core5.reactor.ListenerEndpoint in project httpcomponents-core by apache.

the class TestDefaultListeningIOReactor method testEndpointUpAndDown.

@Test
public void testEndpointUpAndDown() throws Exception {
    ioReactor.start();
    Set<ListenerEndpoint> endpoints = ioReactor.getEndpoints();
    Assertions.assertNotNull(endpoints);
    Assertions.assertEquals(0, endpoints.size());
    final Future<ListenerEndpoint> future1 = ioReactor.listen(new InetSocketAddress(0));
    final ListenerEndpoint endpoint1 = future1.get();
    final Future<ListenerEndpoint> future2 = ioReactor.listen(new InetSocketAddress(0));
    final ListenerEndpoint endpoint2 = future2.get();
    final int port = ((InetSocketAddress) endpoint2.getAddress()).getPort();
    endpoints = ioReactor.getEndpoints();
    Assertions.assertNotNull(endpoints);
    Assertions.assertEquals(2, endpoints.size());
    endpoint1.close();
    endpoints = ioReactor.getEndpoints();
    Assertions.assertNotNull(endpoints);
    Assertions.assertEquals(1, endpoints.size());
    final ListenerEndpoint endpoint = endpoints.iterator().next();
    Assertions.assertEquals(port, ((InetSocketAddress) endpoint.getAddress()).getPort());
    ioReactor.close(CloseMode.GRACEFUL);
    ioReactor.awaitShutdown(TimeValue.ofSeconds(5));
    Assertions.assertEquals(IOReactorStatus.SHUT_DOWN, ioReactor.getStatus());
}
Also used : ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) InetSocketAddress(java.net.InetSocketAddress) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) Test(org.junit.jupiter.api.Test)

Aggregations

InetSocketAddress (java.net.InetSocketAddress)42 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)42 Message (org.apache.hc.core5.http.Message)30 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)27 HttpHost (org.apache.hc.core5.http.HttpHost)26 HttpResponse (org.apache.hc.core5.http.HttpResponse)26 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)26 StringAsyncEntityProducer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer)22 Test (org.junit.Test)16 HttpRequest (org.apache.hc.core5.http.HttpRequest)12 Test (org.junit.jupiter.api.Test)12 AsyncClientEndpoint (org.apache.hc.core5.http.nio.AsyncClientEndpoint)8 IOException (java.io.IOException)7 EntityDetails (org.apache.hc.core5.http.EntityDetails)7 HttpAsyncServer (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer)7 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)7 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)7 ExecutionException (java.util.concurrent.ExecutionException)6 BasicClientTlsStrategy (org.apache.hc.core5.http.nio.ssl.BasicClientTlsStrategy)5 BasicServerTlsStrategy (org.apache.hc.core5.http.nio.ssl.BasicServerTlsStrategy)5