Search in sources :

Example 31 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class HTTP2Test method testMaxConcurrentStreams.

@Test
public void testMaxConcurrentStreams() throws Exception {
    int maxStreams = 2;
    start(new ServerSessionListener.Adapter() {

        @Override
        public Map<Integer, Integer> onPreface(Session session) {
            Map<Integer, Integer> settings = new HashMap<>(1);
            settings.put(SettingsFrame.MAX_CONCURRENT_STREAMS, maxStreams);
            return settings;
        }

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields(), 0);
            stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP);
            return null;
        }
    });
    CountDownLatch settingsLatch = new CountDownLatch(1);
    Session session = newClient(new Session.Listener.Adapter() {

        @Override
        public void onSettings(Session session, SettingsFrame frame) {
            settingsLatch.countDown();
        }
    });
    Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS));
    MetaData.Request request1 = newRequest("GET", new HttpFields());
    FuturePromise<Stream> promise1 = new FuturePromise<>();
    CountDownLatch exchangeLatch1 = new CountDownLatch(2);
    session.newStream(new HeadersFrame(request1, null, false), promise1, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                exchangeLatch1.countDown();
        }
    });
    Stream stream1 = promise1.get(5, TimeUnit.SECONDS);
    MetaData.Request request2 = newRequest("GET", new HttpFields());
    FuturePromise<Stream> promise2 = new FuturePromise<>();
    CountDownLatch exchangeLatch2 = new CountDownLatch(2);
    session.newStream(new HeadersFrame(request2, null, false), promise2, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                exchangeLatch2.countDown();
        }
    });
    Stream stream2 = promise2.get(5, TimeUnit.SECONDS);
    // The third stream must not be created.
    MetaData.Request request3 = newRequest("GET", new HttpFields());
    CountDownLatch maxStreamsLatch = new CountDownLatch(1);
    session.newStream(new HeadersFrame(request3, null, false), new Promise.Adapter<Stream>() {

        @Override
        public void failed(Throwable x) {
            if (x instanceof IllegalStateException)
                maxStreamsLatch.countDown();
        }
    }, new Stream.Listener.Adapter());
    Assert.assertTrue(maxStreamsLatch.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(2, session.getStreams().size());
    // End the second stream.
    stream2.data(new DataFrame(stream2.getId(), BufferUtil.EMPTY_BUFFER, true), new Callback() {

        @Override
        public void succeeded() {
            exchangeLatch2.countDown();
        }
    });
    Assert.assertTrue(exchangeLatch2.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(1, session.getStreams().size());
    // Create a fourth stream.
    MetaData.Request request4 = newRequest("GET", new HttpFields());
    CountDownLatch exchangeLatch4 = new CountDownLatch(2);
    session.newStream(new HeadersFrame(request4, null, true), new Promise.Adapter<Stream>() {

        @Override
        public void succeeded(Stream result) {
            exchangeLatch4.countDown();
        }
    }, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (frame.isEndStream())
                exchangeLatch4.countDown();
        }
    });
    Assert.assertTrue(exchangeLatch4.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(1, session.getStreams().size());
    // End the first stream.
    stream1.data(new DataFrame(stream1.getId(), BufferUtil.EMPTY_BUFFER, true), new Callback() {

        @Override
        public void succeeded() {
            exchangeLatch1.countDown();
        }
    });
    Assert.assertTrue(exchangeLatch2.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(0, session.getStreams().size());
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) FuturePromise(org.eclipse.jetty.util.FuturePromise) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) Callback(org.eclipse.jetty.util.Callback) HashMap(java.util.HashMap) Map(java.util.Map) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 32 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class HTTP2Test method testRequestNoContentResponseEmptyContent.

@Test
public void testRequestNoContentResponseEmptyContent() throws Exception {
    start(new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
            stream.headers(new HeadersFrame(stream.getId(), response, null, false), new Callback() {

                @Override
                public void succeeded() {
                    stream.data(new DataFrame(stream.getId(), BufferUtil.EMPTY_BUFFER, true), NOOP);
                }
            });
            return null;
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    final CountDownLatch latch = new CountDownLatch(1);
    session.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            Assert.assertFalse(frame.isEndStream());
            Assert.assertEquals(stream.getId(), frame.getStreamId());
            MetaData.Response response = (MetaData.Response) frame.getMetaData();
            Assert.assertEquals(200, response.getStatus());
        }

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            Assert.assertTrue(frame.isEndStream());
            callback.succeeded();
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) Callback(org.eclipse.jetty.util.Callback) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 33 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class HttpClientTest method testResponseListenerForMultipleEventsIsInvokedOncePerEvent.

