Search in sources :

Example 26 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.

the class ProxyTest method startProxy.

private void startProxy(HttpServlet proxyServlet, Map<String, String> initParams) throws Exception {
    QueuedThreadPool proxyPool = new QueuedThreadPool();
    proxyPool.setName("proxy");
    proxy = new Server(proxyPool);
    HttpConfiguration configuration = new HttpConfiguration();
    configuration.setSendDateHeader(false);
    configuration.setSendServerVersion(false);
    String value = initParams.get("outputBufferSize");
    if (value != null)
        configuration.setOutputBufferSize(Integer.valueOf(value));
    proxyConnector = new ServerConnector(proxy, new HTTP2ServerConnectionFactory(configuration));
    proxy.addConnector(proxyConnector);
    ServletContextHandler proxyContext = new ServletContextHandler(proxy, "/", true, false);
    ServletHolder proxyServletHolder = new ServletHolder(proxyServlet);
    proxyServletHolder.setInitParameters(initParams);
    proxyContext.addServlet(proxyServletHolder, "/*");
    proxy.start();
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Server(org.eclipse.jetty.server.Server) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 27 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder 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 28 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.

the class TestMemcachedSessions method testMemcached.

@Test
public void testMemcached() throws Exception {
    String contextPath = "/";
    Server server = new Server(0);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setResourceBase(System.getProperty("java.io.tmpdir"));
    server.setHandler(context);
    NullSessionCache dsc = new NullSessionCache(context.getSessionHandler());
    dsc.setSessionDataStore(new CachingSessionDataStore(new MemcachedSessionDataMap("localhost", "11211"), new NullSessionDataStore()));
    context.getSessionHandler().setSessionCache(dsc);
    // Add a test servlet
    ServletHolder h = new ServletHolder();
    h.setServlet(new TestServlet());
    context.addServlet(h, "/");
    try {
        server.start();
        int port = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        HttpClient client = new HttpClient();
        client.start();
        try {
            int value = 42;
            ContentResponse response = client.GET("http://localhost:" + port + contextPath + "?action=set&value=" + value);
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            String sessionCookie = response.getHeaders().get("Set-Cookie");
            assertTrue(sessionCookie != null);
            // Mangle the cookie, replacing Path with $Path, etc.
            sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
            String resp = response.getContentAsString();
            assertEquals(resp.trim(), String.valueOf(value));
            // Be sure the session value is still there
            Request request = client.newRequest("http://localhost:" + port + contextPath + "?action=get");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            resp = response.getContentAsString();
            assertEquals(String.valueOf(value), resp.trim());
            //Delete the session
            request = client.newRequest("http://localhost:" + port + contextPath + "?action=del");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            //Check that the session is gone
            request = client.newRequest("http://localhost:" + port + contextPath + "?action=get");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            resp = response.getContentAsString();
            assertEquals("No session", resp.trim());
        } finally {
            client.stop();
        }
    } finally {
        server.stop();
    }
}
Also used : Server(org.eclipse.jetty.server.Server) CachingSessionDataStore(org.eclipse.jetty.server.session.CachingSessionDataStore) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpClient(org.eclipse.jetty.client.HttpClient) NullSessionDataStore(org.eclipse.jetty.server.session.NullSessionDataStore) NetworkConnector(org.eclipse.jetty.server.NetworkConnector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Test(org.junit.Test)

Example 29 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.

the class EventSourceServletTest method testBasicFunctionality.

@Test
public void testBasicFunctionality() throws Exception {
    final AtomicReference<EventSource.Emitter> emitterRef = new AtomicReference<EventSource.Emitter>();
    final CountDownLatch emitterLatch = new CountDownLatch(1);
    final CountDownLatch closeLatch = new CountDownLatch(1);
    class S extends EventSourceServlet {

        @Override
        protected EventSource newEventSource(HttpServletRequest request) {
            return new EventSource() {

                public void onOpen(Emitter emitter) throws IOException {
                    emitterRef.set(emitter);
                    emitterLatch.countDown();
                }

                public void onClose() {
                    closeLatch.countDown();
                }
            };
        }
    }
    String servletPath = "/eventsource";
    ServletHolder servletHolder = new ServletHolder(new S());
    int heartBeatPeriod = 2;
    servletHolder.setInitParameter("heartBeatPeriod", String.valueOf(heartBeatPeriod));
    context.addServlet(servletHolder, servletPath);
    Socket socket = new Socket("localhost", connector.getLocalPort());
    writeHTTPRequest(socket, servletPath);
    BufferedReader reader = readAndDiscardHTTPResponse(socket);
    Assert.assertTrue(emitterLatch.await(1, TimeUnit.SECONDS));
    EventSource.Emitter emitter = emitterRef.get();
    Assert.assertNotNull(emitter);
    String data = "foo";
    emitter.data(data);
    String line = reader.readLine();
    String received = "";
    while (line != null) {
        received += line;
        if (line.length() == 0)
            break;
        line = reader.readLine();
    }
    Assert.assertEquals("data: " + data, received);
    socket.close();
    Assert.assertTrue(closeLatch.await(heartBeatPeriod * 3, TimeUnit.SECONDS));
}
Also used : ServletHolder(org.eclipse.jetty.servlet.ServletHolder) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) HttpServletRequest(javax.servlet.http.HttpServletRequest) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) Test(org.junit.Test)

Example 30 with ServletHolder

use of org.eclipse.jetty.servlet.ServletHolder in project jetty.project by eclipse.

the class EventSourceServletTest method testEncoding.

@Test
public void testEncoding() throws Exception {
    // The EURO symbol
    final String data = "€";
    class S extends EventSourceServlet {

        @Override
        protected EventSource newEventSource(HttpServletRequest request) {
            return new EventSource() {

                public void onOpen(Emitter emitter) throws IOException {
                    emitter.data(data);
                }

                public void onClose() {
                }
            };
        }
    }
    String servletPath = "/eventsource";
    context.addServlet(new ServletHolder(new S()), servletPath);
    Socket socket = new Socket("localhost", connector.getLocalPort());
    writeHTTPRequest(socket, servletPath);
    BufferedReader reader = readAndDiscardHTTPResponse(socket);
    String line = reader.readLine();
    String received = "";
    while (line != null) {
        received += line;
        if (line.length() == 0)
            break;
        line = reader.readLine();
    }
    Assert.assertEquals("data: " + data, received);
    socket.close();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

ServletHolder (org.eclipse.jetty.servlet.ServletHolder)473 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)255 Server (org.eclipse.jetty.server.Server)177 Test (org.junit.Test)81 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)74 ServerConnector (org.eclipse.jetty.server.ServerConnector)67 HttpServletRequest (javax.servlet.http.HttpServletRequest)47 IOException (java.io.IOException)44 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)36 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)33 File (java.io.File)32 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)32 ServletContainer (org.glassfish.jersey.servlet.ServletContainer)30 DefaultServlet (org.eclipse.jetty.servlet.DefaultServlet)27 HttpServletResponse (javax.servlet.http.HttpServletResponse)26 HttpClient (org.eclipse.jetty.client.HttpClient)24 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)24 CountDownLatch (java.util.concurrent.CountDownLatch)23 ServletException (javax.servlet.ServletException)23 ServletHandler (org.eclipse.jetty.servlet.ServletHandler)23