Search in sources :

Example 81 with ServletException

use of javax.servlet.ServletException in project jetty.project by eclipse.

the class PushCacheFilterTest method testPOSTRequestIsNotPushed.

@Test
public void testPOSTRequestIsNotPushed() throws Exception {
    final String primaryResource = "/primary.html";
    final String secondaryResource = "/secondary.png";
    final byte[] secondaryData = "SECONDARY".getBytes("UTF-8");
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String requestURI = req.getRequestURI();
            ServletOutputStream output = resp.getOutputStream();
            if (requestURI.endsWith(primaryResource))
                output.print("<html><head></head><body>PRIMARY</body></html>");
            else if (requestURI.endsWith(secondaryResource))
                output.write(secondaryData);
        }
    });
    final Session session = newClient(new Session.Listener.Adapter());
    // Request for the primary and secondary resource to build the cache.
    final String referrerURI = newURI(primaryResource);
    HttpFields primaryFields = new HttpFields();
    MetaData.Request primaryRequest = newRequest("GET", primaryResource, primaryFields);
    final CountDownLatch warmupLatch = new CountDownLatch(1);
    session.newStream(new HeadersFrame(primaryRequest, null, true), new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            callback.succeeded();
            if (frame.isEndStream()) {
                // Request for the secondary resource.
                HttpFields secondaryFields = new HttpFields();
                secondaryFields.put(HttpHeader.REFERER, referrerURI);
                MetaData.Request secondaryRequest = newRequest("GET", secondaryResource, secondaryFields);
                session.newStream(new HeadersFrame(secondaryRequest, null, true), new Promise.Adapter<>(), new Stream.Listener.Adapter() {

                    @Override
                    public void onData(Stream stream, DataFrame frame, Callback callback) {
                        callback.succeeded();
                        warmupLatch.countDown();
                    }
                });
            }
        }
    });
    Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS));
    // Request again the primary resource with POST, we should not get the secondary resource pushed.
    primaryRequest = newRequest("POST", primaryResource, primaryFields);
    final CountDownLatch primaryResponseLatch = new CountDownLatch(1);
    final CountDownLatch pushLatch = new CountDownLatch(1);
    session.newStream(new HeadersFrame(primaryRequest, null, true), new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public Stream.Listener onPush(Stream stream, PushPromiseFrame frame) {
            return new Adapter() {

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

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            callback.succeeded();
            if (frame.isEndStream())
                primaryResponseLatch.countDown();
        }
    });
    Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS));
    Assert.assertFalse(pushLatch.await(1, TimeUnit.SECONDS));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) PushPromiseFrame(org.eclipse.jetty.http2.frames.PushPromiseFrame) Promise(org.eclipse.jetty.util.Promise) Callback(org.eclipse.jetty.util.Callback) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 82 with ServletException

use of javax.servlet.ServletException in project jetty.project by eclipse.

the class AsyncServletTest method testStartAsyncThenServerIdleTimeout.

