Search in sources :

Example 1 with BasicHttpServerExpectationDecorator

use of org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator 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 2 with BasicHttpServerExpectationDecorator

use of org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator 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 3 with BasicHttpServerExpectationDecorator

use of org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator in project httpcomponents-core by apache.

the class ClassicIntegrationTest method testHttpPostsWithExpectationVerification.

/**
 * This test case executes a series of simple POST requests that do not
 * meet the target server expectations.
 */
@Test
public void testHttpPostsWithExpectationVerification() throws Exception {
    final int reqNo = 20;
    // Initialize the server-side request handler
    this.server.registerHandler("*", (request, response, context) -> response.setEntity(new StringEntity("No content")));
    this.server.start(null, null, handler -> new BasicHttpServerExpectationDecorator(handler) {

        @Override
        protected ClassicHttpResponse verify(final ClassicHttpRequest request, final HttpContext context) {
            final Header someheader = request.getFirstHeader("Secret");
            if (someheader != null) {
                final int secretNumber;
                try {
                    secretNumber = Integer.parseInt(someheader.getValue());
                } catch (final NumberFormatException ex) {
                    final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_BAD_REQUEST);
                    response.setEntity(new StringEntity(ex.toString()));
                    return response;
                }
                if (secretNumber >= 2) {
                    final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_EXPECTATION_FAILED);
                    response.setEntity(new StringEntity("Wrong secret number", ContentType.TEXT_PLAIN));
                    return response;
                }
            }
            return null;
        }
    });
    this.client.start();
    final HttpCoreContext context = HttpCoreContext.create();
    final HttpHost host = new HttpHost(scheme.id, "localhost", this.server.getPort());
    for (int r = 0; r < reqNo; r++) {
        final BasicClassicHttpRequest post = new BasicClassicHttpRequest(Method.POST, "/");
        post.addHeader("Secret", Integer.toString(r));
        final byte[] b = new byte[2048];
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) ('a' + r);
        }
        post.setEntity(new ByteArrayEntity(b, ContentType.TEXT_PLAIN));
        try (final ClassicHttpResponse response = this.client.execute(host, post, context)) {
            final HttpEntity responseEntity = response.getEntity();
            Assertions.assertNotNull(responseEntity);
            EntityUtils.consume(responseEntity);
            if (r >= 2) {
                Assertions.assertEquals(HttpStatus.SC_EXPECTATION_FAILED, response.getCode());
            } else {
                Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
            }
        }
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicHttpServerExpectationDecorator(org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator) HttpEntity(org.apache.hc.core5.http.HttpEntity) AbstractHttpEntity(org.apache.hc.core5.http.io.entity.AbstractHttpEntity) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Header(org.apache.hc.core5.http.Header) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.Test)

Aggregations

BasicHttpServerExpectationDecorator (org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator)3 HttpService (org.apache.hc.core5.http.impl.io.HttpService)2 HttpServerRequestHandler (org.apache.hc.core5.http.io.HttpServerRequestHandler)2 BasicHttpServerRequestHandler (org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler)2 ServerSocketFactory (javax.net.ServerSocketFactory)1 SSLServerSocketFactory (javax.net.ssl.SSLServerSocketFactory)1 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)1 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)1 Header (org.apache.hc.core5.http.Header)1 HttpEntity (org.apache.hc.core5.http.HttpEntity)1 HttpHost (org.apache.hc.core5.http.HttpHost)1 NamedElementChain (org.apache.hc.core5.http.config.NamedElementChain)1 HttpServer (org.apache.hc.core5.http.impl.bootstrap.HttpServer)1 DefaultBHttpServerConnectionFactory (org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnectionFactory)1 HttpFilterHandler (org.apache.hc.core5.http.io.HttpFilterHandler)1 HttpRequestHandler (org.apache.hc.core5.http.io.HttpRequestHandler)1 AbstractHttpEntity (org.apache.hc.core5.http.io.entity.AbstractHttpEntity)1 ByteArrayEntity (org.apache.hc.core5.http.io.entity.ByteArrayEntity)1 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)1 DefaultTlsSetupHandler (org.apache.hc.core5.http.io.ssl.DefaultTlsSetupHandler)1