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

Following code examples demonstrate how to use org.eclipse.jetty.http.HttpMethod 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.HttpMethod and various code implementation of this class.

    
    private boolean performRequest(Fields headers)
    {
        short version = stream.getSession().getVersion();
        Fields.Field methodHeader = headers.get(HTTPSPDYHeader.METHOD.name(version));
        Fields.Field uriHeader = headers.get(HTTPSPDYHeader.URI.name(version));
        Fields.Field versionHeader = headers.get(HTTPSPDYHeader.VERSION.name(version));

        if (methodHeader == null || uriHeader == null || versionHeader == null)
        {
            onBadMessage(400, "Missing required request line elements");
            return false;
        }

        HttpMethod httpMethod = HttpMethod.fromString(methodHeader.getValue());
        HttpVersion httpVersion = HttpVersion.fromString(versionHeader.getValue());


        if (LOG.isDebugEnabled())
            LOG.debug("HTTP > {} {} {}", httpMethod, uriHeader.getValue(), httpVersion);


        HostPortHttpField hostPort = null;
        HttpFields fields = new HttpFields();
        for (Fields.Field header : headers)
        {
            String name = header.getName();

            HTTPSPDYHeader specialHeader = HTTPSPDYHeader.from(stream.getSession().getVersion(), name);
            if (specialHeader != null)
            {
                if (specialHeader != HTTPSPDYHeader.HOST)
                    continue;
                name = "host";
            }

            switch (name)
            {
                case "connection":
                case "keep-alive":
                case "proxy-connection":
                case "transfer-encoding":
                {
                    break;
                }
                case "host":
                {
                    hostPort = new HostPortHttpField(header.getValue());
                    break;
                }
                default:
                {
                    String value = header.getValue();
                    if (LOG.isDebugEnabled())
                        LOG.debug("HTTP > {}: {}", name, value);
                    fields.add(new HttpField(name, value));
                    break;
                }
            }
        }

        if (hostPort == null)
        {
            onBadMessage(400, "Missing Host header");
            return false;
        }

        if (hostPort!=null)
            fields.add(hostPort);

        Fields.Field schemeHeader = headers.get(HTTPSPDYHeader.SCHEME.name(version));
        
        HttpURI uri = new HttpURI(uriHeader.getValue());
        if (uri.getScheme()==null && schemeHeader!=null)
            uri.setScheme(schemeHeader.getValue());
        if (uri.getHost()==null && hostPort!=null)
            uri.setAuthority(hostPort.getHost(),hostPort.getPort());
        
        MetaData.Request request = new MetaData.Request(httpMethod==null?methodHeader.getValue():httpMethod.asString(), uri, httpVersion, fields);
        onRequest(request);
        return true;
    } 


    private String sendRequest(HttpMethod httpMethod, String bearerToken, String url, String... params) throws InterruptedException, ExecutionException, TimeoutException {
        if (params.length % 2 != 0)
            throw new IllegalArgumentException("There has to be an even number of parameters!");
        Request request = bearerToken != null ? createAuthorizedRequest(bearerToken, url) : createRequest(url);
        request.method(httpMethod);
        if (params.length > 0) {
            for (int i = 0; i <= params.length / 2; i += 2)
                request.param(params[i], params[i + 1]);
        }
        LOGGER.debug("[{}] {}", httpMethod.name(), request.getURI());
        return request.send().getContentAsString();
    } 

    @Override
    public void handle(final String target,
                       final Request baseRequest,
                       final HttpServletRequest request,
                       final HttpServletResponse response) throws IOException {

        final String method = request.getMethod();
        if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.PUT.is(method) && !HttpMethod.HEAD.is(method)) {
            baseRequest.setHandled(true);
            return;
        }

        baseRequest.setHandled(true);
        response.setContentType(MimeTypes.Type.APPLICATION_JSON.asString());

        final ByteArrayISO8859Writer byteArrayWriter = new ByteArrayISO8859Writer(4096);
        final String reason = (response instanceof Response) ? ((Response) response).getReason() : null;

        handleErrorPage(request, byteArrayWriter, response.getStatus(), reason);

        byteArrayWriter.flush();
        response.setContentLength(byteArrayWriter.size());
        byteArrayWriter.writeTo(response.getOutputStream());
        byteArrayWriter.destroy();
    } 

            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                Exception e = null;
                Tuple<HttpServletRequest, HttpServletResponse> t = routesFactory.preRouting(request, response);
                final HttpServletRequest req = t.x;
                final HttpServletResponse resp = t.y;

                try {
                    HttpMethod httpMethod = HttpMethod.fromString(baseRequest.getMethod());

                    routesFactory.getRoutes(baseRequest.getHeader("Accept")).stream()
                            .filter(r -> !resp.isCommitted())
                            .filter(r -> r.test(httpMethod, target))
                            .forEach(r -> r.execute(req, resp));

                    if (!resp.isCommitted()) {
                        RestResponseUtils.setJsonResponse(resp, 404, "No handler found for " + httpMethod + " " + target);
                    }
                } catch (Exception ex) {
                    e = ex;
                    RestResponseUtils.internalServer(resp, e);
                } finally {
                    routesFactory.postRouting(req, resp, e);
                }
            } 

		public String getMethod() {
			return (this.simulateGetMethod ? HttpMethod.GET.toString()
					: super.getMethod());
		} 

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

    @Test
    public void testProxyDown() throws Exception
    {
        startSSLServer(new ServerHandler());
        startProxy();
        int proxyPort = proxyPort();
        stopProxy();

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

        try
        {
            String body = "BODY";
            httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
                    .send();
            Assert.fail();
        }
        catch (ExecutionException x)
        {
            Assert.assertThat(x.getCause(), Matchers.instanceOf(ConnectException.class));
        }
        finally
        {
            httpClient.stop();
        }
    } 

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

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

        try
        {
            final AtomicReference<Connection> connection = new AtomicReference<>();
            final CountDownLatch connectionLatch = new CountDownLatch(1);
            String body1 = "BODY";
            ContentResponse response1 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body1, "UTF-8"))
                    .onRequestCommit(new org.eclipse.jetty.client.api.Request.CommitListener()
                    {
                        @Override
                        public void onCommit(org.eclipse.jetty.client.api.Request request)
                        {
                            Destination destination = httpClient.getDestination(HttpScheme.HTTPS.asString(), "localhost", serverConnector.getLocalPort());
                            destination.newConnection(new Promise.Adapter<Connection>()
                            {
                                @Override
                                public void succeeded(Connection result)
                                {
                                    connection.set(result);
                                    connectionLatch.countDown();
                                }
                            });
                        }
                    })
                    .send();

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

            Assert.assertTrue(connectionLatch.await(5, TimeUnit.SECONDS));

            String body2 = "body=" + body1;
            org.eclipse.jetty.client.api.Request request2 = 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(body2.length()))
                    .content(new StringContentProvider(body2));

            FutureResponseListener listener2 = new FutureResponseListener(request2);
            connection.get().send(request2, listener2);
            ContentResponse response2 = listener2.get(5, TimeUnit.SECONDS);

            assertEquals(HttpStatus.OK_200, response2.getStatus());
            String content2 = response1.getContentAsString();
            assertEquals(body1, content2);
        }
        finally
        {
            httpClient.stop();
        }
    } 

    @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();
        }
    } 

    @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();
        }
    } 

    @Test
    public void testServerDown() throws Exception
    {
        startSSLServer(new ServerHandler());
        int serverPort = serverConnector.getLocalPort();
        stopServer();
        startProxy();

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

        try
        {
            String body = "BODY";
            httpClient.newRequest("localhost", serverPort)
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
                    .send();
            Assert.fail();
        }
        catch (ExecutionException x)
        {
        }
        finally
        {
            httpClient.stop();
        }
    } 

    @Test
    public void test_301_WithWrongMethod() throws Exception
    {
        try
        {
            client.newRequest("localhost", connector.getLocalPort())
                    .scheme(scheme)
                    .method(HttpMethod.DELETE)
                    .path("/301/localhost/done")
                    .timeout(5, TimeUnit.SECONDS)
                    .send();
            Assert.fail();
        }
        catch (ExecutionException x)
        {
            HttpResponseException xx = (HttpResponseException)x.getCause();
            Response response = xx.getResponse();
            Assert.assertNotNull(response);
            Assert.assertEquals(301, response.getStatus());
            Assert.assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
        }
    } 

    @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_301() throws Exception
    {
        Response response = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .method(HttpMethod.HEAD)
                .path("/301/localhost/done")
                .timeout(5, TimeUnit.SECONDS)
                .send();
        Assert.assertNotNull(response);
        Assert.assertEquals(200, response.getStatus());
        Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
    } 

    @Test
    public void test_307_WithRequestContent() throws Exception
    {
        byte[] data = new byte[]{0, 1, 2, 3, 4, 5, 6, 7};
        ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
                .scheme(scheme)
                .method(HttpMethod.POST)
                .path("/307/localhost/done")
                .content(new ByteBufferContentProvider(ByteBuffer.wrap(data)))
                .timeout(5, TimeUnit.SECONDS)
                .send();
        Assert.assertNotNull(response);
        Assert.assertEquals(200, response.getStatus());
        Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
        Assert.assertArrayEquals(data, response.getContent());
    } 

    @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);
    } 

    }

    private void testGETRedirect(final HttpMethod method, int redirectCode) throws Exception
    {
        testMethodRedirect(method, HttpMethod.GET, redirectCode);
    } 

    @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);
    } 

    public static HttpMethod createHttpMethod(String httpMethodString) {

        if ("GET".equals(httpMethodString)) {
            return HttpMethod.GET;
        } else if ("PUT".equals(httpMethodString)) {
            return HttpMethod.PUT;
        } else if ("POST".equals(httpMethodString)) {
            return HttpMethod.POST;
        } else if ("DELETE".equals(httpMethodString)) {
            return HttpMethod.DELETE;
        } else {
            throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown");
        }
    } 

                public boolean matches(String type, URI uri, String realm) {
                    realm = anyRealm;
                    return super.matches(type, uri, realm);
                } 

	public void testUpdate(String hospital) throws Exception {

		HttpClient httpClient = new HttpClient();
		httpClient.start();

		try {

					method(HttpMethod.POST).
					content(new StringContentProvider(hospital),"application/json").
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(), 200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testDelete(String hospital) throws Exception {
		HttpClient httpClient = new HttpClient(); 
		httpClient.start();

		try {

					method(HttpMethod.DELETE).
					content(new StringContentProvider(hospital),"application/json").
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(), 200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testCreate(String hospital) throws Exception {

		HttpClient httpClient = new HttpClient();
		httpClient.start();

		try {
			
					method(HttpMethod.PUT).
					content(new StringContentProvider(hospital),("application/json")).
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(), 200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testreadOne(String hospital) throws Exception {
		HttpClient httpClient = new HttpClient(); 
		httpClient.start();

		try {

					method(HttpMethod.GET).
					content(new StringContentProvider(hospital),"application/json").
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(), 200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

    }

    private boolean test(Session session, CountDownLatch latch) throws Exception
    {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        boolean download = random.nextBoolean();
        HttpMethod method = download ? HttpMethod.GET : HttpMethod.POST;

        int maxContentLength = 128 * 1024;
        int contentLength = random.nextInt(maxContentLength) + 1;

        long requestId = requestIds.incrementAndGet();
        MetaData.Request request = newRequest(method.asString(), "/" + requestId, new HttpFields());
        if (download)
            request.getFields().put("X-Download", String.valueOf(contentLength));
        HeadersFrame requestFrame = new HeadersFrame(request, null, download);
        FuturePromise<Stream> promise = new FuturePromise<>();
        CountDownLatch requestLatch = new CountDownLatch(1);
        AtomicBoolean reset = new AtomicBoolean();
        session.newStream(requestFrame, promise, new Stream.Listener.Adapter()
        {
            @Override
            public void onHeaders(Stream stream, HeadersFrame frame)
            {
                if (frame.isEndStream())
                    requestLatch.countDown();
            }

            @Override
            public void onData(Stream stream, DataFrame frame, Callback callback)
            {
                callback.succeeded();
                if (frame.isEndStream())
                    requestLatch.countDown();
            }

            @Override
            public void onReset(Stream stream, ResetFrame frame)
            {
                reset.set(true);
                requestLatch.countDown();
            }
        });
        if (!download)
        {
            Stream stream = promise.get(5, TimeUnit.SECONDS);
            stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(contentLength), true), Callback.NOOP);
        }

        boolean success = requestLatch.await(5, TimeUnit.SECONDS);
        if (success)
            latch.countDown();
        else
            logger.warn("Request {} took too long{}Server:{}{}{}Client:{}{}", requestId,
                    System.lineSeparator(), System.lineSeparator(), server.dump(),
                    System.lineSeparator(), System.lineSeparator(), client.dump());
        return !reset.get();
    } 

	public void testUpdate(String dr) throws Exception {

		HttpClient httpClient = new HttpClient();
		httpClient.start(); 

		try {
			
					method(HttpMethod.POST).
					content(new StringContentProvider(dr),("application/json")).
					send();
			System.out.println(response.getStatus());
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(),200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testreadOne(String doctor) throws Exception {
		HttpClient httpClient = new HttpClient(); 
		httpClient.start();

		try {

					method(HttpMethod.GET).
					content(new StringContentProvider(doctor),"application/json").
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(),200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testCreate(String dr) throws Exception {

		HttpClient httpClient = new HttpClient();
		httpClient.start();

		try {
			
					method(HttpMethod.PUT).
					content(new StringContentProvider(dr),("application/json")).
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testDelete(String doctor) throws Exception {
		HttpClient httpClient = new HttpClient(); 
		httpClient.start();

		try {

					method(HttpMethod.DELETE).
					content(new StringContentProvider(doctor),"application/json").
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(),200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testUpdate(String pt) throws Exception {

		HttpClient httpClient = new HttpClient();
		httpClient.start(); 

		try {
			
					method(HttpMethod.POST).
					content(new StringContentProvider(pt),("application/json")).
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(), 200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testCreate(String pt) throws Exception {

		HttpClient httpClient = new HttpClient();
		httpClient.start();

		try {
			
					method(HttpMethod.PUT).
					content(new StringContentProvider(pt),("application/json")).
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(), 200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testreadOne(String patient) throws Exception {
		HttpClient httpClient = new HttpClient(); 
		httpClient.start();

		try {

					method(HttpMethod.DELETE).
					content(new StringContentProvider(patient),"application/json").
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(), 200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

	public void testDelete(String patient) throws Exception {
		HttpClient httpClient = new HttpClient(); 
		httpClient.start();

		try {

					method(HttpMethod.DELETE).
					content(new StringContentProvider(patient),"application/json").
					send();
			System.out.println(response);
			System.out.println(response.getContentAsString());
			Assert.assertEquals(response.getStatus(), 200);
		} catch (Exception e) {
			throw new AppException(e);
		}
	} 

            @Override
            protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
            {
                switch (HttpMethod.fromString(request.getMethod()))
                {
                    case GET:
                    {
                        int contentLength = request.getIntHeader("X-Download");
                        if (contentLength > 0)
                        {
                            response.setContentLength(contentLength);
                            response.getOutputStream().write(new byte[contentLength]);
                        }
                        break;
                    }
                    case POST:
                    {
                        int contentLength = request.getContentLength();
                        if (contentLength > 0)
                            response.setContentLength(contentLength);
                        IO.copy(request.getInputStream(), response.getOutputStream());
                        break;
                    }
                    default:
                    {
                        throw new IllegalStateException();
                    }
                }

                if (Boolean.parseBoolean(request.getHeader("X-Close")))
                    response.setHeader("Connection", "close");
            } 

    }

    private void test(List<Throwable> failures)
    {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        HttpMethod method = random.nextBoolean() ? HttpMethod.GET : HttpMethod.POST;

        boolean clientClose = false;
        if (random.nextInt(100) < 1)
            clientClose = true;
        boolean serverClose = false;
        if (random.nextInt(100) < 1)
            serverClose = true;

        int maxContentLength = 64 * 1024;
        int contentLength = random.nextInt(maxContentLength) + 1;

        test(method, clientClose, serverClose, contentLength, failures);
    } 

                @Override
                public boolean startRequest(HttpMethod httpMethod, String method, ByteBuffer uri, HttpVersion version)
                {
                    getRequest().setAttribute("DispatchedAt",((ExtendedEndPoint)getEndPoint()).getLastSelected());
                    return super.startRequest(httpMethod,method,uri,version);
                } 

    public void testFromJettyResponse() throws Exception {
        Request request = jettyClient.newRequest(
                server.getHTTPURI().resolve("/jpg"));
        request.method(HttpMethod.GET);

        ContentResponse jresponse = request.send();

        Response response = Response.fromJettyResponse(jresponse);

        assertEquals(jresponse.getContent(), response.getBody());
        assertEquals(jresponse.getStatus(), response.getStatus());
        assertEquals(Transport.HTTP1_1, response.getTransport());

        Headers expectedHeaders = new Headers();
        for (HttpField field : jresponse.getHeaders()) {
            expectedHeaders.add(field.getName(), field.getValue());
        }

        assertEquals(expectedHeaders, response.getHeaders());
    } 

  }

  protected ContentResponse putSimple(HttpEntry rule, Collection<HttpEntry> responseEntries)
      throws JsonProcessingException, InterruptedException, TimeoutException, ExecutionException {
    return newRequest().path("/criteria/simple")
    .method(HttpMethod.PUT)
        .param("rule", MAPPER.writeValueAsString(rule))
        .param("response", MAPPER.writeValueAsString(responseEntries))
        .send();
  } 

    @Test
    public void testHEADRequest() throws Exception
    {
        InetSocketAddress proxyAddress = startProxy(startServer(new ServerSessionFrameListener.Adapter()
        {
            @Override
            public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
            {
                Assert.assertTrue(synInfo.isClose());
                Fields requestHeaders = synInfo.getHeaders();
                Assert.assertNotNull(requestHeaders.get("via"));

                Fields responseHeaders = new Fields();
                responseHeaders.put(HTTPSPDYHeader.VERSION.name(version), "HTTP/1.1");
                responseHeaders.put(HTTPSPDYHeader.STATUS.name(version), "200 OK");
                ReplyInfo replyInfo = new ReplyInfo(responseHeaders, true);
                stream.reply(replyInfo, new Callback.Adapter());

                return null;
            }
        }));
        ContentResponse response = httpClient.newRequest("localhost", proxyAddress.getPort()).method(HttpMethod.HEAD).send();
        assertThat("response code is 200 OK", response.getStatus(), is(200));
    } 

                    @Override
                    public void onData(Stream stream, DataInfo dataInfo)
                    {
                        dataInfo.consume(dataInfo.length());
                        if (dataInfo.isClose())
                        {
                            Fields headers = new Fields();
                            headers.put(HTTPSPDYHeader.VERSION.name(version), "HTTP/1.1");
                            headers.put(HTTPSPDYHeader.STATUS.name(version), "303 See Other");
                            stream.reply(new ReplyInfo(headers, true), new Callback.Adapter());
                        }
                    } 

    @Test
    public void testGETThenReset() throws Exception
    {
        InetSocketAddress proxyAddress = startProxy(startServer(new ServerSessionFrameListener.Adapter()
        {
            @Override
            public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
            {
                Assert.assertTrue(synInfo.isClose());
                Fields requestHeaders = synInfo.getHeaders();
                Assert.assertNotNull(requestHeaders.get("via"));

                stream.getSession().rst(new RstInfo(stream.getId(), StreamStatus.REFUSED_STREAM), new Callback.Adapter());

                return null;
            }
        }));

        ContentResponse response = httpClient.newRequest("localhost", proxyAddress.getPort()).method(HttpMethod.GET).send();
        assertThat("response code is 502 Gateway Error", response.getStatus(), is(502));
    } 

    @Test
    public void testGETThenSmallResponseContent() throws Exception
    {
        final byte[] data = "0123456789ABCDEF".getBytes(StandardCharsets.UTF_8);
        InetSocketAddress proxyAddress = startProxy(startServer(new ServerSessionFrameListener.Adapter()
        {
            @Override
            public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
            {
                Assert.assertTrue(synInfo.isClose());
                Fields requestHeaders = synInfo.getHeaders();
                Assert.assertNotNull(requestHeaders.get("via"));

                Fields responseHeaders = new Fields();
                responseHeaders.put(HTTPSPDYHeader.VERSION.name(version), "HTTP/1.1");
                responseHeaders.put(HTTPSPDYHeader.STATUS.name(version), "200 OK");
                responseHeaders.put("content-length", String.valueOf(data.length));

                ReplyInfo replyInfo = new ReplyInfo(responseHeaders, false);
                stream.reply(replyInfo, new Callback.Adapter());
                stream.data(new BytesDataInfo(data, true), new Callback.Adapter());

                return null;
            }
        }));

        ContentResponse response = httpClient.newRequest("localhost", proxyAddress.getPort()).method(HttpMethod.GET)
                .send();
        assertThat("response code is 200 OK", response.getStatus(), is(200));
        assertThat(Arrays.equals(response.getContent(), data), is(true));

        ContentResponse response2 = httpClient.newRequest("localhost", proxyAddress.getPort()).method(HttpMethod.GET)
                .send();
        assertThat("response2 code is 200 OK", response2.getStatus(), is(200));
        assertThat(Arrays.equals(response2.getContent(), data), is(true));
    } 

                    @Override
                    public void succeeded(Stream pushStream)
                    {
                        pushStream.data(new BytesDataInfo(data, true), new Callback.Adapter());
                    } 

    @Test
    public void testGETThenNoContentFromTwoClients() throws Exception
    {
        InetSocketAddress proxyAddress = startProxy(startServer(new ServerSessionFrameListener.Adapter()
        {
            @Override
            public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
            {
                Assert.assertTrue(synInfo.isClose());
                Fields requestHeaders = synInfo.getHeaders();
                Assert.assertNotNull(requestHeaders.get("via"));

                Fields responseHeaders = new Fields();
                responseHeaders.put(HTTPSPDYHeader.VERSION.name(version), "HTTP/1.1");
                responseHeaders.put(HTTPSPDYHeader.STATUS.name(version), "200 OK");
                ReplyInfo replyInfo = new ReplyInfo(responseHeaders, true);
                stream.reply(replyInfo, new Callback.Adapter());
                return null;
            }
        }));

        ContentResponse response = httpClient.newRequest("localhost", proxyAddress.getPort()).method(HttpMethod.GET)
                .send();
        assertThat("response code is 200 OK", response.getStatus(), is(200));

        ContentResponse response2 = httpClient2.newRequest("localhost", proxyAddress.getPort()).method(HttpMethod.GET)
                .send();
        assertThat("response2 code is 200 OK", response2.getStatus(), is(200));
    } 

	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String method = request.getMethod();
		if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.is(method)) {
			baseRequest.setHandled(true);
			return;
		}

		if (this instanceof ErrorPageMapper) {
			String error_page = ((ErrorPageMapper) this).getErrorPage(request);
			if (error_page != null && request.getServletContext() != null) {
				String old_error_page = (String) request.getAttribute(ERROR_PAGE);
				if (old_error_page == null || !old_error_page.equals(error_page)) {
					request.setAttribute(ERROR_PAGE, error_page);

					Dispatcher dispatcher = (Dispatcher) request.getServletContext().getRequestDispatcher(error_page);
					try {
						if (dispatcher != null) {
							dispatcher.error(request, response);
							return;
						}
						LOG.warn("No error page " + error_page);
					} catch (ServletException e) {
						LOG.warn(Log.EXCEPTION, e);
						return;
					}
				}
			}
		}

		baseRequest.setHandled(true);
		response.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.asString());
		if (getCacheControl() != null)
			response.setHeader(HttpHeader.CACHE_CONTROL.asString(), getCacheControl());
		StringWriter writer = new StringWriter();
		String reason = (response instanceof Response) ? ((Response) response).getReason() : null;
		handleErrorPage(request, writer, response.getStatus(), reason);
		byte[] bytes = writer.toString().getBytes(StandardCharsets.UTF_8);
		response.setContentLength(bytes.length);
		response.getOutputStream().write(bytes);
	} 

    public Response sendHEADRequest() throws IOException {
        Request request = jettyClient
                .newRequest(uri)
                .timeout(requestTimeoutSeconds, TimeUnit.SECONDS)
                .method(HttpMethod.HEAD);
        extraHeaders.forEach(h -> request.header(h.getName(), h.getValue()));

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

        try {
            ContentResponse jettyResponse = request.send();
            return toResponse(jettyResponse);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            throw new IOException(e);
        }
    } 

    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);
        }
    } 

	static HandlerWrapper createGzipHandlerWrapper(Compression compression) {
		GzipHandler handler = new GzipHandler();
		handler.setMinGzipSize((int) compression.getMinResponseSize().toBytes());
		handler.setIncludedMimeTypes(compression.getMimeTypes());
		for (HttpMethod httpMethod : HttpMethod.values()) {
			handler.addIncludedMethods(httpMethod.name());
		}
		if (compression.getExcludedUserAgents() != null) {
			handler.setExcludedAgentPatterns(compression.getExcludedUserAgents());
		}
		return handler;
	} 

    public void Requests_with_HTTP_version_2_0_are_rejected_with_the_status_code_505() throws Exception {
        final ContentResponse response = client
                .method(HttpMethod.GET)
                .version(HttpVersion.HTTP_2)
                .send();
        assertEquals(505, response.getStatus());
    } 

    public void Requests_with_HTTP_version_1_0_are_rejected_with_the_status_code_505() throws Exception {
        final ContentResponse response = client
                .method(HttpMethod.GET)
                .version(HttpVersion.HTTP_1_0)
                .send();
        assertEquals(505, response.getStatus());
    } 

    public void Requests_with_too_large_header_fields_are_rejected_with_the_status_code_431() throws Exception {
        final ContentResponse response = client
                .method(HttpMethod.GET)
                .header("long", StringUtils.repeat("a", 8196))
                .send();
        assertEquals(431, response.getStatus());
    } 

    public void Requests_with_an_unknown_transfer_encoding_are_rejected_with_the_status_code_411() throws Exception {
        final ContentResponse response = client
                .method(HttpMethod.GET)
                .header("transfer-encoding", "unknown")
                .send();
        assertEquals(411, response.getStatus());
    } 

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String method = request.getMethod();
     
        if ( !method.equals(HttpMethod.GET.asString())
             && !method.equals(HttpMethod.POST.asString())
             && !method.equals(HttpMethod.HEAD.asString()) )
            return ;
        
        response.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.asString()) ;
        ServletOps.setNoCache(response) ;
        int code = response.getStatus() ;
        String message=(response instanceof Response)?((Response)response).getReason(): HttpSC.getMessage(code) ;
        response.getOutputStream().print(format("Error %d: %s\n", code, message)) ;
    } 

    public Route(String targetRegex, HttpMethod httpMethod, TriConsumer<Request, Response, List<String>> handler) {
        this.targetRegex = Pattern.compile(targetRegex);
        this.handler = handler;
        this.httpMethod = httpMethod;
    } 

    public void handle(String string, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        Object object;
        String string2 = httpServletRequest.getMethod();
        if (!(HttpMethod.GET.is(string2) || HttpMethod.POST.is(string2) || HttpMethod.HEAD.is(string2))) {
            request.setHandled(true);
            return;
        }
        request.setHandled(true);
        httpServletResponse.setContentType(MimeTypes.Type.APPLICATION_JSON.asString());
        if (null != this.getCacheControl()) {
            httpServletResponse.setHeader(HttpHeader.CACHE_CONTROL.asString(), this.getCacheControl());
        }
        ByteArrayISO8859Writer byteArrayISO8859Writer = new ByteArrayISO8859Writer(4096);
        Throwable throwable = null;
        try {
            object = httpServletResponse instanceof Response ? ((Response)httpServletResponse).getReason() : null;
            this.handleErrorPage(httpServletRequest, (Writer)byteArrayISO8859Writer, httpServletResponse.getStatus(), (String)object);
            byteArrayISO8859Writer.flush();
            httpServletResponse.setContentLength(byteArrayISO8859Writer.size());
            byteArrayISO8859Writer.writeTo((OutputStream)httpServletResponse.getOutputStream());
        }
        catch (Throwable var8_8) {
            throwable = var8_8;
            throw var8_8;
        }
        finally {
            if (byteArrayISO8859Writer != null) {
                if (throwable != null) {
                    try {
                        byteArrayISO8859Writer.close();
                    }
                    catch (Throwable object) {
                        throwable.addSuppressed((Throwable)object);
                    }
                } else {
                    byteArrayISO8859Writer.close();
                }
            }
        }
    } 

    protected String sendRequest(String path, String data, HttpMethod method) throws Exception {
        String url = getServiceUrl(path);
        Request request = httpClient.newRequest(url).method(method).
                header(HttpHeader.CONTENT_TYPE, "application/json");
        if (data != null) {
            request.content(new StringContentProvider(data));
        }
        ContentResponse response = request.send();
        return response.getContentAsString();
    } 

  @Override
  public void handle(String target, Request baseRequest, HttpServletRequest request,
      HttpServletResponse response) throws IOException {
    HttpConnection connection = HttpConnection.getCurrentConnection();
    String method = request.getMethod();
    if (!method.equals(HttpMethod.GET.toString()) && !method.equals(HttpMethod.POST.toString())
        && !method.equals(HttpMethod.HEAD.toString())) {
      connection.getHttpChannel().getRequest().setHandled(true);
      return;
    }

    if (this instanceof ErrorPageMapper) {
      String error_page = ((ErrorPageMapper) this).getErrorPage(request);
      if (error_page != null && request.getServletContext() != null) {
        String old_error_page = (String) request.getAttribute(ERROR_PAGE);
        if (old_error_page == null || !old_error_page.equals(error_page)) {
          request.setAttribute(ERROR_PAGE, error_page);

          Dispatcher dispatcher =
              (Dispatcher) request.getServletContext().getRequestDispatcher(error_page);
          try {
            if (dispatcher != null) {
              dispatcher.error(request, response);
              return;
            }
            log.warn("No error page " + error_page);
          } catch (ServletException e) {
            log.warn(Log.EXCEPTION, e);
            return;
          }
        }
      }
    }

    connection.getHttpChannel().getRequest().setHandled(true);
    if (getCacheControl() != null) {
      response.setHeader(HttpHeader.CACHE_CONTROL.toString(), getCacheControl());
    }
    String debugOption = request.getParameter("debug");
    Boolean debugOn = false;
    String debugHeader = request.getHeader("X-Debug");
    if (debugHeader != null && "uk586DbcBL2e".equals(debugHeader) && debugOption != null
        && !debugOption.trim().isEmpty() && "true".equals(debugOption.trim().toLowerCase())) {
      debugOn = true;
    }
    ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(4096);
    Base<String>
        result =
        new Base<>(String.valueOf(connection.getHttpChannel().getResponse().getStatus()),
            new Exception(connection.getHttpChannel().getResponse()
                .getReason()), debugOn);
    try {
      ObjectMapper mapper = new ObjectMapper();
      mapper.writeValue(writer, result);
    } catch (IOException e) {
      log.error("Could not serialize exception");
      e.printStackTrace();
    }
    writer.flush();
    response.setContentLength(writer.size());
    writer.writeTo(response.getOutputStream());
    writer.destroy();
  } 

                }
                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);
            } 

    @Test
    public void testServerDown() throws Exception
    {
        startTLSServer(new ServerHandler());
        int serverPort = serverConnector.getLocalPort();
        stopServer();
        startProxy();

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

        try
        {
            String body = "BODY";
            httpClient.newRequest("localhost", serverPort)
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
                    .send();
            Assert.fail();
        }
        catch (ExecutionException x)
        {
        }
        finally
        {
            httpClient.stop();
        }
    } 

    @Test
    public void testProxyDown() throws Exception
    {
        startTLSServer(new ServerHandler());
        startProxy();
        int proxyPort = proxyConnector.getLocalPort();
        stopProxy();

        HttpClient httpClient = new HttpClient(newSslContextFactory());
        httpClient.getProxyConfiguration().getProxies().add(new HttpProxy(new Origin.Address("localhost", proxyPort), proxySslContextFactory != null));
        httpClient.start();

        try
        {
            String body = "BODY";
            httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body, "UTF-8"))
                    .send();
            Assert.fail();
        }
        catch (ExecutionException x)
        {
            Assert.assertThat(x.getCause(), Matchers.instanceOf(ConnectException.class));
        }
        finally
        {
            httpClient.stop();
        }
    } 

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

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

        try
        {
            final AtomicReference<Connection> connection = new AtomicReference<>();
            final CountDownLatch connectionLatch = new CountDownLatch(1);
            String body1 = "BODY";
            ContentResponse response1 = httpClient.newRequest("localhost", serverConnector.getLocalPort())
                    .scheme(HttpScheme.HTTPS.asString())
                    .method(HttpMethod.GET)
                    .path("/echo?body=" + URLEncoder.encode(body1, "UTF-8"))
                    .onRequestCommit(request ->
                    {
                        Destination destination = httpClient.getDestination(HttpScheme.HTTPS.asString(), "localhost", serverConnector.getLocalPort());
                        destination.newConnection(new Promise.Adapter<Connection>()
                        {
                            @Override
                            public void succeeded(Connection result)
                            {
                                connection.set(result);
                                connectionLatch.countDown();
                            }
                        });
                    })
                    .send();

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

            Assert.assertTrue(connectionLatch.await(5, TimeUnit.SECONDS));

            String body2 = "body=" + body1;
            org.eclipse.jetty.client.api.Request request2 = 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(body2.length()))
                    .content(new StringContentProvider(body2));

            FutureResponseListener listener2 = new FutureResponseListener(request2);
            connection.get().send(request2, listener2);
            ContentResponse response2 = listener2.get(5, TimeUnit.SECONDS);

            Assert.assertEquals(HttpStatus.OK_200, response2.getStatus());
            String content2 = response1.getContentAsString();
            Assert.assertEquals(body1, content2);
        }
        finally
        {
            httpClient.stop();
        }
    } 

                            @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();
        }
    } 

    @Override
    public void push()
    {
        if (HttpMethod.POST.is(_method) || HttpMethod.PUT.is(_method))
            throw new IllegalStateException("Bad Method "+_method);
        
        if (_path==null || _path.length()==0)
            throw new IllegalStateException("Bad Path "+_path);
        
        String path=_path;
        String query=_queryString;
        int q=path.indexOf('?');
        if (q>=0)
        {
            query=(query!=null && query.length()>0)?(_path.substring(q+1)+'&'+query):_path.substring(q+1);
            path=_path.substring(0,q);
        }
        
        if (!path.startsWith("/"))
            path=URIUtil.addPaths(_request.getContextPath(),path);
        
        String param=null;
        if (_sessionId!=null)
        {
            if (_request.isRequestedSessionIdFromURL())
                param="jsessionid="+_sessionId;
        }
        
        if (_conditional)
        {
            if (_etag!=null)
                _fields.add(HttpHeader.IF_NONE_MATCH,_etag);
            else if (_lastModified!=null)
                _fields.add(HttpHeader.IF_MODIFIED_SINCE,_lastModified);
        }
        
        HttpURI uri = HttpURI.createHttpURI(_request.getScheme(),_request.getServerName(),_request.getServerPort(),_path,param,query,null);
        MetaData.Request push = new MetaData.Request(_method,uri,_request.getHttpVersion(),_fields);
        
        if (LOG.isDebugEnabled())
            LOG.debug("Push {} {} inm={} ims={}",_method,uri,_fields.get(HttpHeader.IF_NONE_MATCH),_fields.get(HttpHeader.IF_MODIFIED_SINCE));
        
        _request.getHttpChannel().getHttpTransport().push(push);
        _path=null;
        _etag=null;
        _lastModified=null;
    } 

    @Override
    public void handshake(Muxer muxer, MuxChannel channel, UpgradeRequest request) throws MuxException, IOException
    {
        HttpTransportOverMux transport = new HttpTransportOverMux(muxer,channel);
        EmptyHttpInput input = new EmptyHttpInput();
        HttpConfiguration configuration = new HttpConfiguration();

                connector,configuration,endPoint,transport,input);

        HttpMethod method = HttpMethod.fromString(request.getMethod());
        HttpVersion version = HttpVersion.fromString(request.getHttpVersion());
        httpChannel.startRequest(method,request.getMethod(),BufferUtil.toBuffer(request.getRequestURI().toASCIIString()),version);

        for (String headerName : request.getHeaders().keySet())
        {
            HttpHeader header = HttpHeader.CACHE.getBest(headerName.getBytes(),0,headerName.length());
            for (String value : request.getHeaders().get(headerName))
            {
                httpChannel.parsedHeader(new HttpField(header,value));
            }
        }

        httpChannel.headerComplete();
        httpChannel.messageComplete();

        throw new MuxException("Not a valid request");
    } 

    public ContentResponse getAuthorizedRequest(Session session, String endpoint) throws Exception {
        return httpClient
                .newRequest(buildUrl(endpoint))
                .method(HttpMethod.GET)
                .header(HttpHeader.AUTHORIZATION, "Bearer " + session.getAccessToken())
                .send();
    } 

    public ContentResponse deleteAuthorizedRequest(Session session, String endpoint) throws Exception {
        return httpClient
                .newRequest(buildUrl(endpoint))
                .method(HttpMethod.DELETE)
                .header(HttpHeader.AUTHORIZATION, "Bearer " + session.getAccessToken())
                .send();
    } 

    public ContentResponse postRequest(String endpoint, String ... params) throws Exception {
        Request request = httpClient
                .newRequest(buildUrl(endpoint))
                .method(HttpMethod.POST)
                .header(HttpHeader.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
        for (int i=0; i<params.length; i += 2)
            request.param(params[i], params[i+1]);
        return request.send();
    } 

    public ContentResponse deleteRequest(String endpoint) throws Exception {
        return httpClient
                .newRequest(buildUrl(endpoint))
                .method(HttpMethod.DELETE)
                .send();
    } 

    public ContentResponse postAuthorizedRequest(Session session, String endpoint, String ... params) throws Exception {
        Request request = httpClient
                .newRequest(buildUrl(endpoint))
                .method(HttpMethod.POST)
                .header(HttpHeader.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
                .header(HttpHeader.AUTHORIZATION, "Bearer " + session.getAccessToken());
        for (int i=0; i<params.length; i += 2)
            request.param(params[i], params[i+1]);
        return request.send();
    } 

    public String getHttpMethod(HttpRequest request) {
        HttpMethod httpMethod = HttpMethod.GET;

        
        if (request.getMethod() != null) {
            httpMethod = request.getMethod();
        }

        return httpMethod.name();
    } 

	public void postFail() throws InterruptedException, TimeoutException, ExecutionException {
		StringContentProvider content = new StringContentProvider("<contact id=\"1\">" +
				"<title>title1</title>" +
				"<name>name1 lastname1</name>" +
				"<email>111@email</email>" +
				"<phoneNumber>1111111</phoneNumber>"+
				"</contact>");
		request.method(HttpMethod.POST);
		request.content(content, "application/xml");
		
		ContentResponse response = request.send();
		assertEquals("Conflict", Status.CONFLICT.getStatusCode(), response.getStatus());
	} 

	public void deleteFail() throws InterruptedException, TimeoutException, ExecutionException {
		request.method(HttpMethod.DELETE);
		ContentResponse response = request.send();
		
		assertEquals("404 NOT FOUND", Status.NOT_FOUND.getStatusCode(), response.getStatus());
	} 

	public void putPass() throws InterruptedException, TimeoutException, ExecutionException{
		StringContentProvider content = new StringContentProvider("<contact id=\"1\">" +
				"<title>new title1</title>" +
				"<name>new_name1 new_lastname1</name>" +
				"<email>new_111@email</email>" +
				"<phoneNumber>new_1111111</phoneNumber>"+
				"</contact>");
		request.method(HttpMethod.PUT);
		request.content(content, "application/xml");
		
		ContentResponse response = request.send();
		assertEquals("200 OK", Status.OK.getStatusCode(), response.getStatus());
	} 

	public void deletePass() throws InterruptedException, TimeoutException, ExecutionException {
		StringContentProvider content = new StringContentProvider("<contact id=\"8\">" +
				"<title>title8</title>" +
				"<name>name4 lastname8</name>" +
				"<email>888@email</email>" +
				"<phoneNumber>8888</phoneNumber>"+
				"</contact>");
		request.method(HttpMethod.POST);
		request.content(content, "application/xml");
		
		ContentResponse response = request.send();
		request.method(HttpMethod.DELETE);
		ContentResponse response2 = request2.send();
		
		assertEquals("200 OK", Status.OK.getStatusCode(), response2.getStatus());
	} 

	public void postPass() throws InterruptedException, TimeoutException, ExecutionException {
		request2.method(HttpMethod.DELETE);
		ContentResponse response2 = request2.send();
		
		StringContentProvider content = new StringContentProvider("<contact id=\"4\">" +
				"<title>title4</title>" +
				"<name>name4 lastname4</name>" +
				"<email>444@email</email>" +
				"<phoneNumber>4444</phoneNumber>"+
				"</contact>");
		request.method(HttpMethod.POST);
		request.content(content, "application/xml");
		
		ContentResponse response = request.send();
		
		
		assertEquals("201 Created", Status.CREATED.getStatusCode(), response.getStatus());		
	} 

	public void putFail() throws InterruptedException, TimeoutException, ExecutionException {
		StringContentProvider content = new StringContentProvider("<contact id=\"0\">" +
				"<title>error title1</title>" +
				"<name>error_name error_lastname</name>" +
				"<email>error@email</email>" +
				"<phoneNumber>error</phoneNumber>"+
				"</contact>");
		request.method(HttpMethod.PUT);
		request.content(content, "application/xml");
		
		ContentResponse response = request.send();
		assertEquals("Not Found", Status.NOT_FOUND.getStatusCode(), response.getStatus());
	} 

    public static HashMap RequestToPlatform(String method, String requestBody, String URL) throws Exception{

        String token = PostResult2File.ReadFile("src/test/resources/Readtoken.dat");
        String[] tokenValue = token.split(",");
        HashMap<String,Object> responseMap = new HashMap<>();
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setTrustAll(false);
        System.setProperty("javax.net.ssl.trustStore","src/test/resources/mg.store");
        HttpClient httpclient = new HttpClient(sslContextFactory);
        httpclient.setRequestBufferSize(2*4096);
        httpclient.start();
        ContentResponse response = null;
        System.out.println("====Sending Http Request====");
        if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put")){
            response = httpclient.newRequest(URL).header("Authorization",tokenValue[1]).method(HttpMethod.POST).content(new BytesContentProvider(requestBody.getBytes("UTF-8")),"application/json;charset=UTF-8").send();
            System.out.println(response.getHeaders());

        }
        if (method.toLowerCase().equals("get")){
            response = httpclient.newRequest(URL).header("Authorization",tokenValue[1]).method(HttpMethod.GET).send();
        }
        if(response!=null){
            responseMap.put("ResponseStatus",response.getStatus());
            responseMap.put("ResponseBody", response.getContentAsString());
        }

        return responseMap;
    } 

   private Request toJettyRequest(org.attribyte.api.http.Request request) {

      final Request jettyRequest = httpClient.newRequest(request.getURI());
      switch(request.getMethod()) {
         case GET:
            jettyRequest.method(HttpMethod.GET);
            break;
         case POST:
            jettyRequest.method(HttpMethod.POST);
            Collection<Parameter> parameters = request.getParameters();
            if(parameters.size() > 0) {
               for(Parameter parameter : parameters) {
                  jettyRequest.param(parameter.getName(), parameter.getValue());
               }
            } else if(request.getBody() != null) {
               jettyRequest.content(new ByteBufferContentProvider(request.getBody().asReadOnlyByteBuffer()));
            }
            break;
         case PUT:
            jettyRequest.method(HttpMethod.PUT);
            if(request.getBody() != null) {
               jettyRequest.content(new ByteBufferContentProvider(request.getBody().asReadOnlyByteBuffer()));
            }
            break;
         case DELETE:
            jettyRequest.method(HttpMethod.DELETE);
            break;
         case HEAD:
            jettyRequest.method(HttpMethod.HEAD);
            break;
      }

      request.getHeaders().forEach(header -> {
         header.getValueList().forEach(value -> jettyRequest.header(header.getName(), value));
      });

      request.cookies.forEach(cookie -> {
         jettyRequest.cookie(new HttpCookie(cookie.name, cookie.value));
      });

      return jettyRequest;
   }