private void testStartAsyncThenServerIdleTimeout(long sessionTimeout, long streamTimeout) throws Exception {
    prepareServer(new HTTP2ServerConnectionFactory(new HttpConfiguration()) {

        @Override
        protected ServerSessionListener newSessionListener(Connector connector, EndPoint endPoint) {
            return new HTTPServerSessionListener(connector, endPoint) {

                @Override
                public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
                    stream.setIdleTimeout(streamTimeout);
                    return super.onNewStream(stream, frame);
                }
            };
        }
    });
    connector.setIdleTimeout(sessionTimeout);
    ServletContextHandler context = new ServletContextHandler(server, "/");
    long timeout = Math.min(sessionTimeout, streamTimeout);
    CountDownLatch errorLatch = new CountDownLatch(1);
    context.addServlet(new ServletHolder(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = (AsyncContext) request.getAttribute(AsyncContext.class.getName());
            if (asyncContext == null) {
                AsyncContext context = request.startAsync();
                context.setTimeout(2 * timeout);
                request.setAttribute(AsyncContext.class.getName(), context);
                context.addListener(new AsyncListener() {

                    @Override
                    public void onComplete(AsyncEvent event) throws IOException {
                    }

                    @Override
                    public void onTimeout(AsyncEvent event) throws IOException {
                        event.getAsyncContext().complete();
                    }

                    @Override
                    public void onError(AsyncEvent event) throws IOException {
                        errorLatch.countDown();
                    }

                    @Override
                    public void onStartAsync(AsyncEvent event) throws IOException {
                    }
                });
            } else {
                throw new ServletException();
            }
        }
    }), servletPath + "/*");
    server.start();
    prepareClient();
    client.start();
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    CountDownLatch clientLatch = new CountDownLatch(1);
    session.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            MetaData.Response response = (MetaData.Response) frame.getMetaData();
            if (response.getStatus() == HttpStatus.OK_200 && frame.isEndStream())
                clientLatch.countDown();
        }
    });
    // When the server idle times out, but the request has been dispatched
    // then the server must ignore the idle timeout as per Servlet semantic.
    Assert.assertFalse(errorLatch.await(2 * timeout, TimeUnit.MILLISECONDS));
    Assert.assertTrue(clientLatch.await(2 * timeout, TimeUnit.MILLISECONDS));
}
Also used : Connector(org.eclipse.jetty.server.Connector) AsyncListener(javax.servlet.AsyncListener) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) AsyncContext(javax.servlet.AsyncContext) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) EndPoint(org.eclipse.jetty.io.EndPoint) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Stream(org.eclipse.jetty.http2.api.Stream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) HTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncEvent(javax.servlet.AsyncEvent) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) AsyncListener(javax.servlet.AsyncListener) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session)

Example 83 with ServletException

use of javax.servlet.ServletException in project jetty.project by eclipse.

the class AsyncServletTest method testStartAsyncThenDispatch.

@Test
public void testStartAsyncThenDispatch() throws Exception {
    byte[] content = new byte[1024];
    new Random().nextBytes(content);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = (AsyncContext) request.getAttribute(AsyncContext.class.getName());
            if (asyncContext == null) {
                AsyncContext context = request.startAsync();
                context.setTimeout(0);
                request.setAttribute(AsyncContext.class.getName(), context);
                context.start(() -> {
                    sleep(1000);
                    context.dispatch();
                });
            } else {
                response.getOutputStream().write(content);
            }
        }
    });
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    CountDownLatch latch = new CountDownLatch(1);
    session.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            try {
                buffer.write(BufferUtil.toArray(frame.getData()));
                callback.succeeded();
                if (frame.isEndStream())
                    latch.countDown();
            } catch (IOException x) {
                callback.failed(x);
            }
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    Assert.assertArrayEquals(content, buffer.toByteArray());
}
Also used : AsyncListener(javax.servlet.AsyncListener) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) Callback(org.eclipse.jetty.util.Callback) Random(java.util.Random) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Stream(org.eclipse.jetty.http2.api.Stream) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 84 with ServletException

use of javax.servlet.ServletException in project jetty.project by eclipse.

the class StreamResetTest method testServerExceptionConsumesQueuedData.

