Search in sources :

Example 1 with HttpServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpServer in project metrics by dropwizard.

the class InstrumentedHttpClientsTest method registersExpectedExceptionMetrics.

@Test
public void registersExpectedExceptionMetrics() throws Exception {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/");
    final String requestMetricName = "request";
    final String exceptionMetricName = "exception";
    httpServer.createContext("/", HttpExchange::close);
    httpServer.start();
    when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(requestMetricName);
    when(metricNameStrategy.getNameFor(any(), any(Exception.class))).thenReturn(exceptionMetricName);
    try {
        client.execute(get);
        fail();
    } catch (NoHttpResponseException expected) {
        assertThat(metricRegistry.getMeters()).containsKey("exception");
    } finally {
        httpServer.stop(0);
    }
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) NoHttpResponseException(org.apache.hc.core5.http.NoHttpResponseException) InetSocketAddress(java.net.InetSocketAddress) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) HttpServer(com.sun.net.httpserver.HttpServer) HttpExchange(com.sun.net.httpserver.HttpExchange) NoHttpResponseException(org.apache.hc.core5.http.NoHttpResponseException) Test(org.junit.Test)

Example 2 with HttpServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpServer in project httpcomponents-core by apache.

the class ClassicTestServer method start.

public void start(final Http1Config http1Config, final HttpProcessor httpProcessor, final Decorator<HttpServerRequestHandler> handlerDecorator) throws IOException {
    if (serverRef.get() == null) {
        final HttpServerRequestHandler handler = new BasicHttpServerRequestHandler(registry);
        final HttpService httpService = new HttpService(httpProcessor != null ? httpProcessor : HttpProcessors.server(), handlerDecorator != null ? handlerDecorator.decorate(handler) : new BasicHttpServerExpectationDecorator(handler), DefaultConnectionReuseStrategy.INSTANCE, LoggingHttp1StreamListener.INSTANCE);
        final HttpServer server = new HttpServer(0, httpService, null, socketConfig, sslContext != null ? sslContext.getServerSocketFactory() : ServerSocketFactory.getDefault(), new LoggingBHttpServerConnectionFactory(sslContext != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id, http1Config != null ? http1Config : Http1Config.DEFAULT, CharCodingConfig.DEFAULT), null, LoggingExceptionListener.INSTANCE);
        if (serverRef.compareAndSet(null, server)) {
            server.start();
        }
    } else {
        throw new IllegalStateException("Server already running");
    }
}
Also used : BasicHttpServerExpectationDecorator(org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator) HttpServerRequestHandler(org.apache.hc.core5.http.io.HttpServerRequestHandler) BasicHttpServerRequestHandler(org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler) HttpService(org.apache.hc.core5.http.impl.io.HttpService) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) BasicHttpServerRequestHandler(org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler)

Example 3 with HttpServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpServer in project httpcomponents-core by apache.

the class ServerBootstrap method create.