@Test
public void testResponseListenerForMultipleEventsIsInvokedOncePerEvent() throws Exception {
    start(new EmptyServerHandler());
    final AtomicInteger counter = new AtomicInteger();
    final CountDownLatch latch = new CountDownLatch(1);
    Response.Listener listener = new Response.Listener() {

        @Override
        public void onBegin(Response response) {
            counter.incrementAndGet();
        }

        @Override
        public boolean onHeader(Response response, HttpField field) {
            // Number of header may vary, so don't count
            return true;
        }

        @Override
        public void onHeaders(Response response) {
            counter.incrementAndGet();
        }

        @Override
        public void onContent(Response response, ByteBuffer content) {
            // Should not be invoked
            counter.incrementAndGet();
        }

        @Override
        public void onContent(Response response, ByteBuffer content, Callback callback) {
            // Should not be invoked
            counter.incrementAndGet();
        }

        @Override
        public void onSuccess(Response response) {
            counter.incrementAndGet();
        }

        @Override
        public void onFailure(Response response, Throwable failure) {
            // Should not be invoked
            counter.incrementAndGet();
        }

        @Override
        public void onComplete(Result result) {
            Assert.assertEquals(200, result.getResponse().getStatus());
            counter.incrementAndGet();
            latch.countDown();
        }
    };
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onResponseBegin(listener).onResponseHeader(listener).onResponseHeaders(listener).onResponseContent(listener).onResponseContentAsync(listener).onResponseSuccess(listener).onResponseFailure(listener).send(listener);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    int expectedEventsTriggeredByOnResponseXXXListeners = 3;
    int expectedEventsTriggeredByCompletionListener = 4;
    int expected = expectedEventsTriggeredByOnResponseXXXListeners + expectedEventsTriggeredByCompletionListener;
    Assert.assertEquals(expected, counter.get());
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpField(org.eclipse.jetty.http.HttpField) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) EndPoint(org.eclipse.jetty.io.EndPoint) Result(org.eclipse.jetty.client.api.Result) Test(org.junit.Test)

Example 34 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class HttpChannel method sendResponse.

protected boolean sendResponse(MetaData.Response info, ByteBuffer content, boolean complete, final Callback callback) {
    boolean committing = _committed.compareAndSet(false, true);
    if (LOG.isDebugEnabled())
        LOG.debug("sendResponse info={} content={} complete={} committing={} callback={}", info, BufferUtil.toDetailString(content), complete, committing, callback);
    if (committing) {
        // We need an info to commit
        if (info == null)
            info = _response.newResponseMetaData();
        commit(info);
        // wrap callback to process 100 responses
        final int status = info.getStatus();
        final Callback committed = (status < 200 && status >= 100) ? new Commit100Callback(callback) : new CommitCallback(callback);
        // committing write
        _transport.send(info, _request.isHead(), content, complete, committed);
    } else if (info == null) {
        // This is a normal write
        _transport.send(null, _request.isHead(), content, complete, callback);
    } else {
        callback.failed(new IllegalStateException("committed"));
    }
    return committing;
}
Also used : Callback(org.eclipse.jetty.util.Callback) EndPoint(org.eclipse.jetty.io.EndPoint) ChannelEndPoint(org.eclipse.jetty.io.ChannelEndPoint)

Example 35 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class ResponseTest method init.

@Before
public void init() throws Exception {
    _server = new Server();
    Scheduler _scheduler = new TimerScheduler();
    HttpConfiguration config = new HttpConfiguration();
    LocalConnector connector = new LocalConnector(_server, null, _scheduler, null, 1, new HttpConnectionFactory(config));
    _server.addConnector(connector);
    _server.setHandler(new DumpHandler());
    _server.start();
    AbstractEndPoint endp = new ByteArrayEndPoint(_scheduler, 5000) {

        @Override
        public InetSocketAddress getLocalAddress() {
            return LOCALADDRESS;
        }
    };
    _channel = new HttpChannel(connector, new HttpConfiguration(), endp, new HttpTransport() {

        private Throwable _channelError;

        @Override
        public void send(MetaData.Response info, boolean head, ByteBuffer content, boolean lastContent, Callback callback) {
            if (_channelError == null)
                callback.succeeded();
            else
                callback.failed(_channelError);
        }

        @Override
        public boolean isPushSupported() {
            return false;
        }

        @Override
        public void push(org.eclipse.jetty.http.MetaData.Request request) {
        }

        @Override
        public void onCompleted() {
        }

        @Override
        public void abort(Throwable failure) {
            _channelError = failure;
        }

        @Override
        public boolean isOptimizedForDirectBuffers() {
            return false;
        }
    });
}
Also used : TimerScheduler(org.eclipse.jetty.util.thread.TimerScheduler) AbstractEndPoint(org.eclipse.jetty.io.AbstractEndPoint) Scheduler(org.eclipse.jetty.util.thread.Scheduler) TimerScheduler(org.eclipse.jetty.util.thread.TimerScheduler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ByteArrayEndPoint(org.eclipse.jetty.io.ByteArrayEndPoint) ByteBuffer(java.nio.ByteBuffer) HttpServletResponse(javax.servlet.http.HttpServletResponse) Callback(org.eclipse.jetty.util.Callback) Before(org.junit.Before)

Aggregations

Callback (org.eclipse.jetty.util.Callback)81 Test (org.junit.Test)71 CountDownLatch (java.util.concurrent.CountDownLatch)68 HttpFields (org.eclipse.jetty.http.HttpFields)52 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)52 Stream (org.eclipse.jetty.http2.api.Stream)51 MetaData (org.eclipse.jetty.http.MetaData)50 Session (org.eclipse.jetty.http2.api.Session)50 DataFrame (org.eclipse.jetty.http2.frames.DataFrame)46 HttpServletResponse (javax.servlet.http.HttpServletResponse)44 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)41 IOException (java.io.IOException)39 FuturePromise (org.eclipse.jetty.util.FuturePromise)39 ByteBuffer (java.nio.ByteBuffer)38 HttpServletRequest (javax.servlet.http.HttpServletRequest)37 ServletException (javax.servlet.ServletException)34 Promise (org.eclipse.jetty.util.Promise)30 ServletOutputStream (javax.servlet.ServletOutputStream)26 HttpServlet (javax.servlet.http.HttpServlet)21 HTTP2Session (org.eclipse.jetty.http2.HTTP2Session)20