Search in sources :

Example 66 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class HttpClientTest method test_ExchangeIsComplete_OnlyWhenBothRequestAndResponseAreComplete.

@Test
public void test_ExchangeIsComplete_OnlyWhenBothRequestAndResponseAreComplete() throws Exception {
    start(new RespondThenConsumeHandler());
    // Prepare a big file to upload
    Path targetTestsDir = testdir.getEmptyPathDir();
    Files.createDirectories(targetTestsDir);
    Path file = Paths.get(targetTestsDir.toString(), "http_client_conversation.big");
    try (OutputStream output = Files.newOutputStream(file, StandardOpenOption.CREATE)) {
        byte[] kb = new byte[1024];
        for (int i = 0; i < 10 * 1024; ++i) output.write(kb);
    }
    final CountDownLatch latch = new CountDownLatch(3);
    final AtomicLong exchangeTime = new AtomicLong();
    final AtomicLong requestTime = new AtomicLong();
    final AtomicLong responseTime = new AtomicLong();
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).file(file).onRequestSuccess(request -> {
        requestTime.set(System.nanoTime());
        latch.countDown();
    }).send(new Response.Listener.Adapter() {

        @Override
        public void onSuccess(Response response) {
            responseTime.set(System.nanoTime());
            latch.countDown();
        }

        @Override
        public void onComplete(Result result) {
            exchangeTime.set(System.nanoTime());
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
    Assert.assertTrue(requestTime.get() <= exchangeTime.get());
    Assert.assertTrue(responseTime.get() <= exchangeTime.get());
    // Give some time to the server to consume the request content
    // This is just to avoid exception traces in the test output
    Thread.sleep(1000);
    Files.delete(file);
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) EndPoint(org.eclipse.jetty.io.EndPoint) TestingDir(org.eclipse.jetty.toolchain.test.TestingDir) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) Request(org.eclipse.jetty.client.api.Request) ByteBuffer(java.nio.ByteBuffer) Assert.assertThat(org.junit.Assert.assertThat) ServerSocket(java.net.ServerSocket) HttpCookie(java.net.HttpCookie) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) URI(java.net.URI) Path(java.nio.file.Path) Response(org.eclipse.jetty.client.api.Response) Callback(org.eclipse.jetty.util.Callback) SocketAddressResolver(org.eclipse.jetty.util.SocketAddressResolver) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow) StandardOpenOption(java.nio.file.StandardOpenOption) IO(org.eclipse.jetty.util.IO) AbstractConnection(org.eclipse.jetty.io.AbstractConnection) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) FuturePromise(org.eclipse.jetty.util.FuturePromise) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) BadMessageException(org.eclipse.jetty.http.BadMessageException) Connection(org.eclipse.jetty.client.api.Connection) Result(org.eclipse.jetty.client.api.Result) Socket(java.net.Socket) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HttpVersion(org.eclipse.jetty.http.HttpVersion) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) AtomicReference(java.util.concurrent.atomic.AtomicReference) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) ArrayList(java.util.ArrayList) HttpClientTransportOverHTTP(org.eclipse.jetty.client.http.HttpClientTransportOverHTTP) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) Assume(org.junit.Assume) NoSuchElementException(java.util.NoSuchElementException) OutputStream(java.io.OutputStream) HttpHeaderValue(org.eclipse.jetty.http.HttpHeaderValue) Iterator(java.util.Iterator) Files(java.nio.file.Files) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) UnknownHostException(java.net.UnknownHostException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) AtomicLong(java.util.concurrent.atomic.AtomicLong) URLEncoder(java.net.URLEncoder) HttpMethod(org.eclipse.jetty.http.HttpMethod) Rule(org.junit.Rule) Paths(java.nio.file.Paths) HttpField(org.eclipse.jetty.http.HttpField) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) Destination(org.eclipse.jetty.client.api.Destination) Assert(org.junit.Assert) Collections(java.util.Collections) InputStream(java.io.InputStream) Exchanger(java.util.concurrent.Exchanger) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) EndPoint(org.eclipse.jetty.io.EndPoint) Result(org.eclipse.jetty.client.api.Result) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.junit.Test)

Example 67 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class HttpClientTest method testCompleteNotInvokedUntilContentConsumed.