public HttpServer create() {
    final RequestHandlerRegistry<HttpRequestHandler> handlerRegistry = new RequestHandlerRegistry<>(canonicalHostName != null ? canonicalHostName : InetAddressUtils.getCanonicalLocalHostName(), () -> lookupRegistry != null ? lookupRegistry : UriPatternType.newMatcher(UriPatternType.URI_PATTERN));
    for (final HandlerEntry<HttpRequestHandler> entry : handlerList) {
        handlerRegistry.register(entry.hostname, entry.uriPattern, entry.handler);
    }
    final HttpServerRequestHandler requestHandler;
    if (!filters.isEmpty()) {
        final NamedElementChain<HttpFilterHandler> filterChainDefinition = new NamedElementChain<>();
        filterChainDefinition.addLast(new TerminalServerFilter(handlerRegistry, this.responseFactory != null ? this.responseFactory : DefaultClassicHttpResponseFactory.INSTANCE), StandardFilter.MAIN_HANDLER.name());
        filterChainDefinition.addFirst(new HttpServerExpectationFilter(), StandardFilter.EXPECT_CONTINUE.name());
        for (final FilterEntry<HttpFilterHandler> entry : filters) {
            switch(entry.position) {
                case AFTER:
                    filterChainDefinition.addAfter(entry.existing, entry.filterHandler, entry.name);
                    break;
                case BEFORE:
                    filterChainDefinition.addBefore(entry.existing, entry.filterHandler, entry.name);
                    break;
                case REPLACE:
                    filterChainDefinition.replace(entry.existing, entry.filterHandler);
                    break;
                case FIRST:
                    filterChainDefinition.addFirst(entry.filterHandler, entry.name);
                    break;
                case LAST:
                    // Don't add last, after TerminalServerFilter, as that does not delegate to the chain
                    // Instead, add the filter just before it, making it effectively the last filter
                    filterChainDefinition.addBefore(StandardFilter.MAIN_HANDLER.name(), entry.filterHandler, entry.name);
                    break;
            }
        }
        NamedElementChain<HttpFilterHandler>.Node current = filterChainDefinition.getLast();
        HttpServerFilterChainElement filterChain = null;
        while (current != null) {
            filterChain = new HttpServerFilterChainElement(current.getValue(), filterChain);
            current = current.getPrevious();
        }
        requestHandler = new HttpServerFilterChainRequestHandler(filterChain);
    } else {
        requestHandler = new BasicHttpServerExpectationDecorator(new BasicHttpServerRequestHandler(handlerRegistry, this.responseFactory != null ? this.responseFactory : DefaultClassicHttpResponseFactory.INSTANCE));
    }
    final HttpService httpService = new HttpService(this.httpProcessor != null ? this.httpProcessor : HttpProcessors.server(), requestHandler, this.connStrategy != null ? this.connStrategy : DefaultConnectionReuseStrategy.INSTANCE, this.streamListener);
    ServerSocketFactory serverSocketFactoryCopy = this.serverSocketFactory;
    if (serverSocketFactoryCopy == null) {
        if (this.sslContext != null) {
            serverSocketFactoryCopy = this.sslContext.getServerSocketFactory();
        } else {
            serverSocketFactoryCopy = ServerSocketFactory.getDefault();
        }
    }
    HttpConnectionFactory<? extends DefaultBHttpServerConnection> connectionFactoryCopy = this.connectionFactory;
    if (connectionFactoryCopy == null) {
        final String scheme = serverSocketFactoryCopy instanceof SSLServerSocketFactory ? URIScheme.HTTPS.id : URIScheme.HTTP.id;
        connectionFactoryCopy = new DefaultBHttpServerConnectionFactory(scheme, this.http1Config, this.charCodingConfig);
    }
    return new HttpServer(Math.max(this.listenerPort, 0), httpService, this.localAddress, this.socketConfig != null ? this.socketConfig : SocketConfig.DEFAULT, serverSocketFactoryCopy, connectionFactoryCopy, sslSetupHandler != null ? sslSetupHandler : new DefaultTlsSetupHandler(), this.exceptionListener != null ? this.exceptionListener : ExceptionListener.NO_OP);
}
Also used : BasicHttpServerExpectationDecorator(org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator) HttpRequestHandler(org.apache.hc.core5.http.io.HttpRequestHandler) SSLServerSocketFactory(javax.net.ssl.SSLServerSocketFactory) ServerSocketFactory(javax.net.ServerSocketFactory) DefaultTlsSetupHandler(org.apache.hc.core5.http.io.ssl.DefaultTlsSetupHandler) NamedElementChain(org.apache.hc.core5.http.config.NamedElementChain) HttpServerExpectationFilter(org.apache.hc.core5.http.io.support.HttpServerExpectationFilter) BasicHttpServerRequestHandler(org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler) RequestHandlerRegistry(org.apache.hc.core5.http.protocol.RequestHandlerRegistry) TerminalServerFilter(org.apache.hc.core5.http.io.support.TerminalServerFilter) HttpServerRequestHandler(org.apache.hc.core5.http.io.HttpServerRequestHandler) BasicHttpServerRequestHandler(org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler) HttpServerFilterChainRequestHandler(org.apache.hc.core5.http.io.support.HttpServerFilterChainRequestHandler) HttpService(org.apache.hc.core5.http.impl.io.HttpService) SSLServerSocketFactory(javax.net.ssl.SSLServerSocketFactory) HttpFilterHandler(org.apache.hc.core5.http.io.HttpFilterHandler) HttpServerFilterChainElement(org.apache.hc.core5.http.io.support.HttpServerFilterChainElement) DefaultBHttpServerConnectionFactory(org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnectionFactory)

Example 4 with HttpServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpServer in project httpcomponents-core by apache.

the class ClassicServerFilterExample method main.