@Test
public void testServerExceptionConsumesQueuedData() throws Exception {
    try (StacklessLogging suppressor = new StacklessLogging(HttpChannel.class)) {
        start(new HttpServlet() {

            @Override
            protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                try {
                    // Wait to let the data sent by the client to be queued.
                    Thread.sleep(1000);
                    throw new IllegalStateException("explictly_thrown_by_test");
                } catch (InterruptedException e) {
                    throw new InterruptedIOException();
                }
            }
        });
        Session client = newClient(new Session.Listener.Adapter());
        Log.getLogger(HttpChannel.class).info("Expecting java.lang.IllegalStateException: explictly_thrown_by_test");
        MetaData.Request request = newRequest("GET", new HttpFields());
        HeadersFrame frame = new HeadersFrame(request, null, false);
        FuturePromise<Stream> promise = new FuturePromise<>();
        client.newStream(frame, promise, new Stream.Listener.Adapter());
        Stream stream = promise.get(5, TimeUnit.SECONDS);
        ByteBuffer data = ByteBuffer.allocate(FlowControlStrategy.DEFAULT_WINDOW_SIZE);
        CountDownLatch dataLatch = new CountDownLatch(1);
        stream.data(new DataFrame(stream.getId(), data, false), new Callback() {

            @Override
            public void succeeded() {
                dataLatch.countDown();
            }
        });
        // The server does not read the data, so the flow control window should be zero.
        Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS));
        Assert.assertEquals(0, ((ISession) client).updateSendWindow(0));
        // Wait for the server process the exception, and
        // for the client to process the window updates.
        Thread.sleep(2000);
        Assert.assertThat(((ISession) client).updateSendWindow(0), Matchers.greaterThan(0));
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) WriteListener(javax.servlet.WriteListener) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HttpChannel(org.eclipse.jetty.server.HttpChannel) Stream(org.eclipse.jetty.http2.api.Stream) ServletOutputStream(javax.servlet.ServletOutputStream) IStream(org.eclipse.jetty.http2.IStream) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Callback(org.eclipse.jetty.util.Callback) FutureCallback(org.eclipse.jetty.util.FutureCallback) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Example 85 with ServletException

use of javax.servlet.ServletException in project jetty.project by eclipse.

the class StreamResetTest method testBlockingWriteAfterStreamReceivingReset.

@Test
public void testBlockingWriteAfterStreamReceivingReset() throws Exception {
    final CountDownLatch resetLatch = new CountDownLatch(1);
    final CountDownLatch dataLatch = new CountDownLatch(1);
    start(new HttpServlet() {

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Charset charset = StandardCharsets.UTF_8;
            byte[] data = "AFTER RESET".getBytes(charset);
            response.setStatus(200);
            response.setContentType("text/plain;charset=" + charset.name());
            response.setContentLength(data.length * 10);
            response.flushBuffer();
            try {
                // Wait for the reset to happen.
                Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS));
            } catch (InterruptedException x) {
                throw new InterruptedIOException();
            }
            try {
                // been reset, it should throw an exception.
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(500);
                    response.getOutputStream().write(data);
                    response.flushBuffer();
                }
            } catch (InterruptedException x) {
            } catch (IOException x) {
                dataLatch.countDown();
            }
        }
    });
    Session client = newClient(new Session.Listener.Adapter());
    MetaData.Request request = newRequest("GET", new HttpFields());
    HeadersFrame frame = new HeadersFrame(request, null, true);
    client.newStream(frame, new FuturePromise<>(), new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP);
            resetLatch.countDown();
        }
    });
    Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS));
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) WriteListener(javax.servlet.WriteListener) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) Charset(java.nio.charset.Charset) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) ServletOutputStream(javax.servlet.ServletOutputStream) IStream(org.eclipse.jetty.http2.IStream) ResetFrame(org.eclipse.jetty.http2.frames.ResetFrame) Session(org.eclipse.jetty.http2.api.Session) ISession(org.eclipse.jetty.http2.ISession) Test(org.junit.Test)

Aggregations

ServletException (javax.servlet.ServletException)2492 IOException (java.io.IOException)1623 HttpServletRequest (javax.servlet.http.HttpServletRequest)698 HttpServletResponse (javax.servlet.http.HttpServletResponse)658 Test (org.junit.Test)444 PrintWriter (java.io.PrintWriter)238 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)226 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)188 CountDownLatch (java.util.concurrent.CountDownLatch)169 HttpServlet (javax.servlet.http.HttpServlet)151 Request (org.eclipse.jetty.server.Request)148 HashMap (java.util.HashMap)147 InputStream (java.io.InputStream)146 ArrayList (java.util.ArrayList)133 HttpSession (javax.servlet.http.HttpSession)127 SQLException (java.sql.SQLException)124 OutputStream (java.io.OutputStream)116 ServletOutputStream (javax.servlet.ServletOutputStream)113 Properties (java.util.Properties)108 List (java.util.List)107