@Test
public void testCompleteNotInvokedUntilContentConsumed() 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);
            ServletOutputStream output = response.getOutputStream();
            output.write(new byte[1024]);
        }
    });
    final AtomicReference<Callback> callbackRef = new AtomicReference<>();
    final CountDownLatch contentLatch = new CountDownLatch(1);
    final CountDownLatch completeLatch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).send(new Response.Listener.Adapter() {

        @Override
        public void onContent(Response response, ByteBuffer content, Callback callback) {
            // Do not notify the callback yet.
            callbackRef.set(callback);
            contentLatch.countDown();
        }

        @Override
        public void onComplete(Result result) {
            if (result.isSucceeded())
                completeLatch.countDown();
        }
    });
    Assert.assertTrue(contentLatch.await(5, TimeUnit.SECONDS));
    // Make sure the complete event is not emitted.
    Assert.assertFalse(completeLatch.await(1, TimeUnit.SECONDS));
    // Consume the content.
    callbackRef.get().succeeded();
    // Now the complete event is emitted.
    Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
}
Also used : FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Callback(org.eclipse.jetty.util.Callback) Test(org.junit.Test)

Example 68 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class HttpCookieTest method test_CookieIsStored.

@Test
public void test_CookieIsStored() throws Exception {
    final String name = "foo";
    final String value = "bar";
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.addCookie(new Cookie(name, value));
            baseRequest.setHandled(true);
        }
    });
    String host = "localhost";
    int port = connector.getLocalPort();
    String path = "/path";
    String uri = scheme + "://" + host + ":" + port + path;
    Response response = client.GET(uri);
    Assert.assertEquals(200, response.getStatus());
    List<HttpCookie> cookies = client.getCookieStore().get(URI.create(uri));
    Assert.assertNotNull(cookies);
    Assert.assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    Assert.assertEquals(name, cookie.getName());
    Assert.assertEquals(value, cookie.getValue());
}
Also used : HttpCookie(java.net.HttpCookie) Cookie(javax.servlet.http.Cookie) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpServletResponse(javax.servlet.http.HttpServletResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpCookie(java.net.HttpCookie) Test(org.junit.Test)

Example 69 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class HttpResponseAbortTest method testAbortOnContent.

@Test
public void testAbortOnContent() throws Exception {
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            try {
                baseRequest.setHandled(true);
                OutputStream output = response.getOutputStream();
                output.write(1);
                output.flush();
                output.write(2);
                output.flush();
            } catch (IOException ignored) {
            // The client may have already closed, and we'll get an exception here, but it's expected
            }
        }
    });
    final CountDownLatch latch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onResponseContent(new Response.ContentListener() {

        @Override
        public void onContent(Response response, ByteBuffer content) {
            response.abort(new Exception());
        }
    }).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            Assert.assertTrue(result.isFailed());
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : OutputStream(java.io.OutputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.eclipse.jetty.client.api.Response) Test(org.junit.Test)

Example 70 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class HttpClientAuthenticationTest method test_Authentication_ThrowsException.

@Test
public void test_Authentication_ThrowsException() throws Exception {
    startBasic(new EmptyServerHandler());
    // Request without Authentication would cause a 401,
    // but the client will throw an exception trying to
    // send the credentials to the server.
    final String cause = "thrown_explicitly_by_test";
    client.getAuthenticationStore().addAuthentication(new Authentication() {

        @Override
        public boolean matches(String type, URI uri, String realm) {
            return true;
        }

        @Override
        public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes context) {
            throw new RuntimeException(cause);
        }
    });
    final CountDownLatch latch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure").timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            Assert.assertTrue(result.isFailed());
            Assert.assertEquals(cause, result.getFailure().getMessage());
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) Attributes(org.eclipse.jetty.util.Attributes) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) Result(org.eclipse.jetty.client.api.Result) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Authentication(org.eclipse.jetty.client.api.Authentication) DigestAuthentication(org.eclipse.jetty.client.util.DigestAuthentication) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) Test(org.junit.Test)

Aggregations

Response (org.eclipse.jetty.client.api.Response)113 Test (org.junit.Test)90 HttpServletResponse (javax.servlet.http.HttpServletResponse)89 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)84 IOException (java.io.IOException)77 HttpServletRequest (javax.servlet.http.HttpServletRequest)70 ServletException (javax.servlet.ServletException)68 CountDownLatch (java.util.concurrent.CountDownLatch)54 Result (org.eclipse.jetty.client.api.Result)51 InputStream (java.io.InputStream)36 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)36 ByteBuffer (java.nio.ByteBuffer)34 ServletOutputStream (javax.servlet.ServletOutputStream)34 Request (org.eclipse.jetty.client.api.Request)31 InterruptedIOException (java.io.InterruptedIOException)29 HttpServlet (javax.servlet.http.HttpServlet)29 InputStreamResponseListener (org.eclipse.jetty.client.util.InputStreamResponseListener)29 Request (org.eclipse.jetty.server.Request)26 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)23 Callback (org.eclipse.jetty.util.Callback)22