public static void main(final String[] args) throws Exception {
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }
    final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).setSocketConfig(socketConfig).replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractHttpServerAuthFilter<String>(false) {

        @Override
        protected String parseChallengeResponse(final String authorizationValue, final HttpContext context) throws HttpException {
            return authorizationValue;
        }

        @Override
        protected boolean authenticate(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
            return "let me pass".equals(challengeResponse);
        }

        @Override
        protected String generateChallenge(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
            return "who goes there?";
        }
    }).addFilterFirst("my-filter", (request, responseTrigger, context, chain) -> {
        if (request.getRequestUri().equals("/back-door")) {
            final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_OK);
            response.setEntity(new StringEntity("Welcome", ContentType.TEXT_PLAIN));
            responseTrigger.submitResponse(response);
        } else {
            chain.proceed(request, new HttpFilterChain.ResponseTrigger() {

                @Override
                public void sendInformation(final ClassicHttpResponse response) throws HttpException, IOException {
                    responseTrigger.sendInformation(response);
                }

                @Override
                public void submitResponse(final ClassicHttpResponse response) throws HttpException, IOException {
                    response.addHeader("X-Filter", "My-Filter");
                    responseTrigger.submitResponse(response);
                }
            }, context);
        }
    }).register("*", (request, response, context) -> {
        // do something useful
        response.setCode(HttpStatus.SC_OK);
        response.setEntity(new StringEntity("Hello"));
    }).create();
    server.start();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> server.close(CloseMode.GRACEFUL)));
    System.out.println("Listening on port " + port);
    server.awaitTermination(TimeValue.MAX_VALUE);
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) TimeValue(org.apache.hc.core5.util.TimeValue) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOException(java.io.IOException) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) TimeUnit(java.util.concurrent.TimeUnit) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) AbstractHttpServerAuthFilter(org.apache.hc.core5.http.io.support.AbstractHttpServerAuthFilter) URIAuthority(org.apache.hc.core5.net.URIAuthority) ServerBootstrap(org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap) ContentType(org.apache.hc.core5.http.ContentType) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpFilterChain(org.apache.hc.core5.http.io.HttpFilterChain) CloseMode(org.apache.hc.core5.io.CloseMode) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) HttpStatus(org.apache.hc.core5.http.HttpStatus) StandardFilter(org.apache.hc.core5.http.impl.bootstrap.StandardFilter) URIAuthority(org.apache.hc.core5.net.URIAuthority) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOException(java.io.IOException) AbstractHttpServerAuthFilter(org.apache.hc.core5.http.io.support.AbstractHttpServerAuthFilter) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) HttpException(org.apache.hc.core5.http.HttpException) HttpFilterChain(org.apache.hc.core5.http.io.HttpFilterChain) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 5 with HttpServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpServer in project wiremock by wiremock.

the class ProxyAcceptanceTest method successfullyGetsResponseBinaryResponses.

@Test
public void successfullyGetsResponseBinaryResponses() throws IOException {
    initWithDefaultConfig();
    final byte[] bytes = new byte[] { 0x10, 0x49, 0x6e, (byte) 0xb7, 0x46, (byte) 0xe6, 0x52, (byte) 0x95, (byte) 0x95, 0x42 };
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    server.createContext("/binary", new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            InputStream request = exchange.getRequestBody();
            byte[] buffy = new byte[10];
            request.read(buffy);
            if (Arrays.equals(buffy, bytes)) {
                exchange.sendResponseHeaders(200, bytes.length);
                OutputStream out = exchange.getResponseBody();
                out.write(bytes);
                out.close();
            } else {
                exchange.sendResponseHeaders(500, 0);
                exchange.close();
            }
        }
    });
    server.start();
    proxy.register(post(urlEqualTo("/binary")).willReturn(aResponse().proxiedFrom("http://localhost:" + server.getAddress().getPort()).withBody(bytes)));
    WireMockResponse post = testClient.post("/binary", new ByteArrayEntity(bytes, ContentType.DEFAULT_BINARY));
    assertThat(post.statusCode(), is(200));
    assertThat(post.binaryContent(), Matchers.equalTo(bytes));
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) WireMockResponse(com.github.tomakehurst.wiremock.testsupport.WireMockResponse) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) HttpServer(com.sun.net.httpserver.HttpServer) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) Test(org.junit.jupiter.api.Test)

Aggregations

HttpServer (org.apache.hc.core5.http.impl.bootstrap.HttpServer)8 IOException (java.io.IOException)6 HttpException (org.apache.hc.core5.http.HttpException)5 SocketConfig (org.apache.hc.core5.http.io.SocketConfig)5 SocketTimeoutException (java.net.SocketTimeoutException)3 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)3 ExceptionListener (org.apache.hc.core5.http.ExceptionListener)3 HttpConnection (org.apache.hc.core5.http.HttpConnection)3 HttpRequest (org.apache.hc.core5.http.HttpRequest)3 HttpExchange (com.sun.net.httpserver.HttpExchange)2 HttpServer (com.sun.net.httpserver.HttpServer)2 InetSocketAddress (java.net.InetSocketAddress)2 URISyntaxException (java.net.URISyntaxException)2 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)2 HttpService (org.apache.hc.core5.http.impl.io.HttpService)2 HttpServerRequestHandler (org.apache.hc.core5.http.io.HttpServerRequestHandler)2 BasicHttpServerExpectationDecorator (org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator)2 BasicHttpServerRequestHandler (org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler)2 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)2 WireMockResponse (com.github.tomakehurst.wiremock.testsupport.WireMockResponse)1