Java Code Examples for org.eclipse.jetty.http.HttpStatus

Following code examples demonstrate how to use org.eclipse.jetty.http.HttpStatus from jetty. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.eclipse.jetty.http.HttpStatus and various code implementation of this class.

    
    protected void doGetFail(int status)
        throws Exception
    {
        startClient(getRealm());

        ContentExchange getExchange = new ContentExchange();
        getExchange.setURL(getBaseUrl() + "input.txt");
        getExchange.setMethod(HttpMethods.GET);
        getExchange.setRequestHeader("X-Response-Status",Integer.toString(status));
       
        getClient().send(getExchange);
        int state = getExchange.waitForDone();
        
        String content;
        int responseStatus = getExchange.getResponseStatus();
        if (responseStatus == HttpStatus.OK_200) {
            content = getExchange.getResponseContent();
        }
        
        stopClient();

        assertEquals(status, responseStatus);
    } 


    @Test
    public void testPostUnauthorized()
        throws Exception
    {
        doPostFail(HttpStatus.UNAUTHORIZED_401);
    } 

    @Test
    public void testGetBadRequest()
        throws Exception
    {
        doGetFail(HttpStatus.BAD_REQUEST_400);
    } 

    @Test
    public void testGetUnauthorized()
        throws Exception
    {
        doGetFail(HttpStatus.UNAUTHORIZED_401);
    } 

    @Test
    public void testPutUnauthorized()
        throws Exception
    {
        doPutFail(HttpStatus.UNAUTHORIZED_401);
    } 

    @Test
    public void testPostNotFound()
        throws Exception
    {
        doPostFail(HttpStatus.NOT_FOUND_404);
    } 

    @Test
    public void testPutBadRequest()
        throws Exception
    {
        doPutFail(HttpStatus.BAD_REQUEST_400);
    } 

    @Test
    public void testPutServerError()
        throws Exception
    {
        doPutFail(HttpStatus.INTERNAL_SERVER_ERROR_500);    
    } 

    @Test
    public void testGetServerError()
        throws Exception
    {
        doGetFail(HttpStatus.INTERNAL_SERVER_ERROR_500);    
    } 

    @Test
    public void testPostBadRequest() 
        throws Exception
    {
        doPostFail(HttpStatus.BAD_REQUEST_400);
    } 

    @Test
    public void testPostForbidden()
        throws Exception
    {
        doPostFail(HttpStatus.FORBIDDEN_403);
    } 

    @Test
    public void testGetNotFound()
        throws Exception
    {
        doGetFail(HttpStatus.NOT_FOUND_404);    
    } 

    @Test
    public void testPutForbidden()
        throws Exception
    {
        doPutFail(HttpStatus.FORBIDDEN_403);
    } 

    @Test
    public void testPostServerError()
        throws Exception
    {
        doPostFail(HttpStatus.INTERNAL_SERVER_ERROR_500);
    } 

    @Test
    public void testPutNotFound()
        throws Exception
    {
        doPutFail(HttpStatus.NOT_FOUND_404);    
    } 

    @Test
    public void testGetWrongPassword()
        throws Exception
    {
        setRealm(_dummyRealm);
        
        doGetFail(HttpStatus.UNAUTHORIZED_401); 
        
        setRealm(_testRealm);
    } 

    @Test
    public void testPutWrongPassword()
        throws Exception
    {
        setRealm(_dummyRealm);
        
        doPutFail(HttpStatus.UNAUTHORIZED_401);
        
        setRealm(_testRealm);
    } 

    @Override
    public void testGetUnauthorized()
        throws Exception
    {
        setRealm(null);
        
        doGetFail(HttpStatus.UNAUTHORIZED_401);
        
        setRealm(_testRealm);
    } 

    @Override
    public void testPutUnauthorized()
        throws Exception
    {
        setRealm(null);
        
        doPutFail(HttpStatus.UNAUTHORIZED_401);
        
        setRealm(_testRealm);
    } 

    @Test
    public void testGetUnauthorized()
        throws Exception
    {
        setRealm(null);
        
        doGetFail(HttpStatus.UNAUTHORIZED_401);
        
        setRealm(_testRealm);
    } 

    @Test
    public void testPutUnauthorized()
        throws Exception
    {
        setRealm(null);
        
        doPutFail(HttpStatus.UNAUTHORIZED_401);
        
        setRealm(_testRealm);
    } 

    @Test
    public void testGetWrongPassword()
        throws Exception
    {
        setRealm(_dummyRealm);
        
        doGetFail(HttpStatus.UNAUTHORIZED_401); 
        
        setRealm(_testRealm);
    } 

    @Test
    public void testPutWrongPassword()
        throws Exception
    {
        setRealm(_dummyRealm);
        
        doPutFail(HttpStatus.UNAUTHORIZED_401);
        
        setRealm(_testRealm);
    } 

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                HttpVersion version = HttpVersion.fromString(request.getProtocol());
                response.setStatus(version == HttpVersion.HTTP_2 ? HttpStatus.OK_200 : HttpStatus.INTERNAL_SERVER_ERROR_500);
            } 

    @Test
    public void testResponseAbortSendsResetFrame() throws Exception
    {
        CountDownLatch resetLatch = new CountDownLatch(1);
        start(new ServerSessionListener.Adapter()
        {
            @Override
            public Stream.Listener onNewStream(Stream stream, HeadersFrame frame)
            {
                MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
                stream.headers(new HeadersFrame(stream.getId(), metaData, null, false), new Callback()
                {
                    @Override
                    public void succeeded()
                    {
                        ByteBuffer data = ByteBuffer.allocate(1024);
                        stream.data(new DataFrame(stream.getId(), data, false), NOOP);
                    }
                });

                return new Stream.Listener.Adapter()
                {
                    @Override
                    public void onReset(Stream stream, ResetFrame frame)
                    {
                        resetLatch.countDown();
                    }
                };
            }
        });

        try
        {
            client.newRequest("localhost", connector.getLocalPort())
                    .onResponseContent((response, buffer) -> response.abort(new Exception("explicitly_aborted_by_test")))
                    .send();
            Assert.fail();
        }
        catch (ExecutionException x)
        {
            Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS));
        }
    } 

    @Test
    public void testExternalServer() throws Exception
    {
        HTTP2Client http2Client = new HTTP2Client();
        SslContextFactory sslContextFactory = new SslContextFactory();
        HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client), sslContextFactory);
        Executor executor = new QueuedThreadPool();
        httpClient.setExecutor(executor);

        httpClient.start();


        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());

        httpClient.stop();
    } 

                    @Override
                    public void onReset(Stream stream, ResetFrame frame)
                    {
                        latch.countDown();
                    } 

    @Test
    public void testPushedResourceRedirect() throws Exception
    {
        Random random = new Random();
        byte[] pushBytes = new byte[512];
        random.nextBytes(pushBytes);

        String oldPath = "/old";
        String newPath = "/new";
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                if (target.equals(oldPath))
                    response.sendRedirect(newPath);
                else if (target.equals(newPath))
                    response.getOutputStream().write(pushBytes);
                else
                    baseRequest.getPushBuilder().path(oldPath).push();
            }
        });

        CountDownLatch latch = new CountDownLatch(1);
        HttpRequest request = (HttpRequest)client.newRequest("localhost", connector.getLocalPort());
        ContentResponse response = request
                .pushListener((mainRequest, pushedRequest) -> new BufferingResponseListener()
                {
                    @Override
                    public void onComplete(Result result)
                    {
                        Assert.assertTrue(result.isSucceeded());
                        Assert.assertEquals(oldPath, pushedRequest.getPath());
                        Assert.assertEquals(newPath, result.getRequest().getPath());
                        Assert.assertArrayEquals(pushBytes, getContent());
                        latch.countDown();
                    }
                })
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    } 

                    @Override
                    public void succeeded(Stream pushStream)
                    {
                        MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
                        stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP);
                    } 

                    @Override
                    public void onComplete(Result result)
                    {
                        Assert.assertTrue(result.isSucceeded());
                        if (pushedRequest.getPath().equals(path1))
                        {
                            Assert.assertArrayEquals(pushBytes1, getContent());
                            latch1.countDown();
                        }
                        else if (pushedRequest.getPath().equals(path2))
                        {
                            Assert.assertArrayEquals(pushBytes2, getContent());
                            latch2.countDown();
                        }
                    } 

    @Test
    public void testProxyAuthenticationWithExplicitAuthorizationHeader() throws Exception
    {
        String proxyRealm = "proxyRealm";
        String serverRealm = "serverRealm";
        int status = HttpStatus.NO_CONTENT_204;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                String authorization = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());
                if (authorization == null)
                {
                    response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407);
                    response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "Basic realm=\"" + proxyRealm + "\"");
                }
                else
                {
                    authorization = request.getHeader(HttpHeader.AUTHORIZATION.asString());
                    if (authorization == null)
                    {
                        response.setStatus(HttpStatus.UNAUTHORIZED_401);
                        response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Basic realm=\"" + serverRealm + "\"");
                    }
                    else
                    {
                        response.setStatus(status);
                    }
                }
            }
        });

        String proxyHost = "localhost";
        int proxyPort = connector.getLocalPort();
        String serverHost = "server";
        int serverPort = proxyPort + 1;
        client.getAuthenticationStore().addAuthentication(new BasicAuthentication(proxyURI, proxyRealm, "proxyUser", "proxyPassword"));
        client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));
        final AtomicInteger requests = new AtomicInteger();
        client.getRequestListeners().add(new Request.Listener.Adapter()
        {
            @Override
            public void onSuccess(Request request)
            {
                requests.incrementAndGet();
            }
        });
        ContentResponse response1 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .header(HttpHeader.AUTHORIZATION, "Basic foobar")
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response1.getStatus());
        Assert.assertEquals(2, requests.get());

        requests.set(0);
        ContentResponse response2 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .header(HttpHeader.AUTHORIZATION, "Basic foobar")
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response2.getStatus());
        Assert.assertEquals(1, requests.get());
    } 

    @Test
    public void testProxyAuthenticationWithRedirect() throws Exception
    {
        String user = "foo";
        String password = "bar";
        String credentials = B64Code.encode(user + ":" + password, StandardCharsets.ISO_8859_1);
        String proxyHost = "localhost";
        String serverHost = "server";
        int serverPort = HttpScheme.HTTP.is(scheme) ? 80 : 443;
        String realm = "test_realm";
        int status = HttpStatus.NO_CONTENT_204;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                if (target.startsWith("/proxy"))
                {
                    String authorization = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());
                    if (authorization == null)
                    {
                        response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407);
                        response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "Basic realm=\"" + realm + "\"");
                    }
                    else
                    {
                        String prefix = "Basic ";
                        if (authorization.startsWith(prefix))
                        {
                            String attempt = authorization.substring(prefix.length());
                            if (credentials.equals(attempt))
                            {
                            }
                        }
                    }
                }
                else if (target.startsWith("/server"))
                {
                    response.setStatus(status);
                }
                else
                {
                    response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500);
                }
            }
        });

        int proxyPort = connector.getLocalPort();
        client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));

        ContentResponse response1 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .path("/proxy")
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus());

        client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, user, password));
        final AtomicInteger requests = new AtomicInteger();
        client.getRequestListeners().add(new Request.Listener.Adapter()
        {
            @Override
            public void onSuccess(Request request)
            {
                requests.incrementAndGet();
            }
        });
        ContentResponse response2 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .path("/proxy")
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response2.getStatus());
        Assert.assertEquals(3, requests.get());

        requests.set(0);
        ContentResponse response3 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .path("/server")
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response3.getStatus());
        Assert.assertEquals(1, requests.get());
    } 

    @Test
    public void testProxyAuthenticationWithServerAuthentication() throws Exception
    {
        String proxyRealm = "proxyRealm";
        String serverRealm = "serverRealm";
        int status = HttpStatus.NO_CONTENT_204;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                String authorization = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());
                if (authorization == null)
                {
                    response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407);
                    response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "Basic realm=\"" + proxyRealm + "\"");
                }
                else
                {
                    authorization = request.getHeader(HttpHeader.AUTHORIZATION.asString());
                    if (authorization == null)
                    {
                        response.setStatus(HttpStatus.UNAUTHORIZED_401);
                        response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Basic realm=\"" + serverRealm + "\"");
                    }
                    else
                    {
                        response.setStatus(status);
                    }
                }
            }
        });

        String proxyHost = "localhost";
        int proxyPort = connector.getLocalPort();
        String serverHost = "server";
        int serverPort = proxyPort + 1;
        client.getAuthenticationStore().addAuthentication(new BasicAuthentication(proxyURI, proxyRealm, "proxyUser", "proxyPassword"));
        client.getAuthenticationStore().addAuthentication(new BasicAuthentication(serverURI, serverRealm, "serverUser", "serverPassword"));
        client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));
        final AtomicInteger requests = new AtomicInteger();
        client.getRequestListeners().add(new Request.Listener.Adapter()
        {
            @Override
            public void onSuccess(Request request)
            {
                requests.incrementAndGet();
            }
        });
        ContentResponse response1 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response1.getStatus());
        Assert.assertEquals(3, requests.get());

        requests.set(0);
        ContentResponse response2 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response2.getStatus());
        Assert.assertEquals(1, requests.get());
    } 

    @Test
    public void testProxiedRequest() throws Exception
    {
        final String serverHost = "server";
        final int status = HttpStatus.NO_CONTENT_204;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                if (!URI.create(baseRequest.getHttpURI().toString()).isAbsolute())
                    response.setStatus(HttpServletResponse.SC_USE_PROXY);
                else if (serverHost.equals(request.getServerName()))
                    response.setStatus(status);
                else
                    response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            }
        });

        int proxyPort = connector.getLocalPort();
        client.getProxyConfiguration().getProxies().add(new HttpProxy("localhost", proxyPort));

        ContentResponse response = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response.getStatus());
    } 

    @Test
    public void testProxyAuthentication() throws Exception
    {
        final String user = "foo";
        final String password = "bar";
        final String credentials = B64Code.encode(user + ":" + password, StandardCharsets.ISO_8859_1);
        final String serverHost = "server";
        final String realm = "test_realm";
        final int status = HttpStatus.NO_CONTENT_204;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                String authorization = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());
                if (authorization == null)
                {
                    response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407);
                    response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "Basic realm=\"" + realm + "\"");
                }
                else
                {
                    String prefix = "Basic ";
                    if (authorization.startsWith(prefix))
                    {
                        String attempt = authorization.substring(prefix.length());
                        if (credentials.equals(attempt))
                            response.setStatus(status);
                    }
                }
            }
        });

        String proxyHost = "localhost";
        int proxyPort = connector.getLocalPort();
        client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort));

        ContentResponse response1 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus());

        client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, user, password));
        final AtomicInteger requests = new AtomicInteger();
        client.getRequestListeners().add(new Request.Listener.Adapter()
        {
            @Override
            public void onSuccess(Request request)
            {
                requests.incrementAndGet();
            }
        });
        ContentResponse response2 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response2.getStatus());
        Assert.assertEquals(2, requests.get());

        requests.set(0);
        ContentResponse response3 = client.newRequest(serverHost, serverPort)
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(status, response3.getStatus());
        Assert.assertEquals(1, requests.get());
    } 

            @Override
            protected void doNonErrorHandle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                jettyRequest.setHandled(true);

                ServletInputStream input = jettyRequest.getInputStream();
                while (true)
                {
                    int read = input.read();
                    if (read < 0)
                        break;
                }

                HttpFields trailers = jettyRequest.getTrailers();
                Assert.assertNotNull(trailers);
                Assert.assertEquals(trailerValue, trailers.get(trailerName));
            } 

                    }
                    catch (Throwable x)
                    {
                        failure.set(x);
                    } 

    @Test
    public void testEmptyRequestTrailers() throws Exception
    {
        start(new AbstractHandler.ErrorDispatchHandler()
        {
            @Override
            protected void doNonErrorHandle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                jettyRequest.setHandled(true);

                ServletInputStream input = jettyRequest.getInputStream();
                while (true)
                {
                    int read = input.read();
                    if (read < 0)
                        break;
                }

                HttpFields trailers = jettyRequest.getTrailers();
                Assert.assertNull(trailers);
            }
        });

        HttpFields trailers = new HttpFields();
        HttpRequest request = (HttpRequest)client.newRequest(newURI());
        request = request.trailers(() -> trailers);
        ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send();
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testEmptyResponseTrailers() throws Exception
    {
        start(new AbstractHandler.ErrorDispatchHandler()
        {
            @Override
            protected void doNonErrorHandle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                jettyRequest.setHandled(true);

                HttpFields trailers = new HttpFields();

                Response jettyResponse = (Response)response;
                jettyResponse.setTrailers(() -> trailers);
            }
        });

        AtomicReference<Throwable> failure = new AtomicReference<>(new Throwable("no_success"));
        ContentResponse response = client.newRequest(newURI())
                .onResponseSuccess(r ->
                {
                    try
                    {
                        HttpResponse httpResponse = (HttpResponse)r;
                        HttpFields trailers = httpResponse.getTrailers();
                        Assert.assertNull(trailers);
                        failure.set(null);
                    }
                    catch (Throwable x)
                    {
                        failure.set(x);
                    }
                })
                .timeout(5, TimeUnit.SECONDS)
                .send();
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
        Assert.assertNull(failure.get());
    } 

    @Override
    protected void onResponseStatus(Buffer version, int status, Buffer reason) throws IOException
    {
        if ( status == HttpStatus.CREATED_201 )
        {
            LOG.debug( "MkcolExchange:Status: Successfully created resource" );
            exists = true;
        }

        {
            LOG.debug( "MkcolExchange:Status: Resource must exist" );
            exists = true;
        }

        super.onResponseStatus(version, status, reason);
    } 

    @Test
    public void testPathWithQuery() throws Exception
    {
        String name = "a";
        String value = "1";
        final String query = name + "=" + value;
        final String path = "/path";
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(path, request.getRequestURI());
                Assert.assertEquals(query, request.getQueryString());
            }
        });

        String pathQuery = path + "?" + query;
        Request request = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .path(pathQuery);

        Assert.assertEquals(path, request.getPath());
        Assert.assertEquals(query, request.getQuery());
        Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
        Fields params = request.getParams();
        Assert.assertEquals(1, params.getSize());
        Assert.assertEquals(value, params.get(name).getValue());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testPathWithQueryAndParamValueEncoded() throws Exception
    {
        final String name1 = "a";
        final String value1 = "\u20AC";
        final String encodedValue1 = URLEncoder.encode(value1, "UTF-8");
        final String name2 = "b";
        final String value2 = "\u00A5";
        String encodedValue2 = URLEncoder.encode(value2, "UTF-8");
        final String query = name1 + "=" + encodedValue1 + "&" + name2 + "=" + encodedValue2;
        final String path = "/path";
        String pathQuery = path + "?" + query;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(path, request.getRequestURI());
                Assert.assertEquals(query, request.getQueryString());
                Assert.assertEquals(value1, request.getParameter(name1));
                Assert.assertEquals(value2, request.getParameter(name2));
            }
        });

        Request request = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .path(path + "?" + name1 + "=" + encodedValue1)
                .param(name2, value2);

        Assert.assertEquals(path, request.getPath());
        Assert.assertEquals(query, request.getQuery());
        Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
        Fields params = request.getParams();
        Assert.assertEquals(2, params.getSize());
        Assert.assertEquals(value1, params.get(name1).getValue());
        Assert.assertEquals(value2, params.get(name2).getValue());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testHostIsCaseInsensitive() throws Exception
    {
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
            }
        });

        ContentResponse response = client.newRequest("LOCALHOST", connector.getLocalPort())
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testPathWithQueryAndParam() throws Exception
    {
        String name1 = "a";
        String value1 = "1";
        String name2 = "b";
        String value2 = "2";
        final String query = name1 + "=" + value1 + "&" + name2 + "=" + value2;
        final String path = "/path";
        String pathQuery = path + "?" + query;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(path, request.getRequestURI());
                Assert.assertEquals(query, request.getQueryString());
            }
        });

        Request request = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .path(path + "?" + name1 + "=" + value1)
                .param(name2, value2);

        Assert.assertEquals(path, request.getPath());
        Assert.assertEquals(query, request.getQuery());
        Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
        Fields params = request.getParams();
        Assert.assertEquals(2, params.getSize());
        Assert.assertEquals(value1, params.get(name1).getValue());
        Assert.assertEquals(value2, params.get(name2).getValue());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testNoParameterNameWithParameterValue() throws Exception
    {
        final String path = "/path";
        String pathQuery = path + "?" + query;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(path, request.getRequestURI());
                Assert.assertEquals(query, request.getQueryString());
            }
        });

        Request request = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .path(pathQuery);

        Assert.assertEquals(path, request.getPath());
        Assert.assertEquals(query, request.getQuery());
        Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
        Fields params = request.getParams();
        Assert.assertEquals(0, params.getSize());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testNoParameterNameNoParameterValue() throws Exception
    {
        final String path = "/path";
        String pathQuery = path + "?" + query;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(path, request.getRequestURI());
                Assert.assertEquals(query, request.getQueryString());
            }
        });

        Request request = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .path(pathQuery);

        Assert.assertEquals(path, request.getPath());
        Assert.assertEquals(query, request.getQuery());
        Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
        Fields params = request.getParams();
        Assert.assertEquals(0, params.getSize());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testAsteriskFormTarget() throws Exception
    {
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals("*", target);
                Assert.assertEquals("*", request.getPathInfo());
            }
        });

        Request request = client.newRequest("localhost", connector.getLocalPort())
                .method(HttpMethod.OPTIONS)
                .scheme(scheme)
                .path("*")
                .timeout(5, TimeUnit.SECONDS);

        Assert.assertEquals("*", request.getPath());
        Assert.assertNull(request.getQuery());
        Fields params = request.getParams();
        Assert.assertEquals(0, params.getSize());
        Assert.assertNull(request.getURI());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testSchemeIsCaseInsensitive() throws Exception
    {
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
            }
        });

        ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme.toUpperCase(Locale.ENGLISH))
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testCaseSensitiveParameterName() throws Exception
    {
        final String name1 = "a";
        final String name2 = "A";
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(name1, request.getParameter(name1));
                Assert.assertEquals(name2, request.getParameter(name2));
            }
        });

        ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .path("/path?" + name1 + "=" + name1)
                .param(name2, name2)
                .timeout(5, TimeUnit.SECONDS)
                .send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testRawQueryIsPreservedInURI() throws Exception
    {
        final String name = "a";
        final String rawValue = "Hello%20World";
        final String rawQuery = name + "=" + rawValue;
        final String value = "Hello World";
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(rawQuery, request.getQueryString());
                Assert.assertEquals(value, request.getParameter(name));
            }
        });

        Request request = client.newRequest(uri)
                .timeout(5, TimeUnit.SECONDS);
        Assert.assertEquals(rawQuery, request.getQuery());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(path, request.getRequestURI());
            } 

    @Test
    public void testRawQueryIsPreservedWithParam() throws Exception
    {
        final String name1 = "a";
        final String name2 = "b";
        final String rawValue1 = "Hello%20World";
        final String rawQuery1 = name1 + "=" + rawValue1;
        final String value1 = "Hello World";
        final String value2 = "alfa omega";
        final String encodedQuery2 = name2 + "=" + URLEncoder.encode(value2, "UTF-8");
        final String query = rawQuery1 + "&" + encodedQuery2;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(query, request.getQueryString());
                Assert.assertEquals(value1, request.getParameter(name1));
                Assert.assertEquals(value2, request.getParameter(name2));
            }
        });

        Request request = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .path("/path?" + rawQuery1)
                .param(name2, value2)
                .timeout(5, TimeUnit.SECONDS);
        Assert.assertEquals(query, request.getQuery());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testIPv6Host() throws Exception
    {
        start(new EmptyServerHandler());

        String host = "::1";
        Request request = client.newRequest(host, connector.getLocalPort())
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS);

        Assert.assertEquals(host, request.getHost());
        StringBuilder uri = new StringBuilder();
        URIUtil.appendSchemeHostPort(uri, scheme, host, connector.getLocalPort());
        Assert.assertEquals(uri.toString(), request.getURI().toString());

        Assert.assertEquals(HttpStatus.OK_200, request.send().getStatus());
    } 

    @Test
    public void testPathWithParam() throws Exception
    {
        String name = "a";
        String value = "1";
        final String query = name + "=" + value;
        final String path = "/path";
        String pathQuery = path + "?" + query;
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(path, request.getRequestURI());
                Assert.assertEquals(query, request.getQueryString());
            }
        });

        Request request = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .timeout(5, TimeUnit.SECONDS)
                .path(path)
                .param(name, value);

        Assert.assertEquals(path, request.getPath());
        Assert.assertEquals(query, request.getQuery());
        Assert.assertTrue(request.getURI().toString().endsWith(pathQuery));
        Fields params = request.getParams();
        Assert.assertEquals(1, params.getSize());
        Assert.assertEquals(value, params.get(name).getValue());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testRawQueryIsPreservedInPath() throws Exception
    {
        final String name = "a";
        final String rawValue = "Hello%20World";
        final String rawQuery = name + "=" + rawValue;
        final String value = "Hello World";
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                Assert.assertEquals(rawQuery, request.getQueryString());
                Assert.assertEquals(value, request.getParameter(name));
            }
        });

        Request request = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .path("/path?" + rawQuery)
                .timeout(5, TimeUnit.SECONDS);
        Assert.assertEquals(rawQuery, request.getQuery());

        ContentResponse response = request.send();

        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException,
                    ServletException
            {
                response.setStatus(HttpStatus.CREATED_201);
                request.setAttribute("target",target);
                request.setAttribute("URI",request.getRequestURI());
                request.setAttribute("info",request.getPathInfo());
            } 

    }

    private void assertIsRequest(String expectedRequestPath)
    {
        assertThat("Response Status",_response.getStatus(),is(HttpStatus.CREATED_201));
        assertThat("Request Target",_request.getAttribute("target"),is(expectedRequestPath));
    } 

                        }
                        catch (Exception x)
                        {
                            running.set(false);
                            reloads.set(-1);
                        } 

    @Test
    public void testReload() throws Exception
    {
        start(new EchoHandler());

        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, null);
        SSLSocketFactory socketFactory = ctx.getSocketFactory();
        try (SSLSocket client1 = (SSLSocket)socketFactory.createSocket("localhost", connector.getLocalPort()))
        {
            String serverDN1 = client1.getSession().getPeerPrincipal().getName();
            Assert.assertThat(serverDN1, Matchers.startsWith("CN=localhost1"));

            String request = "" +
                    "GET / HTTP/1.1\r\n" +
                    "Host: localhost\r\n" +
                    "\r\n";

            OutputStream output1 = client1.getOutputStream();
            output1.write(request.getBytes(StandardCharsets.UTF_8));
            output1.flush();

            HttpTester.Response response1 = HttpTester.parseResponse(HttpTester.from(client1.getInputStream()));
            Assert.assertNotNull(response1);
            Assert.assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200));

            sslContextFactory.reload(sslContextFactory ->
            {
                sslContextFactory.setKeyStorePath(KEYSTORE_2);
                sslContextFactory.setKeyStorePassword("storepwd");
            });

            try (SSLSocket client2 = (SSLSocket)socketFactory.createSocket("localhost", connector.getLocalPort()))
            {
                String serverDN2 = client2.getSession().getPeerPrincipal().getName();
                Assert.assertThat(serverDN2, Matchers.startsWith("CN=localhost2"));

                OutputStream output2 = client1.getOutputStream();
                output2.write(request.getBytes(StandardCharsets.UTF_8));
                output2.flush();

                HttpTester.Response response2 = HttpTester.parseResponse(HttpTester.from(client1.getInputStream()));
                Assert.assertNotNull(response2);
                Assert.assertThat(response2.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
            }

            output1.write(request.getBytes(StandardCharsets.UTF_8));
            output1.flush();

            response1 = HttpTester.parseResponse(HttpTester.from(client1.getInputStream()));
            Assert.assertNotNull(response1);
            Assert.assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
        }
    } 

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException,
                    ServletException
            {
                response.setStatus(HttpStatus.CREATED_201);
                request.setAttribute("target",target);
                request.setAttribute("URI",request.getRequestURI());
                request.setAttribute("info",request.getPathInfo());
            } 

    }

    private void assertIsRequest(String expectedRequestPath)
    {
        assertThat("Response Status",_response.getStatus(),is(HttpStatus.CREATED_201));
        assertThat("Request Target",_request.getAttribute("target"),is(expectedRequestPath));
    } 

            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                if (target.endsWith("/redirect"))
                {
                    response.setStatus(HttpStatus.TEMPORARY_REDIRECT_307);
                    response.setContentLength(0);
                    response.flushBuffer();
                    baseRequest.getHttpChannel().getEndPoint().shutdownOutput();
                }
                else
                {
                    response.setStatus(HttpStatus.OK_200);
                    response.setContentLength(0);
                    response.setHeader(HttpHeader.CONNECTION.asString(), HttpHeaderValue.CLOSE.asString());
                }
            } 

    @Test
    public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithConnectionCloseHeader() throws Exception
    {
        testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                response.setStatus(HttpStatus.OK_200);
                response.setContentLength(0);
                response.setHeader(HttpHeader.CONNECTION.asString(), HttpHeaderValue.CLOSE.asString());
            }
        });
    } 

    @Test
    public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithoutConnectionCloseHeader() throws Exception
    {
        testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(new AbstractHandler()
        {
            @Override
            public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                response.setStatus(HttpStatus.OK_200);
                response.setContentLength(0);
                response.flushBuffer();
                baseRequest.getHttpChannel().getEndPoint().shutdownOutput();
            }
        });
    } 

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        HttpChannel channel = baseRequest.getHttpChannel();
        if (baseRequest.isSecure() || (channel == null))
        {
            return;
        }

        HttpConfiguration httpConfig = channel.getHttpConfiguration();
        if (httpConfig == null)
        {
            response.sendError(HttpStatus.FORBIDDEN_403,"No http configuration available");
            return;
        }

        if (httpConfig.getSecurePort() > 0)
        {
            String scheme = httpConfig.getSecureScheme();
            int port = httpConfig.getSecurePort();

            String url = URIUtil.newURI(scheme,baseRequest.getServerName(),port,baseRequest.getRequestURI(),baseRequest.getQueryString());
            response.setContentLength(0);
            response.sendRedirect(url);
        }
        else
        {
            response.sendError(HttpStatus.FORBIDDEN_403,"Not Secure");
        }
        
        baseRequest.setHandled(true);
    } 

    @Test
    public void testGET_HttpTesting() throws Exception
    {
        HttpTester.Request request = HttpTester.newRequest();
        request.setMethod("GET");
        request.setURI("/tests/alpha.txt");
        request.put("Host","localhost");
        request.put("Connection","close");

        HttpTesting testing = new HttpTesting(new HttpSocketImpl(),serverPort);
        HttpTester.Response response = testing.request(request);

        assertEquals(HttpStatus.OK_200, response.getStatus());
        assertEquals("text/plain", response.get("Content-Type"));
        assertTrue(response.getContent().contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"));
    } 

    @Test
    public void testGET_Raw() throws Exception
    {
        StringBuffer rawRequest = new StringBuffer();
        rawRequest.append("GET /tests/alpha.txt HTTP/1.1\r\n");
        rawRequest.append("Host: localhost\r\n");
        rawRequest.append("Connection: close\r\n");
        rawRequest.append("\r\n");

        Socket sock = new Socket(InetAddress.getLocalHost(),serverPort);

        DEBUG("--raw-request--\n" + rawRequest);
        InputStream in = new ByteArrayInputStream(rawRequest.toString().getBytes());

        IO.copy(in,sock.getOutputStream());

        String rawResponse = IO.toString(sock.getInputStream());
        DEBUG("--raw-response--\n" + rawResponse);
        
        HttpTester.Response response = HttpTester.parseResponse(rawResponse);

        assertEquals(HttpStatus.OK_200, response.getStatus());

        assertTrue(response.getContent().contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"));
    } 

    @Override
    public Result exchangeTerminating(HttpExchange exchange, Result result)
    {
        if (result.isFailed())
            return result;

        HttpResponse response = exchange.getResponse();
        
        if ((response.getVersion() == HttpVersion.HTTP_1_1) && 
            (response.getStatus() == HttpStatus.SWITCHING_PROTOCOLS_101))
        {
            String connection = response.getHeaders().get(HttpHeader.CONNECTION);
            if ((connection == null) || !connection.toLowerCase(Locale.US).contains("upgrade"))
            {
                return new Result(result,new HttpResponseException("101 Switching Protocols without Connection: Upgrade not supported",response));
            }
            
            HttpRequest request = exchange.getRequest();
            if (request instanceof HttpConnectionUpgrader)
            {
                HttpConnectionUpgrader listener = (HttpConnectionUpgrader)request;
                try
                {
                    listener.upgrade(response,getHttpConnection());
                }
                catch (Throwable x)
                {
                    return new Result(result,x);
                }
            }
        }

        return result;
    } 

    @Override
    public void exchangeTerminated(HttpExchange exchange, Result result)
    {
        super.exchangeTerminated(exchange, result);

        Response response = result.getResponse();
        HttpFields responseHeaders = response.getHeaders();

        String closeReason = null;
        if (result.isFailed())
            closeReason = "failure";
        else if (receiver.isShutdown())
            closeReason = "server close";
        else if (sender.isShutdown())
            closeReason = "client close";

        if (closeReason == null)
        {
            if (response.getVersion().compareTo(HttpVersion.HTTP_1_1) < 0)
            {
                boolean keepAlive = responseHeaders.contains(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString());
                boolean connect = HttpMethod.CONNECT.is(exchange.getRequest().getMethod());
                if (!keepAlive && !connect)
                    closeReason = "http/1.0";
            }
            else
            {
                if (responseHeaders.contains(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()))
                    closeReason = "http/1.1";
            }
        }

        if (closeReason != null)
        {
            if (LOG.isDebugEnabled())
                LOG.debug("Closing, reason: {} - {}", closeReason, connection);
            connection.close();
        }
        else
        {
            if (response.getStatus() == HttpStatus.SWITCHING_PROTOCOLS_101)
                connection.remove();
            else
                release();
        }
    } 

    @Test
    public void testBundle() throws Exception
    {
        HttpClient client = new HttpClient();
        try
        {
            client.start();
            
            assertEquals(HttpStatus.OK_200, response.getStatus());
            String content = new String(response.getContent());
            assertTrue(content.indexOf("<h1>Test OSGi WebAppA</h1>") != -1);

            assertEquals(HttpStatus.OK_200, response.getStatus());
            content = new String(response.getContent());
            assertTrue(content.indexOf("MIMETYPE=application/gzip") != -1);

            assertEquals(HttpStatus.OK_200, response.getStatus());
            content = new String(response.getContent());
            assertTrue(content.indexOf("<h1>Test OSGi WebAppB</h1>") != -1);
        }
        finally
        {
            client.stop();
        }

        ServiceReference[] refs = bundleContext.getServiceReferences(WebAppContext.class.getName(), null);
        assertNotNull(refs);
        assertEquals(2, refs.length);
        WebAppContext wac = (WebAppContext) bundleContext.getService(refs[0]);
        assertEquals("/acme", wac.getContextPath());
        wac = (WebAppContext) bundleContext.getService(refs[1]);
        assertEquals("/acme", wac.getContextPath());
    } 

    @Test
    public void testWrongToken() throws Exception
    {
        start(null);

        HttpTester.Response response = shutdown("wrongToken");
        Assert.assertEquals(HttpStatus.UNAUTHORIZED_401, response.getStatus());

        Thread.sleep(1000);
        Assert.assertEquals(AbstractLifeCycle.STARTED, server.getState());
    } 

            @Override
            public void lifeCycleStopped(LifeCycle event)
            {
                stopLatch.countDown();
            } 

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setRemoteAddr(new InetSocketAddress("192.168.0.1", 12345));
                super.handle(target, baseRequest, request, response);
            } 

    public String get(String url) {
        String responseBody = null;
        try {
            client.start();
            ContentResponse response = client.GET(url);
            if (response.getStatus() == HttpStatus.OK_200) {
                responseBody = response.getContentAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        close();
        return responseBody;
    } 

    public String post(String url, String body) {
        String responseBody = null;
        try {
            client.start();
            ContentResponse response = client.POST(url)
                    .content(new StringContentProvider(body, StandardCharsets.UTF_8))
                    .send();
            if (response.getStatus() == HttpStatus.OK_200) {
                responseBody = response.getContentAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        close();
        return responseBody;
    } 

                                @Override
                                public void succeeded(Connection result)
                                {
                                    connection.set(result);
                                    connectionLatch.countDown();
                                } 

    @Test
    public void testOneExchangeViaSSL() throws Exception
    {
        startSSLServer(new ServerHandler());
        startProxy();

        HttpClient httpClient = new HttpClient(sslContextFactory);
        httpClient.getProxyConfiguration().getProxies().add(new HttpProxy("localhost", proxyPort()));
        httpClient.start();

        try
        {
            String body = "BODY";
            ContentResponse response = httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
                    .send();

            assertEquals(HttpStatus.OK_200, response.getStatus());
            String content = response.getContentAsString();
            assertEquals(body, content);
        }
        finally
        {
            httpClient.stop();
        }
    } 

        }
        catch (IOException x)
        {
            Assume.assumeNoException(x);
        } 

    @Test
    public void testTwoExchangesViaSSL() throws Exception
    {
        startSSLServer(new ServerHandler());
        startProxy();

        HttpClient httpClient = new HttpClient(sslContextFactory);
        httpClient.getProxyConfiguration().getProxies().add(new HttpProxy("localhost", proxyPort()));
        httpClient.start();

        try
        {
            String body = "BODY";
            ContentResponse response1 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
                    .send();

            assertEquals(HttpStatus.OK_200, response1.getStatus());
            String content = response1.getContentAsString();
            assertEquals(body, content);

            content = "body=" + body;
            ContentResponse response2 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.POST)
                    .path("/echo")
                    .header(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString())
                    .header(HttpHeader.CONTENT_LENGTH, String.valueOf(content.length()))
                    .content(new StringContentProvider(content))
                    .send();

            assertEquals(HttpStatus.OK_200, response2.getStatus());
            content = response2.getContentAsString();
            assertEquals(body, content);
        }
        finally
        {
            httpClient.stop();
        }
    } 

    public void onResponseStatus(Buffer version, int status, Buffer reason) throws IOException {
        if (exchange.getMethod().equals("POST") && (status == HttpStatus.SEE_OTHER_303 || status == HttpStatus.MOVED_TEMPORARILY_302)) {
            exchange.setMethod("GET");
        }
        
        if (status == HttpStatus.SEE_OTHER_303) {
            status = HttpStatus.MOVED_TEMPORARILY_302;
        }

        super.onResponseStatus(version, status, reason);
    } 

    @Test
    public void testSimpleWebAppWithJSP() throws Exception
    {
        String jettyVersion = System.getProperty("jettyVersion");
        DistributionTester distribution = DistributionTester.Builder.newInstance()
                .jettyVersion(jettyVersion)
                .mavenLocalRepository(System.getProperty("mavenRepoPath"))
                .build();

        String[] args1 = {
                "--create-startd",
                "--approve-all-licenses",
                "--add-to-start=resources,server,http,webapp,deploy,jsp,jmx,servlet,servlets"
        };
        try (DistributionTester.Run run1 = distribution.start(args1))
        {
            assertTrue(run1.awaitFor(5, TimeUnit.SECONDS));
            assertEquals(0, run1.getExitValue());

            File war = distribution.resolveArtifact("org.eclipse.jetty.tests:test-simple-webapp:war:" + jettyVersion);
            distribution.installWarFile(war, "test");

            int port = distribution.freePort();
            try (DistributionTester.Run run2 = distribution.start("jetty.http.port=" + port))
            {
                assertTrue(run2.awaitConsoleLogsFor("Started @", 10, TimeUnit.SECONDS));

                startHttpClient();
                assertEquals(HttpStatus.OK_200, response.getStatus());
                assertThat(response.getContentAsString(), containsString("Hello"));
                assertThat(response.getContentAsString(), not(containsString("<%")));
            }
        }
    } 

    @DisabledOnJre(JRE.JAVA_8)
    public void testSimpleWebAppWithJSPOnModulePath() throws Exception
    {
        String jettyVersion = System.getProperty("jettyVersion");
        DistributionTester distribution = DistributionTester.Builder.newInstance()
                .jettyVersion(jettyVersion)
                .mavenLocalRepository(System.getProperty("mavenRepoPath"))
                .build();

        String[] args1 = {
                "--create-startd",
                "--approve-all-licenses",
                "--add-to-start=resources,server,http,webapp,deploy,jsp,jmx,servlet,servlets"
        };
        try (DistributionTester.Run run1 = distribution.start(args1))
        {
            assertTrue(run1.awaitFor(5, TimeUnit.SECONDS));
            assertEquals(0, run1.getExitValue());

            File war = distribution.resolveArtifact("org.eclipse.jetty.tests:test-simple-webapp:war:" + jettyVersion);
            distribution.installWarFile(war, "test");

            int port = distribution.freePort();
            String[] args2 = {
                    "--jpms",
                    "jetty.http.port=" + port
            };
            try (DistributionTester.Run run2 = distribution.start(args2))
            {
                assertTrue(run2.awaitConsoleLogsFor("Started @", 10, TimeUnit.SECONDS));

                startHttpClient();
                assertEquals(HttpStatus.OK_200, response.getStatus());
                assertThat(response.getContentAsString(), containsString("Hello"));
                assertThat(response.getContentAsString(), not(containsString("<%")));
            }
        }
    } 

    @DisabledOnJre(JRE.JAVA_8)
    public void testSimpleWebAppWithJSPOverH2C() throws Exception
    {
        String jettyVersion = System.getProperty("jettyVersion");
        DistributionTester distribution = DistributionTester.Builder.newInstance()
                .jettyVersion(jettyVersion)
                .mavenLocalRepository(System.getProperty("mavenRepoPath"))
                .build();

        String[] args1 = {
                "--create-startd",
                "--add-to-start=http2c,jsp,deploy"
        };
        try (DistributionTester.Run run1 = distribution.start(args1))
        {
            assertTrue(run1.awaitFor(5, TimeUnit.SECONDS));
            assertEquals(0, run1.getExitValue());

            File war = distribution.resolveArtifact("org.eclipse.jetty.tests:test-simple-webapp:war:" + jettyVersion);
            distribution.installWarFile(war, "test");

            int port = distribution.freePort();
            try (DistributionTester.Run run2 = distribution.start("jetty.http.port=" + port))
            {
                assertTrue(run2.awaitConsoleLogsFor("Started @", 10, TimeUnit.SECONDS));

                HTTP2Client h2Client = new HTTP2Client();
                startHttpClient(() -> new HttpClient(new HttpClientTransportOverHTTP2(h2Client), null));
                assertEquals(HttpStatus.OK_200, response.getStatus());
                assertThat(response.getContentAsString(), containsString("Hello"));
                assertThat(response.getContentAsString(), not(containsString("<%")));
            }
        }
    } 

    @Test
    public void testUnixSocket() throws Exception
    {
        Path tmpSockFile;
        String unixSocketTmp = System.getProperty("unix.socket.tmp");
        if (StringUtil.isNotBlank(unixSocketTmp))
            tmpSockFile = Files.createTempFile(Paths.get(unixSocketTmp), "unix", ".sock");
        else
            tmpSockFile = Files.createTempFile("unix", ".sock");
        if (tmpSockFile.toAbsolutePath().toString().length() > UnixSocketConnector.MAX_UNIX_SOCKET_PATH_LENGTH)
        {
            Path tmp = Paths.get("/tmp");
            assumeTrue(Files.exists(tmp) && Files.isDirectory(tmp));
            tmpSockFile = Files.createTempFile(tmp, "unix", ".sock");
        }
        Path sockFile = tmpSockFile;
        assertTrue(Files.deleteIfExists(sockFile), "temp sock file cannot be deleted");

        String jettyVersion = System.getProperty("jettyVersion");
        DistributionTester distribution = DistributionTester.Builder.newInstance()
                .jettyVersion(jettyVersion)
                .mavenLocalRepository(System.getProperty("mavenRepoPath"))
                .build();

        String[] args1 = {
                "--create-startd",
                "--add-to-start=unixsocket-http,deploy,jsp",
                "--approve-all-licenses"
        };
        try (DistributionTester.Run run1 = distribution.start(args1))
        {
            assertTrue(run1.awaitFor(5, TimeUnit.SECONDS));
            assertEquals(0, run1.getExitValue());

            File war = distribution.resolveArtifact("org.eclipse.jetty.tests:test-simple-webapp:war:" + jettyVersion);
            distribution.installWarFile(war, "test");

            try (DistributionTester.Run run2 = distribution.start("jetty.unixsocket.path=" + sockFile.toString()))
            {
                assertTrue(run2.awaitConsoleLogsFor("Started @", 10, TimeUnit.SECONDS));

                startHttpClient(() -> new HttpClient(new HttpClientTransportOverUnixSockets(sockFile.toString()), null));
                assertEquals(HttpStatus.OK_200, response.getStatus());
                assertThat(response.getContentAsString(), containsString("Hello"));
                assertThat(response.getContentAsString(), not(containsString("<%")));
            }
        }
        finally
        {
            Files.deleteIfExists(sockFile);
        }
    } 

    @Test
    public void testStartStop() throws Exception
    {
        String jettyVersion = System.getProperty("jettyVersion");
        DistributionTester distribution = DistributionTester.Builder.newInstance()
                .jettyVersion(jettyVersion)
                .mavenLocalRepository(System.getProperty("mavenRepoPath"))
                .build();

        try (DistributionTester.Run run1 = distribution.start("--add-to-start=http"))
        {
            assertTrue(run1.awaitFor(5, TimeUnit.SECONDS));
            assertEquals(0, run1.getExitValue());

            int port = distribution.freePort();
            try (DistributionTester.Run run2 = distribution.start("jetty.http.port=" + port))
            {
                assertTrue(run2.awaitConsoleLogsFor("Started @", 10, TimeUnit.SECONDS));

                startHttpClient();
                assertEquals(HttpStatus.NOT_FOUND_404, response.getStatus());

                run2.stop();
                assertTrue(run2.awaitFor(5, TimeUnit.SECONDS));
            }
        }
    } 

    @Test
    public void testDemoBase() throws Exception
    {
        String jettyVersion = System.getProperty("jettyVersion");
        DistributionTester distribution = DistributionTester.Builder.newInstance()
                .jettyVersion(jettyVersion)
                .jettyBase(Paths.get("demo-base"))
                .mavenLocalRepository(System.getProperty("mavenRepoPath"))
                .build();

        int port = distribution.freePort();
        try (DistributionTester.Run run1 = distribution.start("jetty.http.port=" + port))
        {
            assertTrue(run1.awaitConsoleLogsFor("Started @", 20, TimeUnit.SECONDS));

            startHttpClient();
            assertEquals(HttpStatus.OK_200, response.getStatus());
            assertThat(response.getContentAsString(), containsString("PathInfo"));
            assertThat(response.getContentAsString(), not(containsString("<%")));
        }
    } 

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                ref.set(baseRequest.getHttpChannel().getEndPoint());
                ServletInputStream input = request.getInputStream();
                while (true)
                {
                    int read = input.read();
                    if (read < 0)
                        break;
                }
                response.setStatus(HttpStatus.OK_200);
            } 

    @Test
    public void test_PUT_301() throws Exception
    {
        testSameMethodRedirect(HttpMethod.PUT, HttpStatus.MOVED_PERMANENTLY_301);
    } 

    @Test
    public void test_HEAD_302() throws Exception
    {
        testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.FOUND_302);
    } 

    @Test
    public void test_PUT_303() throws Exception
    {
        testGETRedirect(HttpMethod.PUT, HttpStatus.SEE_OTHER_303);
    } 

    @Test
    public void test_HEAD_303() throws Exception
    {
        testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.SEE_OTHER_303);
    } 

    @Test
    public void test_HEAD_301() throws Exception
    {
        testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.MOVED_PERMANENTLY_301);
    } 

    @Test
    public void test_PUT_307() throws Exception
    {
        testSameMethodRedirect(HttpMethod.PUT, HttpStatus.TEMPORARY_REDIRECT_307);
    } 

    @Test
    public void test_PUT_302() throws Exception
    {
        testSameMethodRedirect(HttpMethod.PUT, HttpStatus.FOUND_302);
    } 

    @Test
    public void test_HEAD_307() throws Exception
    {
        testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.TEMPORARY_REDIRECT_307);
    } 

    @Test
    public void test_POST_301() throws Exception
    {
        testGETRedirect(HttpMethod.POST, HttpStatus.MOVED_PERMANENTLY_301);
    } 

    @Test
    public void test_POST_302() throws Exception
    {
        testGETRedirect(HttpMethod.POST, HttpStatus.FOUND_302);
    } 

    @Test
    public void test_POST_307() throws Exception
    {
        testSameMethodRedirect(HttpMethod.POST, HttpStatus.TEMPORARY_REDIRECT_307);
    } 

    @Test
    public void test_POST_303() throws Exception
    {
        testGETRedirect(HttpMethod.POST, HttpStatus.SEE_OTHER_303);
    } 

			protected void writeDebugInfo(final HttpServletRequest request, final Writer writer) throws IOException {
				writer.write("<hr>");
				writer.write("<h1>Welcome to Gyrex!</h1>");
				writer.write("<img src=\"" + DefaultErrorHandlerResourcesHandler.URI_GYREX_LOGO + "\" style=\"float:right;padding-left:1em;\">");
				writer.write("<p>Useful links:");
				writer.write("<ul>");
				writer.write("</ul></p>");
				writer.write("<div style=\"clear:both;\"></div>");
				writer.write("<hr>");
				writer.write(NEWLINE);
				final Server server = getServer();
				final Handler[] handlers = server == null ? null : server.getChildHandlersByClass(ApplicationHandler.class);
				if (handlers.length > 0) {
					writer.write("<p>Applications known to this server are: <ul>");
					writer.write(NEWLINE);
					for (int i = 0; (handlers != null) && (i < handlers.length); i++) {
						writer.write("<li>");
						final ApplicationHandler appHandler = (ApplicationHandler) handlers[i];
						writer.write(appHandler.getApplicationId());
						writer.write(" (");
						writer.write(appHandler.getApplicationRegistration().getProviderId());
						writer.write(")");
						if (appHandler.isRunning()) {
							writer.write(" [running]");
						} else {
							if (appHandler.isFailed()) {
								writer.write(" [failed]");
							}
							if (appHandler.isStopped()) {
								writer.write(" [stopped]");
							}
						}
						final String[] urls = appHandler.getUrls();
						for (final String url : urls) {
							writer.write(String.format("<br><small> --> <a href=\"%s\">%s</a></small>", url, url));
						}
						writer.write("</li>");
						writer.write(NEWLINE);
					}
					writer.write("</ul></p>");
					writer.write(NEWLINE);
				} else {
					writer.write("<p>No applications known to this server!</p>");
					writer.write(NEWLINE);
				}
				if (JettyDebug.handlers) {
					writer.write("<pre>");
					writer.write(NEWLINE);
					server.dump(writer);
					writer.write("</pre>");
					writer.write(NEWLINE);
				}
			} 

                }
                catch (InterruptedException x)
                {
                    onConnectFailure(request, response, null, x);
                } 

    @Test
    public void testTwoExchanges() throws Exception
    {
        startTLSServer(new ServerHandler());
        startProxy();

        HttpClient httpClient = new HttpClient(newSslContextFactory());
        httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
        httpClient.start();

        try
        {
            String body = "BODY";
            ContentResponse response1 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
                    .send();

            Assert.assertEquals(HttpStatus.OK_200, response1.getStatus());
            String content = response1.getContentAsString();
            Assert.assertEquals(body, content);

            content = "body=" + body;
            ContentResponse response2 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.POST)
                    .path("/echo")
                    .header(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString())
                    .header(HttpHeader.CONTENT_LENGTH, String.valueOf(content.length()))
                    .content(new StringContentProvider(content))
                    .send();

            Assert.assertEquals(HttpStatus.OK_200, response2.getStatus());
            content = response2.getContentAsString();
            Assert.assertEquals(body, content);
        }
        finally
        {
            httpClient.stop();
        }
    } 

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            {
                String proxyAuth = request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString());
                if (proxyAuth == null)
                {
                    baseRequest.setHandled(true);
                    response.setStatus(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407);
                    response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "Basic realm=\"" + proxyRealm + "\"");
                    return;
                }
                super.handle(target, baseRequest, request, response);
            } 

                            @Override
                            public void succeeded(Connection result)
                            {
                                connection.set(result);
                                connectionLatch.countDown();
                            } 

    @Test
    public void testOneExchange() throws Exception
    {
        startTLSServer(new ServerHandler());
        startProxy();

        HttpClient httpClient = new HttpClient(newSslContextFactory());
        httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
        httpClient.start();

        try
        {
            String host = "127.0.0.1";
            String body = "BODY";
            ContentResponse response = httpClient.newRequest(host, serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
                    .send();

            Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
            String content = response.getContentAsString();
            Assert.assertEquals(body, content);
        }
        finally
        {
            httpClient.stop();
        }
    } 

        }
        catch (Throwable x)
        {
            Assume.assumeNoException(x);
        } 

    public Response sendGETRequest(Range range) throws IOException {
        try {
            InputStreamResponseListener listener =
                    new InputStreamResponseListener();

            extraHeaders.set("Range",
                    "bytes=" + range.start + "-" + range.end);

            Request request = jettyClient
                    .newRequest(uri)
                    .timeout(requestTimeoutSeconds, TimeUnit.SECONDS)
                    .method(HttpMethod.GET);
            extraHeaders.forEach(h -> request.header(h.getName(), h.getValue()));

            LOGGER.trace("Requesting GET {} (extra headers: {})",
                    uri, extraHeaders);

            request.send(listener);

            org.eclipse.jetty.client.api.Response jettyResponse = listener.get(
                    requestTimeoutSeconds, TimeUnit.SECONDS);

            if (jettyResponse.getStatus() == HttpStatus.OK_200 ||
                    jettyResponse.getStatus() == HttpStatus.PARTIAL_CONTENT_206) {
                return toResponse(jettyResponse, listener);
            } else {
                throw new IOException("Unexpected HTTP response code: " +
                        jettyResponse.getStatus());
            }
        } catch (InterruptedException | TimeoutException | ExecutionException e) {
            throw new IOException(e);
        }
    } 

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                if (target.equals("/timeout"))
                {
                    AsyncContext asyncContext = request.startAsync();
                    asyncContext.setTimeout(0);
                }
            } 

    @Test
    public void testIdleClientIdleTimeout() throws Exception
    {
        start(new EmptyServerHandler());
        client.stop();
        client.setIdleTimeout(idleTimeout);
        client.start();

        ContentResponse response = client.newRequest(newURI()).send();
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());

        Thread.sleep(2 * idleTimeout);

        response = client.newRequest(newURI()).send();
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testRequestIdleTimeout() throws Exception
    {
        start(new AbstractHandler()
        {
            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                baseRequest.setHandled(true);
                if (target.equals("/timeout"))
                {
                    AsyncContext asyncContext = request.startAsync();
                    asyncContext.setTimeout(0);
                }
            }
        });

        final CountDownLatch latch = new CountDownLatch(1);
        client.newRequest(newURI())
                .path("/timeout")
                .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS)
                .send(result ->
                {
                    if (result.isFailed())
                        latch.countDown();
                });

        Assert.assertTrue(latch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));

        ContentResponse response = client.newRequest(newURI()).send();
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } 

    @Test
    public void testIdleServerIdleTimeout() throws Exception
    {
        start(new EmptyServerHandler());
        connector.setIdleTimeout(idleTimeout);

        ContentResponse response1 = client.newRequest(newURI()).send();
        Assert.assertEquals(HttpStatus.OK_200, response1.getStatus());

        Thread.sleep(2 * idleTimeout);

        ContentResponse response2 = client.newRequest(newURI()).send();
        Assert.assertEquals(HttpStatus.OK_200, response2.getStatus());
    } 

	public void testSecurity() throws Exception {
		Request request = HttpTester.newRequest();
		request.setHeader("Host", "tester");
		request.setMethod("GET");
		request.setURI("/");

		ByteBuffer responseString = localConnector.getResponses(request.generate());
		Response response = HttpTester.parseResponse(responseString);
		assertEquals(HttpStatus.UNAUTHORIZED_401, response.getStatus());
		assertTrue(response.contains(HttpHeader.WWW_AUTHENTICATE, "Basic realm=\"Security Test\""));

		request.setHeader(HttpHeader.AUTHORIZATION.toString(), "Basic " + B64Code.encode("alice:alicepassword"));
		responseString = localConnector.getResponses(request.generate());
		response = HttpTester.parseResponse(responseString);
		assertEquals(HttpStatus.OK_200, response.getStatus());

		request.setHeader(HttpHeader.AUTHORIZATION.toString(), "Basic " + B64Code.encode("bob:bobpassword"));
		responseString = localConnector.getResponses(request.generate());
		response = HttpTester.parseResponse(responseString);
		assertEquals(HttpStatus.FORBIDDEN_403, response.getStatus());
	} 

    public void doGet_insufficientPermissions_Cars() throws Exception {
        HttpURLConnection http = (HttpURLConnection) serverUri.resolve("/Controller?command=CARS").toURL().openConnection();
        http.connect();
        assertThat("Response Code", http.getResponseCode(), is(HttpStatus.FORBIDDEN_403));
    } 

    public void doGet_Abracadabra() throws Exception {
        HttpURLConnection http = (HttpURLConnection) serverUri.resolve("/abracadabra").toURL().openConnection();
        http.connect();
        assertThat("Response Code", http.getResponseCode(), is(HttpStatus.NOT_FOUND_404));
    } 

    public void doGet_Car() throws Exception {
        HttpURLConnection http = (HttpURLConnection) serverUri.resolve("/Controller?command=USERSPACE").toURL().openConnection();
        http.connect();
        assertThat("Response Code", http.getResponseCode(), is(HttpStatus.OK_200));
    } 

    public void doGet_insufficientPermissions_Admin() throws Exception {
        HttpURLConnection http = (HttpURLConnection) serverUri.resolve("/Controller?command=ADMIN").toURL().openConnection();
        http.connect();
        assertThat("Response Code", http.getResponseCode(), is(HttpStatus.FORBIDDEN_403));
    } 

    public void doGet_insufficientPermissions() throws Exception {
        HttpURLConnection http = (HttpURLConnection) serverUri.resolve("/Controller?command=INVOICES").toURL().openConnection();
        http.connect();
        assertThat("Response Code", http.getResponseCode(), is(HttpStatus.FORBIDDEN_403));
    } 

                    @Override
                    public void failed(Throwable x)
                    {
                        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
                        response.setHeader("X-Failure", "stream");
                        asyncContext.complete();
                    } 

            @Override
            public void failed(Throwable x)
            {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
                response.setHeader("X-Failure", "session");
                asyncContext.complete();
            } 

    }

    public void emit(HttpField field)
    {
        HttpHeader header = field.getHeader();
        String name = field.getName();
        String value = field.getValue();
        int field_size = name.length() + (value == null ? 0 : value.length());
        _size+=field_size+32;
        if (_size>_maxSize)
            throw new BadMessageException(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE_431,"Header size "+_size+">"+_maxSize);

        if (field instanceof StaticTableHttpField)
        {
            StaticTableHttpField staticField = (StaticTableHttpField)field;
            switch(header)
            {
                case C_STATUS:
                    _status=(Integer)staticField.getStaticValue();
                    break;

                case C_METHOD:
                    _method=value;
                    break;

                case C_SCHEME:
                    _scheme = (HttpScheme)staticField.getStaticValue();
                    break;

                default:
                    throw new IllegalArgumentException(name);
            }
        }
        else if (header!=null)
        {
            switch(header)
            {
                case C_STATUS:
                    _status=field.getIntValue();
                    break;

                case C_METHOD:
                    _method=value;
                    break;

                case C_SCHEME:
                    if (value != null)
                        _scheme = HttpScheme.CACHE.get(value);
                    break;

                case C_AUTHORITY:
                    if (field instanceof HostPortHttpField)
                        _authority = (HostPortHttpField)field;
                    else if (value != null)
                        _authority = new AuthorityHttpField(value);
                    break;

                case HOST:
                    if (_authority==null)
                    {
                        if (field instanceof HostPortHttpField)
                            _authority = (HostPortHttpField)field;
                        else if (value != null)
                            _authority = new AuthorityHttpField(value);
                    }
                    _fields.add(field);
                    break;

                case C_PATH:
                    _path = value;
                    break;

                case CONTENT_LENGTH:
                    _contentLength = field.getLongValue();
                    _fields.add(field);
                    break;

                default:
                    if (name.charAt(0)!=':')
                        _fields.add(field);
                    break;
            }
        }
        else
        {
            if (name.charAt(0)!=':')
                _fields.add(field);
        }
    } 

    
    public void checkSize(int length, boolean huffman)
    {
        if (huffman)
            length=(length*4)/3;
        if ((_size+length)>_maxSize)
            throw new BadMessageException(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE_431,"Header size "+(_size+length)+">"+_maxSize);
    } 

    @Override
    protected void onResponseStatus(Buffer version, int status, Buffer reason) throws IOException
    {
        if ( status == HttpStatus.OK_200 )
        {
            LOG.debug( "PropfindExchange:Status: Exists" );
            _propertyExists = true;
        }
        else
        {
            LOG.debug( "PropfindExchange:Status: Not Exists" );
        }

        super.onResponseStatus(version, status, reason);
    } 

    @Test
    public void testDeferredContent() throws Exception
    {
        start(new ConsumeInputHandler());

        DeferredContentProvider contentProvider = new DeferredContentProvider();
        CountDownLatch latch = new CountDownLatch(1);
        client.POST(newURI())
                .content(contentProvider)
                .send(result ->
                {
                    if (result.isSucceeded() &&
                            result.getResponse().getStatus() == HttpStatus.OK_200)
                        latch.countDown();
                });
        contentProvider.offer(ByteBuffer.wrap(new byte[1]));
        contentProvider.close();

        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    } 

    @Test
    public void testEmptyInputStream() throws Exception
    {
        start(new ConsumeInputHandler());

        InputStreamContentProvider contentProvider =
                new InputStreamContentProvider(new ByteArrayInputStream(new byte[0]));
        CountDownLatch latch = new CountDownLatch(1);
        client.POST(newURI())
                .content(contentProvider)
                .send(result ->
                {
                    if (result.isSucceeded() &&
                            result.getResponse().getStatus() == HttpStatus.OK_200)
                        latch.countDown();
                });
        contentProvider.close();

        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    } 

    @Test
    public void testEmptyDeferredContent() throws Exception
    {
        start(new ConsumeInputHandler());

        DeferredContentProvider contentProvider = new DeferredContentProvider();
        CountDownLatch latch = new CountDownLatch(1);
        client.POST(newURI())
                .content(contentProvider)
                .send(result ->
                {
                    if (result.isSucceeded() &&
                            result.getResponse().getStatus() == HttpStatus.OK_200)
                        latch.countDown();
                });
        contentProvider.close();

        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    } 

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
        {
            baseRequest.setHandled(true);
            ServletInputStream input = request.getInputStream();
            while (true)
            {
                int read = input.read();
                if (read < 0)
                    break;
            }
            response.setStatus(HttpStatus.OK_200);
        } 

    @Test
    public void testEmptyOutputStream() throws Exception
    {
        start(new ConsumeInputHandler());

        OutputStreamContentProvider contentProvider = new OutputStreamContentProvider();
        CountDownLatch latch = new CountDownLatch(1);
        client.POST(newURI())
                .content(contentProvider)
                .send(result ->
                {
                    if (result.isSucceeded() &&
                            result.getResponse().getStatus() == HttpStatus.OK_200)
                        latch.countDown();
                });
        contentProvider.close();

        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    } 

    @Test
    public void testInputStream() throws Exception
    {
        start(new ConsumeInputHandler());

        InputStreamContentProvider contentProvider =
                new InputStreamContentProvider(new ByteArrayInputStream(new byte[1]));
        CountDownLatch latch = new CountDownLatch(1);
        client.POST(newURI())
                .content(contentProvider)
                .send(result ->
                {
                    if (result.isSucceeded() &&
                            result.getResponse().getStatus() == HttpStatus.OK_200)
                        latch.countDown();
                });
        contentProvider.close();

        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    } 

    @Test
    public void testOutputStream() throws Exception
    {
        start(new ConsumeInputHandler());

        OutputStreamContentProvider contentProvider = new OutputStreamContentProvider();
        CountDownLatch latch = new CountDownLatch(1);
        client.POST(newURI())
                .content(contentProvider)
                .send(result ->
                {
                    if (result.isSucceeded() &&
                            result.getResponse().getStatus() == HttpStatus.OK_200)
                        latch.countDown();
                });
        OutputStream output = contentProvider.getOutputStream();
        output.write(new byte[1]);
        output.flush();
        contentProvider.close();

        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    } 

Advertisement
Javadoc


Http Status Codes @see IANA HTTP Status Code Registry
Advertisement