Search in sources :

Example 21 with StacklessLogging

use of org.eclipse.jetty.util.log.StacklessLogging in project jetty.project by eclipse.

the class IdleSessionTest method testSessionIdle.

/**
     * @throws Exception
     */
@Test
public void testSessionIdle() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int inactivePeriod = 20;
    int scavengePeriod = 3;
    int evictionSec = 5;
    DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory();
    cacheFactory.setEvictionPolicy(evictionSec);
    SessionDataStoreFactory storeFactory = new TestSessionDataStoreFactory();
    _server1 = new TestServer(0, inactivePeriod, scavengePeriod, cacheFactory, storeFactory);
    ServletHolder holder = new ServletHolder(_servlet);
    ServletContextHandler contextHandler = _server1.addContext(contextPath);
    contextHandler.addServlet(holder, servletMapping);
    _server1.start();
    int port1 = _server1.getPort();
    try (StacklessLogging stackless = new StacklessLogging(Log.getLogger("org.eclipse.jetty.server.session"))) {
        HttpClient client = new HttpClient();
        client.start();
        String url = "http://localhost:" + port1 + contextPath + servletMapping;
        //make a request to set up a session on the server
        ContentResponse response = client.GET(url + "?action=init");
        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=");
        //and wait until the session should be idled out
        pause(evictionSec * 3);
        //check that the session has been idled
        String id = TestServer.extractSessionId(sessionCookie);
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //make another request to de-idle the session
        Request request = client.newRequest(url + "?action=test");
        request.getHeaders().add("Cookie", sessionCookie);
        ContentResponse response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        //check session de-idled
        assertTrue(contextHandler.getSessionHandler().getSessionCache().contains(id));
        //wait again for the session to be idled
        pause(evictionSec * 3);
        //check that it is
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //While idle, take some action to ensure that a deidle won't work, like
        //deleting the sessions in the store
        ((TestSessionDataStore) contextHandler.getSessionHandler().getSessionCache().getSessionDataStore())._map.clear();
        //make a request
        request = client.newRequest(url + "?action=testfail");
        request.getHeaders().add("Cookie", sessionCookie);
        response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        //Test trying to de-idle an expired session (ie before the scavenger can get to it)
        //make a request to set up a session on the server
        response = client.GET(url + "?action=init");
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        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=");
        id = TestServer.extractSessionId(sessionCookie);
        //and wait until the session should be idled out
        pause(evictionSec * 3);
        //stop the scavenger
        if (_server1.getHouseKeeper() != null)
            _server1.getHouseKeeper().stop();
        //check that the session is idle
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //wait until the session should be expired
        pause(inactivePeriod + (3 * scavengePeriod));
        //make another request to de-idle the session
        request = client.newRequest(url + "?action=testfail");
        request.getHeaders().add("Cookie", sessionCookie);
        response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertFalse(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
    } finally {
        _server1.stop();
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpClient(org.eclipse.jetty.client.HttpClient) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Test(org.junit.Test)

Example 22 with StacklessLogging

use of org.eclipse.jetty.util.log.StacklessLogging 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 23 with StacklessLogging

use of org.eclipse.jetty.util.log.StacklessLogging in project jetty.project by eclipse.

the class ThreadMonitorTest method monitorTest.

@Ignore
@Test
public void monitorTest() throws Exception {
    try (StacklessLogging stackless = new StacklessLogging(ThreadMonitor.class)) {
        final AtomicInteger countLogs = new AtomicInteger(0);
        final AtomicInteger countSpin = new AtomicInteger(0);
        ThreadMonitor monitor = new ThreadMonitor(1000, 50, 1, 1) {

            @Override
            protected void logThreadInfo(boolean logAll) {
                if (logAll)
                    countLogs.incrementAndGet();
                else
                    countSpin.incrementAndGet();
                super.logThreadInfo(logAll);
            }
        };
        monitor.setDumpable(new Dumpable() {

            public void dump(Appendable out, String indent) throws IOException {
                out.append(dump());
            }

            public String dump() {
                return "Dump Spinning";
            }
        });
        monitor.logCpuUsage(2000, 0);
        monitor.start();
        Random rnd = new Random();
        for (long cnt = 0; cnt < 100; cnt++) {
            long value = rnd.nextLong() % 50 + 50;
            Sleeper sleeper = new Sleeper(value);
            Thread runner = new Thread(sleeper);
            runner.setDaemon(true);
            runner.start();
        }
        Spinner spinner = new Spinner();
        Thread runner = new Thread(spinner);
        runner.start();
        Thread.sleep(DURATION);
        spinner.setDone();
        monitor.stop();
        assertTrue(countLogs.get() >= 1);
        assertTrue(countSpin.get() >= 2);
    }
}
Also used : Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) IOException(java.io.IOException) Dumpable(org.eclipse.jetty.util.component.Dumpable) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 24 with StacklessLogging

use of org.eclipse.jetty.util.log.StacklessLogging in project jetty.project by eclipse.

the class ConnectorTimeoutTest method testBlockingTimeoutRead.

@Test(timeout = 60000)
// TODO make more stable
@Ignore
public void testBlockingTimeoutRead() throws Exception {
    _httpConfiguration.setBlockingTimeout(750L);
    configureServer(new EchoHandler());
    Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
    client.setSoTimeout(10000);
    InputStream is = client.getInputStream();
    Assert.assertFalse(client.isClosed());
    OutputStream os = client.getOutputStream();
    os.write(("GET / HTTP/1.1\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "Transfer-Encoding: chunked\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "\r\n" + "5\r\n" + "LMNOP\r\n").getBytes("utf-8"));
    os.flush();
    long start = System.currentTimeMillis();
    try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class)) {
        Thread.sleep(300);
        os.write("1".getBytes("utf-8"));
        os.flush();
        Thread.sleep(300);
        os.write("0".getBytes("utf-8"));
        os.flush();
        Thread.sleep(300);
        os.write("\r".getBytes("utf-8"));
        os.flush();
        Thread.sleep(300);
        os.write("\n".getBytes("utf-8"));
        os.flush();
        Thread.sleep(300);
        os.write("0123456789ABCDEF\r\n".getBytes("utf-8"));
        os.write("0\r\n".getBytes("utf-8"));
        os.write("\r\n".getBytes("utf-8"));
        os.flush();
    } catch (Exception e) {
    }
    long duration = System.currentTimeMillis() - start;
    Assert.assertThat(duration, Matchers.greaterThan(500L));
    try {
        // read the response
        String response = IO.toString(is);
        Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 500 "));
        Assert.assertThat(response, Matchers.containsString("InterruptedIOException"));
    } catch (SSLException e) {
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) SSLException(javax.net.ssl.SSLException) Socket(java.net.Socket) ServletException(javax.servlet.ServletException) SocketException(java.net.SocketException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 25 with StacklessLogging

use of org.eclipse.jetty.util.log.StacklessLogging in project jetty.project by eclipse.

the class HttpConnectionTest method testBadURIencoding.

@Test
public void testBadURIencoding() throws Exception {
    Log.getLogger(HttpParser.class).info("badMessage: bad encoding expected ...");
    String response;
    try (StacklessLogging stackless = new StacklessLogging(HttpParser.class)) {
        response = connector.getResponse("GET /bad/encoding%1 HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n");
        checkContains(response, 0, "HTTP/1.1 400");
    }
}
Also used : HttpParser(org.eclipse.jetty.http.HttpParser) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Test(org.junit.Test)

Aggregations

StacklessLogging (org.eclipse.jetty.util.log.StacklessLogging)143 Test (org.junit.Test)134 CloseInfo (org.eclipse.jetty.websocket.common.CloseInfo)55 WebSocketFrame (org.eclipse.jetty.websocket.common.WebSocketFrame)51 ArrayList (java.util.ArrayList)46 Fuzzer (org.eclipse.jetty.websocket.common.test.Fuzzer)45 TextFrame (org.eclipse.jetty.websocket.common.frames.TextFrame)35 ByteBuffer (java.nio.ByteBuffer)29 IOException (java.io.IOException)26 HttpServletRequest (javax.servlet.http.HttpServletRequest)24 HttpServletResponse (javax.servlet.http.HttpServletResponse)22 ContinuationFrame (org.eclipse.jetty.websocket.common.frames.ContinuationFrame)21 ServletException (javax.servlet.ServletException)20 CountDownLatch (java.util.concurrent.CountDownLatch)17 PingFrame (org.eclipse.jetty.websocket.common.frames.PingFrame)17 Matchers.containsString (org.hamcrest.Matchers.containsString)17 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)14 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)13 OutputStream (java.io.OutputStream)12 Socket (java.net.Socket)12