Merge branch 'jetty-9.3.x'

This commit is contained in:
Joakim Erdfelt 2016-03-16 10:29:29 -07:00
commit 3624339ec6
49 changed files with 1426 additions and 1233 deletions

File diff suppressed because it is too large Load Diff

View File

@ -63,25 +63,41 @@ public class BasicAuthentication extends AbstractAuthentication
@Override
public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes context)
{
String value = "Basic " + B64Code.encode(user + ":" + password, StandardCharsets.ISO_8859_1);
return new BasicResult(headerInfo.getHeader(), value);
return new BasicResult(getURI(), headerInfo.getHeader(), user, password);
}
private class BasicResult implements Result
/**
* Basic authentication result.
* <p>
* Application may utilize this class directly via
* {@link AuthenticationStore#addAuthenticationResult(Result)}
* to perform preemptive authentication, that is immediately
* sending the authorization header based on the fact that the
* URI is known to require authentication and that username
* and password are known a priori.
*/
public static class BasicResult implements Result
{
private final URI uri;
private final HttpHeader header;
private final String value;
public BasicResult(HttpHeader header, String value)
public BasicResult(URI uri, String user, String password)
{
this(uri, HttpHeader.AUTHORIZATION, user, password);
}
public BasicResult(URI uri, HttpHeader header, String user, String password)
{
this.uri = uri;
this.header = header;
this.value = value;
this.value = "Basic " + B64Code.encode(user + ":" + password, StandardCharsets.ISO_8859_1);
}
@Override
public URI getURI()
{
return BasicAuthentication.this.getURI();
return uri;
}
@Override

View File

@ -366,4 +366,33 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void test_PreemptedAuthentication() throws Exception
{
startBasic(new EmptyServerHandler());
AuthenticationStore authenticationStore = client.getAuthenticationStore();
URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
authenticationStore.addAuthenticationResult(new BasicAuthentication.BasicResult(uri, "basic", "basic"));
AtomicInteger requests = new AtomicInteger();
client.getRequestListeners().add(new Request.Listener.Adapter()
{
@Override
public void onSuccess(Request request)
{
requests.incrementAndGet();
}
});
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/secure")
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(1, requests.get());
}
}

View File

@ -43,7 +43,7 @@ import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;
@ -378,9 +378,7 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
@Test
public void test_BigRequestContent_ResponseWithConnectionCloseHeader_RemovesConnection() throws Exception
{
StdErrLog logger = StdErrLog.getLogger(org.eclipse.jetty.server.HttpConnection.class);
logger.setHideStacks(true);
try
try (StacklessLogging stackless = new StacklessLogging(HttpConnection.class))
{
start(new AbstractHandler()
{
@ -431,10 +429,6 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
server.stop();
}
finally
{
logger.setHideStacks(false);
}
}
@Slow

View File

@ -58,14 +58,17 @@ public class HttpChannelOverFCGI extends HttpChannel
protected void header(HttpField field)
{
if (FCGI.Headers.REQUEST_METHOD.equalsIgnoreCase(field.getName()))
method = field.getValue();
else if (FCGI.Headers.DOCUMENT_URI.equalsIgnoreCase(field.getName()))
path = field.getValue();
else if (FCGI.Headers.QUERY_STRING.equalsIgnoreCase(field.getName()))
query = field.getValue();
else if (FCGI.Headers.SERVER_PROTOCOL.equalsIgnoreCase(field.getName()))
version = field.getValue();
String name = field.getName();
String value = field.getValue();
getRequest().setAttribute(name, value);
if (FCGI.Headers.REQUEST_METHOD.equalsIgnoreCase(name))
method = value;
else if (FCGI.Headers.DOCUMENT_URI.equalsIgnoreCase(name))
path = value;
else if (FCGI.Headers.QUERY_STRING.equalsIgnoreCase(name))
query = value;
else if (FCGI.Headers.SERVER_PROTOCOL.equalsIgnoreCase(name))
version = value;
else
processField(field);
}
@ -107,10 +110,11 @@ public class HttpChannelOverFCGI extends HttpChannel
httpName.append(part.substring(1).toLowerCase(Locale.ENGLISH));
}
String headerName = httpName.toString();
String value = field.getValue();
if (HttpHeader.HOST.is(headerName))
return new HostPortHttpField(field.getValue());
return new HostPortHttpField(value);
else
return new HttpField(httpName.toString(), field.getValue());
return new HttpField(headerName, value);
}
return null;
}

View File

@ -71,6 +71,7 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent
public static final String SCRIPT_ROOT_INIT_PARAM = "scriptRoot";
public static final String SCRIPT_PATTERN_INIT_PARAM = "scriptPattern";
public static final String ORIGINAL_URI_ATTRIBUTE_INIT_PARAM = "originalURIAttribute";
public static final String ORIGINAL_QUERY_ATTRIBUTE_INIT_PARAM = "originalQueryAttribute";
public static final String FASTCGI_HTTPS_INIT_PARAM = "fastCGI.HTTPS";
private static final String REMOTE_ADDR_ATTRIBUTE = FastCGIProxyServlet.class.getName() + ".remoteAddr";
@ -80,9 +81,11 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent
private static final String SERVER_PORT_ATTRIBUTE = FastCGIProxyServlet.class.getName() + ".serverPort";
private static final String SCHEME_ATTRIBUTE = FastCGIProxyServlet.class.getName() + ".scheme";
private static final String REQUEST_URI_ATTRIBUTE = FastCGIProxyServlet.class.getName() + ".requestURI";
private static final String REQUEST_QUERY_ATTRIBUTE = FastCGIProxyServlet.class.getName() + ".requestQuery";
private Pattern scriptPattern;
private String originalURIAttribute;
private String originalQueryAttribute;
private boolean fcgiHTTPS;
@Override
@ -96,6 +99,7 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent
scriptPattern = Pattern.compile(value);
originalURIAttribute = getInitParameter(ORIGINAL_URI_ATTRIBUTE_INIT_PARAM);
originalQueryAttribute = getInitParameter(ORIGINAL_QUERY_ATTRIBUTE_INIT_PARAM);
fcgiHTTPS = Boolean.parseBoolean(getInitParameter(FASTCGI_HTTPS_INIT_PARAM));
}
@ -122,14 +126,21 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent
// Has the original URI been rewritten ?
String originalURI = null;
String originalQuery = null;
if (originalURIAttribute != null)
originalURI = (String)request.getAttribute(originalURIAttribute);
if (originalURI != null && originalQueryAttribute != null)
{
originalQuery = (String)request.getAttribute(originalQueryAttribute);
if (originalQuery != null)
originalURI += "?" + originalQuery;
}
if (originalURI == null)
{
// If we are forwarded or included, retain the original request URI.
String originalPath = (String)request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
String originalQuery = (String)request.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING);
originalQuery = (String)request.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING);
if (originalPath == null)
{
originalPath = (String)request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
@ -145,6 +156,8 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent
if (originalURI != null)
proxyRequest.attribute(REQUEST_URI_ATTRIBUTE, originalURI);
if (originalQuery != null)
proxyRequest.attribute(REQUEST_QUERY_ATTRIBUTE, originalQuery);
// If the Host header is missing, add it.
if (!proxyRequest.getHeaders().containsKey(HttpHeader.HOST.asString()))
@ -200,6 +213,10 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent
}
fastCGIHeaders.put(FCGI.Headers.REQUEST_URI, requestURI);
String requestQuery = (String)proxyRequest.getAttributes().get(REQUEST_QUERY_ATTRIBUTE);
if (requestQuery != null)
fastCGIHeaders.put(FCGI.Headers.QUERY_STRING, requestQuery);
String scriptName = rawPath;
Matcher matcher = scriptPattern.matcher(rawPath);
if (matcher.matches())

View File

@ -50,6 +50,7 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.Assert;
import org.junit.Test;
@ -603,7 +604,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
}
});
try
try (StacklessLogging stackless = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class))
{
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)

View File

@ -31,13 +31,17 @@ import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.fcgi.FCGI;
import org.eclipse.jetty.fcgi.server.ServerFCGIConnectionFactory;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
@ -57,6 +61,7 @@ public class FastCGIProxyServletTest
private Server server;
private ServerConnector httpConnector;
private ServerConnector fcgiConnector;
private ServletContextHandler context;
private HttpClient client;
public FastCGIProxyServletTest(boolean sendStatus200)
@ -76,7 +81,7 @@ public class FastCGIProxyServletTest
server.addConnector(fcgiConnector);
final String contextPath = "/";
ServletContextHandler context = new ServletContextHandler(server, contextPath);
context = new ServletContextHandler(server, contextPath);
final String servletPath = "/script";
FastCGIProxyServlet fcgiServlet = new FastCGIProxyServlet()
@ -138,11 +143,11 @@ public class FastCGIProxyServletTest
prepare(new HttpServlet()
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Assert.assertTrue(req.getRequestURI().endsWith(path));
resp.setContentLength(data.length);
resp.getOutputStream().write(data);
Assert.assertTrue(request.getRequestURI().endsWith(path));
response.setContentLength(data.length);
response.getOutputStream().write(data);
}
});
@ -169,4 +174,48 @@ public class FastCGIProxyServletTest
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
}
@Test
public void testURIRewrite() throws Exception
{
String originalPath = "/original/index.php";
String originalQuery = "foo=bar";
String remotePath = "/remote/index.php";
prepare(new HttpServlet()
{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Assert.assertThat((String)request.getAttribute(FCGI.Headers.REQUEST_URI), Matchers.startsWith(originalPath));
Assert.assertEquals(originalQuery, request.getAttribute(FCGI.Headers.QUERY_STRING));
Assert.assertThat(request.getRequestURI(), Matchers.endsWith(remotePath));
}
});
context.stop();
String pathAttribute = "_path_attribute";
String queryAttribute = "_query_attribute";
ServletHolder fcgi = context.getServletHandler().getServlet("fcgi");
fcgi.setInitParameter(FastCGIProxyServlet.ORIGINAL_URI_ATTRIBUTE_INIT_PARAM, pathAttribute);
fcgi.setInitParameter(FastCGIProxyServlet.ORIGINAL_QUERY_ATTRIBUTE_INIT_PARAM, queryAttribute);
context.insertHandler(new HandlerWrapper()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
if (target.startsWith("/remote/"))
{
request.setAttribute(pathAttribute, originalPath);
request.setAttribute(queryAttribute, originalQuery);
}
super.handle(target, baseRequest, request, response);
}
});
context.start();
ContentResponse response = client.newRequest("localhost", httpConnector.getLocalPort())
.path(remotePath)
.send();
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
}
}

View File

@ -65,7 +65,7 @@ import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.Assert;
import org.junit.Test;
@ -370,9 +370,7 @@ public class HTTP2ServerTest extends AbstractServerTest
@Test
public void testNonISOHeader() throws Exception
{
StdErrLog logger = StdErrLog.getLogger(HttpChannel.class);
logger.setHideStacks(true);
try
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
startServer(new HttpServlet()
{
@ -403,10 +401,6 @@ public class HTTP2ServerTest extends AbstractServerTest
Assert.assertTrue(closed);
}
}
finally
{
logger.setHideStacks(false);
}
}
@Test

View File

@ -25,8 +25,7 @@ import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.Test;
@ -40,61 +39,62 @@ public class ThreadMonitorTest
@Test
public void monitorTest() throws Exception
{
((StdErrLog)Log.getLogger(ThreadMonitor.class.getName())).setHideStacks(true);
((StdErrLog)Log.getLogger(ThreadMonitor.class.getName())).setSource(false);
final AtomicInteger countLogs=new AtomicInteger(0);
final AtomicInteger countSpin=new AtomicInteger(0);
ThreadMonitor monitor = new ThreadMonitor(1000,50,1,1)
try(StacklessLogging stackless=new StacklessLogging(ThreadMonitor.class))
{
@Override
protected void logThreadInfo(boolean logAll)
final AtomicInteger countLogs=new AtomicInteger(0);
final AtomicInteger countSpin=new AtomicInteger(0);
ThreadMonitor monitor = new ThreadMonitor(1000,50,1,1)
{
if (logAll)
countLogs.incrementAndGet();
else
countSpin.incrementAndGet();
super.logThreadInfo(logAll);
}
};
monitor.setDumpable(new Dumpable()
{
public void dump(Appendable out, String indent) throws IOException
@Override
protected void logThreadInfo(boolean logAll)
{
if (logAll)
countLogs.incrementAndGet();
else
countSpin.incrementAndGet();
super.logThreadInfo(logAll);
}
};
monitor.setDumpable(new Dumpable()
{
out.append(dump());
}
public String dump()
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++)
{
return "Dump Spinning";
long value = rnd.nextLong() % 50 + 50;
Sleeper sleeper = new Sleeper(value);
Thread runner = new Thread(sleeper);
runner.setDaemon(true);
runner.start();
}
});
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);
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);
}
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);
}

View File

@ -77,7 +77,7 @@ import org.eclipse.jetty.util.Utf8StringBuilder;
import org.eclipse.jetty.util.ajax.JSON;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
@ -94,6 +94,7 @@ public class AsyncMiddleManServletTest
private ServerConnector proxyConnector;
private Server server;
private ServerConnector serverConnector;
private StacklessLogging stackless;
private void startServer(HttpServlet servlet) throws Exception
{
@ -136,8 +137,8 @@ public class AsyncMiddleManServletTest
proxyContext.addServlet(proxyServletHolder, "/*");
proxy.start();
((StdErrLog)proxyServlet._log).setHideStacks(true);
stackless=new StacklessLogging(proxyServlet._log);
}
private void startClient() throws Exception
@ -156,6 +157,7 @@ public class AsyncMiddleManServletTest
client.stop();
proxy.stop();
server.stop();
stackless.close();
}
@Test

View File

@ -54,8 +54,7 @@ import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.toolchain.test.http.SimpleHttpParser;
import org.eclipse.jetty.toolchain.test.http.SimpleHttpResponse;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
@ -304,12 +303,15 @@ public class ProxyServletFailureTest
prepareServer(new EchoHttpServlet());
long idleTimeout = 1000;
serverConnector.setIdleTimeout(idleTimeout);
try(StacklessLogging stackless = new StacklessLogging(ServletHandler.class))
{
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.content(new BytesContentProvider(content))
.send();
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.content(new BytesContentProvider(content))
.send();
Assert.assertEquals(500, response.getStatus());
Assert.assertEquals(500, response.getStatus());
}
}
@Test(expected = TimeoutException.class)
@ -391,8 +393,7 @@ public class ProxyServletFailureTest
@Test
public void testServerException() throws Exception
{
((StdErrLog)Log.getLogger(ServletHandler.class)).setHideStacks(true);
try
try (StacklessLogging stackless = new StacklessLogging(ServletHandler.class))
{
prepareProxy();
prepareServer(new HttpServlet()
@ -410,9 +411,5 @@ public class ProxyServletFailureTest
Assert.assertEquals(500, response.getStatus());
}
finally
{
((StdErrLog)Log.getLogger(ServletHandler.class)).setHideStacks(false);
}
}
}

View File

@ -136,7 +136,7 @@ import org.eclipse.jetty.util.thread.Scheduler;
@ManagedObject("Abstract implementation of the Connector Interface")
public abstract class AbstractConnector extends ContainerLifeCycle implements Connector, Dumpable
{
protected final Logger LOG = Log.getLogger(getClass());
protected final Logger LOG = Log.getLogger(AbstractConnector.class);
// Order is important on server side, so we use a LinkedHashMap
private final Map<String, ConnectionFactory> _factories = new LinkedHashMap<>();
private final Server _server;

View File

@ -871,8 +871,8 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
ClassLoader old_classloader = null;
ClassLoader old_webapploader = null;
Thread current_thread = null;
exitScope(null);
Context old_context = __context.get();
enterScope(null,"doStop");
__context.set(_scontext);
try
{
@ -895,13 +895,27 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
_errorHandler.stop();
for (EventListener l : _programmaticListeners)
{
removeEventListener(l);
if (l instanceof ContextScopeListener)
{
try
{
((ContextScopeListener)l).exitScope(_scontext,null);
}
catch(Throwable e)
{
LOG.warn(e);
}
}
}
_programmaticListeners.clear();
}
finally
{
LOG.info("Stopped {}", this);
__context.set(old_context);
exitScope(null);
LOG.info("Stopped {}", this);
// reset the classloader
if ((old_classloader == null || (old_classloader != old_webapploader)) && current_thread != null)
current_thread.setContextClassLoader(old_classloader);

View File

@ -42,8 +42,7 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.toolchain.test.http.SimpleHttpParser;
import org.eclipse.jetty.toolchain.test.http.SimpleHttpResponse;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@ -59,6 +58,8 @@ public abstract class AbstractHttpTest
protected static ServerConnector connector;
protected String httpVersion;
protected SimpleHttpParser httpParser;
StacklessLogging stackless;
public AbstractHttpTest(String httpVersion)
{
@ -74,19 +75,19 @@ public abstract class AbstractHttpTest
server.addConnector(connector);
httpParser = new SimpleHttpParser();
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
stackless=new StacklessLogging(HttpChannel.class);
}
@After
public void tearDown() throws Exception
{
server.stop();
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
stackless.close();
}
protected SimpleHttpResponse executeRequest() throws URISyntaxException, IOException
{
try(Socket socket = new Socket("localhost", connector.getLocalPort());)
try(Socket socket = new Socket("localhost", connector.getLocalPort()))
{
socket.setSoTimeout((int)connector.getIdleTimeout());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
@ -98,14 +99,15 @@ public abstract class AbstractHttpTest
writer.flush();
SimpleHttpResponse response = httpParser.readResponse(reader);
if ("HTTP/1.1".equals(httpVersion)
&& response.getHeaders().get("content-length") == null
&& response.getHeaders().get("transfer-encoding") == null
&& !__noBodyCodes.contains(response.getCode()))
if ("HTTP/1.1".equals(httpVersion)
&& response.getHeaders().get("content-length") == null
&& response.getHeaders().get("transfer-encoding") == null
&& !__noBodyCodes.contains(response.getCode()))
assertThat("If HTTP/1.1 response doesn't contain transfer-encoding or content-length headers, " +
"it should contain connection:close", response.getHeaders().get("connection"), is("close"));
return response;
}
}
}
protected void assertResponseBody(SimpleHttpResponse response, String expectedResponseBody)

View File

@ -43,8 +43,7 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.AdvancedRunner;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
@ -451,9 +450,8 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
os.flush();
long start = System.currentTimeMillis();
try
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
Thread.sleep(300);
os.write("1".getBytes("utf-8"));
os.flush();
@ -475,10 +473,6 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
catch(Exception e)
{
}
finally
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
}
long duration=System.currentTimeMillis() - start;
Assert.assertThat(duration,Matchers.greaterThan(500L));
@ -564,10 +558,8 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
line=is.readLine();
long start=System.currentTimeMillis();
try
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class,AbstractConnection.class))
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
((StdErrLog)Log.getLogger(AbstractConnection.class)).setHideStacks(true);
for (int i=0;i<(128*1024);i++)
{
if (i%1028==0)
@ -582,11 +574,6 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
}
catch(Throwable e)
{}
finally
{
((StdErrLog)Log.getLogger(AbstractConnection.class)).setHideStacks(false);
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
}
long end=System.currentTimeMillis();
long duration = end-start;
Assert.assertThat(duration,Matchers.lessThan(20L*128L));

View File

@ -24,6 +24,10 @@
*/
package org.eclipse.jetty.server;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
@ -46,17 +50,13 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class HttpConnectionTest
{
private Server server;
@ -349,11 +349,14 @@ public class HttpConnectionTest
Log.getLogger(HttpParser.class).info("badMessage: bad encoding expected ...");
String response;
response=connector.getResponses("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");
try(StacklessLogging stackless = new StacklessLogging(HttpParser.class))
{
response=connector.getResponses("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");
}
}
@Test
@ -633,19 +636,14 @@ public class HttpConnectionTest
"abcdefghij\r\n";
Logger logger = Log.getLogger(HttpChannel.class);
try
try (StacklessLogging stackless = new StacklessLogging(logger))
{
logger.info("EXPECTING: java.lang.IllegalStateException...");
((StdErrLog)logger).setHideStacks(true);
String response = connector.getResponses(requests);
offset = checkContains(response,offset,"HTTP/1.1 500");
offset = checkContains(response,offset,"Connection: close");
checkNotContained(response,offset,"HTTP/1.1 200");
}
finally
{
((StdErrLog)logger).setHideStacks(false);
}
}
@Test
@ -756,11 +754,9 @@ public class HttpConnectionTest
server.start();
Logger logger = Log.getLogger(HttpChannel.class);
try
try (StacklessLogging stackless = new StacklessLogging(logger))
{
logger.info("Expect IOException: Response header too large...");
((StdErrLog)logger).setHideStacks(true);
response = connector.getResponses("GET / HTTP/1.1\r\n"+
"Host: localhost\r\n" +
"\r\n"
@ -775,19 +771,14 @@ public class HttpConnectionTest
System.err.println(response);
throw e;
}
finally
{
((StdErrLog)logger).setHideStacks(false);
}
}
@Test
public void testAsterisk() throws Exception
{
String response = null;
try
try (StacklessLogging stackless = new StacklessLogging(HttpParser.LOG))
{
((StdErrLog)HttpParser.LOG).setHideStacks(true);
int offset=0;
response=connector.getResponses("OPTIONS * HTTP/1.1\r\n"+
@ -834,10 +825,6 @@ public class HttpConnectionTest
System.err.println(response);
throw e;
}
finally
{
((StdErrLog)HttpParser.LOG).setHideStacks(false);
}
}
@Test

View File

@ -57,7 +57,7 @@ import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.AbstractLogger;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
@ -185,10 +185,10 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
{
configureServer(new HelloWorldHandler());
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort()))
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
StacklessLogging stackless = new StacklessLogging(HttpConnection.class))
{
client.setSoTimeout(10000);
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
((AbstractLogger) Log.getLogger(HttpConnection.class)).info("expect request is too large, then ISE extra data ...");
OutputStream os = client.getOutputStream();
@ -203,10 +203,6 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 413 "));
}
finally
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
}
}
/*
@ -217,9 +213,9 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
{
configureServer(new HelloWorldHandler());
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort()))
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
StacklessLogging stackless = new StacklessLogging(HttpConnection.class))
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
((AbstractLogger)Log.getLogger(HttpConnection.class)).info("expect URI is too large, then ISE extra data ...");
OutputStream os = client.getOutputStream();
@ -239,10 +235,6 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 414 "));
}
finally
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
}
}
@Test
@ -263,9 +255,8 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
OutputStream os = client.getOutputStream();
try
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
Log.getLogger(HttpChannel.class).info("Expecting ServletException: TEST handler exception...");
os.write(request.toString().getBytes());
os.flush();
@ -307,10 +298,6 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
String response = readResponse(client);
assertThat(response,Matchers.containsString(" 500 "));
}
finally
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
}
}
@Test
@ -371,10 +358,10 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
configureServer(new HelloWorldHandler());
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort()))
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
StacklessLogging stackless = new StacklessLogging(HttpConnection.class))
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
((AbstractLogger)Log.getLogger(HttpConnection.class)).info("expect header is too large, then ISE extra data ...");
Log.getLogger(HttpConnection.class).info("expect header is too large, then ISE extra data ...");
OutputStream os = client.getOutputStream();
byte[] buffer = new byte[64 * 1024];
@ -405,10 +392,6 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 413 "));
}
finally
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
}
}
/*
@ -1212,10 +1195,9 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
CommittedErrorHandler handler = new CommittedErrorHandler();
configureServer(handler);
Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
try
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
((AbstractLogger)Log.getLogger(HttpChannel.class)).info("Expecting exception after commit then could not send 500....");
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
@ -1243,13 +1225,6 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
assertTrue(!handler._endp.isOpen());
}
finally
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
if (!client.isClosed())
client.close();
}
}
public static class CommittedErrorHandler extends AbstractHandler

View File

@ -35,9 +35,11 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.toolchain.test.AdvancedRunner;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@ -535,21 +537,24 @@ public class PartialRFC2616Test
@Test
public void test14_23() throws Exception
{
int offset=0;
String response = connector.getResponses("GET /R1 HTTP/1.0\n" + "Connection: close\n" + "\n");
offset=checkContains(response,offset,"HTTP/1.1 200","200")+1;
try (StacklessLogging stackless = new StacklessLogging(HttpParser.class))
{
int offset=0;
String response = connector.getResponses("GET /R1 HTTP/1.0\n" + "Connection: close\n" + "\n");
offset=checkContains(response,offset,"HTTP/1.1 200","200")+1;
offset=0;
response=connector.getResponses("GET /R1 HTTP/1.1\n"+"Connection: close\n"+"\n");
offset=checkContains(response,offset,"HTTP/1.1 400","400")+1;
offset=0;
response=connector.getResponses("GET /R1 HTTP/1.1\n"+"Connection: close\n"+"\n");
offset=checkContains(response,offset,"HTTP/1.1 400","400")+1;
offset=0;
response=connector.getResponses("GET /R1 HTTP/1.1\n"+"Host: localhost\n"+"Connection: close\n"+"\n");
offset=checkContains(response,offset,"HTTP/1.1 200","200")+1;
offset=0;
response=connector.getResponses("GET /R1 HTTP/1.1\n"+"Host: localhost\n"+"Connection: close\n"+"\n");
offset=checkContains(response,offset,"HTTP/1.1 200","200")+1;
offset=0;
response=connector.getResponses("GET /R1 HTTP/1.1\n"+"Host:\n"+"Connection: close\n"+"\n");
offset=checkContains(response,offset,"HTTP/1.1 400","400")+1;
offset=0;
response=connector.getResponses("GET /R1 HTTP/1.1\n"+"Host:\n"+"Connection: close\n"+"\n");
offset=checkContains(response,offset,"HTTP/1.1 400","400")+1;
}
}
@Test

View File

@ -18,7 +18,9 @@
package org.eclipse.jetty.server;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
@ -137,12 +139,15 @@ public class ProxyConnectionTest
@Test
public void testBadPort() throws Exception
{
String response=_connector.getResponses("PROXY TCP 1.2.3.4 5.6.7.8 9999999999999 222\r\n"+
"GET /path HTTP/1.1\n"+
"Host: server:80\n"+
"Connection: close\n"+
"\n");
try(StacklessLogging stackless = new StacklessLogging(ProxyConnectionFactory.class))
{
String response=_connector.getResponses("PROXY TCP 1.2.3.4 5.6.7.8 9999999999999 222\r\n"+
"GET /path HTTP/1.1\n"+
"Host: server:80\n"+
"Connection: close\n"+
"\n");
Assert.assertThat(response,Matchers.equalTo(""));
}
}
@Test

View File

@ -61,7 +61,7 @@ import org.eclipse.jetty.util.MultiPartInputStreamParser;
import org.eclipse.jetty.util.Utf8Appendable;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
@ -332,9 +332,12 @@ public class RequestTest
"\r\n"+
multipart;
String responses=_connector.getResponses(request);
//System.err.println(responses);
assertTrue(responses.startsWith("HTTP/1.1 500"));
try(StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
String responses=_connector.getResponses(request);
//System.err.println(responses);
assertTrue(responses.startsWith("HTTP/1.1 500"));
}
}
@ -1286,111 +1289,101 @@ public class RequestTest
@Test
public void testHashDOSKeys() throws Exception
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
LOG.info("Expecting maxFormKeys limit and Closing HttpParser exceptions...");
_server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize",-1);
_server.setAttribute("org.eclipse.jetty.server.Request.maxFormKeys",1000);
StringBuilder buf = new StringBuilder(4000000);
buf.append("a=b");
// The evil keys file is not distributed - as it is dangerous
File evil_keys = new File("/tmp/keys_mapping_to_zero_2m");
if (evil_keys.exists())
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
LOG.info("Using real evil keys!");
try (BufferedReader in = new BufferedReader(new FileReader(evil_keys)))
LOG.info("Expecting maxFormKeys limit and Closing HttpParser exceptions...");
_server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize",-1);
_server.setAttribute("org.eclipse.jetty.server.Request.maxFormKeys",1000);
StringBuilder buf = new StringBuilder(4000000);
buf.append("a=b");
// The evil keys file is not distributed - as it is dangerous
File evil_keys = new File("/tmp/keys_mapping_to_zero_2m");
if (evil_keys.exists())
{
String key=null;
while((key=in.readLine())!=null)
buf.append("&").append(key).append("=").append("x");
LOG.info("Using real evil keys!");
try (BufferedReader in = new BufferedReader(new FileReader(evil_keys)))
{
String key=null;
while((key=in.readLine())!=null)
buf.append("&").append(key).append("=").append("x");
}
}
}
else
{
// we will just create a lot of keys and make sure the limit is applied
for (int i=0;i<2000;i++)
buf.append("&").append("K").append(i).append("=").append("x");
}
buf.append("&c=d");
_handler._checker = new RequestTester()
{
@Override
public boolean check(HttpServletRequest request,HttpServletResponse response)
else
{
return "b".equals(request.getParameter("a")) && request.getParameter("c")==null;
// we will just create a lot of keys and make sure the limit is applied
for (int i=0;i<2000;i++)
buf.append("&").append("K").append(i).append("=").append("x");
}
};
buf.append("&c=d");
String request="POST / HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: "+MimeTypes.Type.FORM_ENCODED.asString()+"\r\n"+
"Content-Length: "+buf.length()+"\r\n"+
"Connection: close\r\n"+
"\r\n"+
buf;
try
{
_handler._checker = new RequestTester()
{
@Override
public boolean check(HttpServletRequest request,HttpServletResponse response)
{
return "b".equals(request.getParameter("a")) && request.getParameter("c")==null;
}
};
String request="POST / HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: "+MimeTypes.Type.FORM_ENCODED.asString()+"\r\n"+
"Content-Length: "+buf.length()+"\r\n"+
"Connection: close\r\n"+
"\r\n"+
buf;
long start=System.currentTimeMillis();
String response = _connector.getResponses(request);
assertThat(response,Matchers.containsString("IllegalStateException"));
long now=System.currentTimeMillis();
assertTrue((now-start)<5000);
}
finally
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
}
}
@Test
public void testHashDOSSize() throws Exception
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
LOG.info("Expecting maxFormSize limit and too much data exceptions...");
_server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize",3396);
_server.setAttribute("org.eclipse.jetty.server.Request.maxFormKeys",1000);
StringBuilder buf = new StringBuilder(4000000);
buf.append("a=b");
// we will just create a lot of keys and make sure the limit is applied
for (int i=0;i<500;i++)
buf.append("&").append("K").append(i).append("=").append("x");
buf.append("&c=d");
_handler._checker = new RequestTester()
{
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
@Override
public boolean check(HttpServletRequest request,HttpServletResponse response)
LOG.info("Expecting maxFormSize limit and too much data exceptions...");
_server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize",3396);
_server.setAttribute("org.eclipse.jetty.server.Request.maxFormKeys",1000);
StringBuilder buf = new StringBuilder(4000000);
buf.append("a=b");
// we will just create a lot of keys and make sure the limit is applied
for (int i=0;i<500;i++)
buf.append("&").append("K").append(i).append("=").append("x");
buf.append("&c=d");
_handler._checker = new RequestTester()
{
return "b".equals(request.getParameter("a")) && request.getParameter("c")==null;
}
};
@Override
public boolean check(HttpServletRequest request,HttpServletResponse response)
{
return "b".equals(request.getParameter("a")) && request.getParameter("c")==null;
}
};
String request="POST / HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: "+MimeTypes.Type.FORM_ENCODED.asString()+"\r\n"+
"Content-Length: "+buf.length()+"\r\n"+
"Connection: close\r\n"+
"\r\n"+
buf;
String request="POST / HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: "+MimeTypes.Type.FORM_ENCODED.asString()+"\r\n"+
"Content-Length: "+buf.length()+"\r\n"+
"Connection: close\r\n"+
"\r\n"+
buf;
try
{
long start=System.currentTimeMillis();
String response = _connector.getResponses(request);
assertTrue(response.contains("IllegalStateException"));
long now=System.currentTimeMillis();
assertTrue((now-start)<5000);
}
finally
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
}
}
@Test(expected = UnsupportedEncodingException.class)

View File

@ -50,6 +50,7 @@ import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.toolchain.test.OS;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.Test;
@ -242,21 +243,21 @@ public class ServerConnectorTest
public void testExceptionWhileAccepting() throws Exception
{
Server server = new Server();
AtomicLong spins = new AtomicLong();
ServerConnector connector = new ServerConnector(server)
try (StacklessLogging stackless = new StacklessLogging(AbstractConnector.class))
{
@Override
public void accept(int acceptorID) throws IOException
AtomicLong spins = new AtomicLong();
ServerConnector connector = new ServerConnector(server)
{
spins.incrementAndGet();
throw new IOException("explicitly_thrown_by_test");
}
};
server.addConnector(connector);
server.start();
@Override
public void accept(int acceptorID) throws IOException
{
spins.incrementAndGet();
throw new IOException("explicitly_thrown_by_test");
}
};
server.addConnector(connector);
server.start();
try
{
Thread.sleep(1000);
assertThat(spins.get(), Matchers.lessThan(5L));
}

View File

@ -18,6 +18,7 @@
package org.eclipse.jetty.server;
import java.io.Closeable;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
@ -71,24 +72,26 @@ public class ShutdownMonitorTest
{
ShutdownMonitor monitor = ShutdownMonitor.getInstance();
monitor.setPort(0);
TestableServer server = new TestableServer();
server.start();
try(CloseableServer server = new CloseableServer())
{
server.start();
//shouldn't be registered for shutdown on jvm
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
//shouldn't be registered for shutdown on jvm
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
String key = monitor.getKey();
int port = monitor.getPort();
String key = monitor.getKey();
int port = monitor.getPort();
stop("forcestop", port, key, true);
monitor.await();
stop("forcestop", port, key, true);
monitor.await();
assertTrue(!monitor.isAlive());
assertTrue(server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(!ShutdownMonitor.isRegistered(server));
assertTrue(!monitor.isAlive());
assertTrue(server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(!ShutdownMonitor.isRegistered(server));
}
}
@Test
@ -98,25 +101,27 @@ public class ShutdownMonitorTest
monitor.setExitVm(false);
monitor.setPort(0);
TestableServer server = new TestableServer();
server.setStopAtShutdown(true);
server.start();
try(CloseableServer server = new CloseableServer())
{
server.setStopAtShutdown(true);
server.start();
//should be registered for shutdown on exit
assertTrue(ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
//should be registered for shutdown on exit
assertTrue(ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
String key = monitor.getKey();
int port = monitor.getPort();
String key = monitor.getKey();
int port = monitor.getPort();
stop("stop", port, key, true);
monitor.await();
stop("stop", port, key, true);
monitor.await();
assertTrue(!monitor.isAlive());
assertTrue(server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(!ShutdownMonitor.isRegistered(server));
assertTrue(!monitor.isAlive());
assertTrue(server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(!ShutdownMonitor.isRegistered(server));
}
}
@Test
@ -125,24 +130,26 @@ public class ShutdownMonitorTest
ShutdownMonitor monitor = ShutdownMonitor.getInstance();
monitor.setExitVm(false);
monitor.setPort(0);
TestableServer server = new TestableServer();
server.setStopAtShutdown(false);
server.start();
try(CloseableServer server = new CloseableServer())
{
server.setStopAtShutdown(false);
server.start();
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
String key = monitor.getKey();
int port = monitor.getPort();
String key = monitor.getKey();
int port = monitor.getPort();
stop("stop", port, key, true);
monitor.await();
stop("stop", port, key, true);
monitor.await();
assertTrue(!monitor.isAlive());
assertTrue(!server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
assertTrue(!monitor.isAlive());
assertTrue(!server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
}
}
public void stop(String command, int port, String key, boolean check) throws Exception
@ -170,7 +177,7 @@ public class ShutdownMonitorTest
}
}
public class TestableServer extends Server
public class CloseableServer extends Server implements Closeable
{
boolean destroyed = false;
boolean stopped = false;
@ -196,5 +203,19 @@ public class ShutdownMonitorTest
destroyed = false;
super.doStart();
}
@Override
public void close()
{
try
{
stop();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
}

View File

@ -53,7 +53,7 @@ import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -812,11 +812,9 @@ public class RequestLogHandlerTest
requestLog.setHandler(testHandler);
server.setHandler(requestLog);
try
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class,HttpChannelState.class))
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
((StdErrLog)Log.getLogger(HttpChannelState.class)).setHideStacks(true);
server.start();
String host = connector.getHost();
@ -855,8 +853,6 @@ public class RequestLogHandlerTest
finally
{
server.stop();
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
((StdErrLog)Log.getLogger(HttpChannelState.class)).setHideStacks(false);
}
}

View File

@ -34,7 +34,9 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.QuietServletException;
@ -42,6 +44,7 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@ -177,21 +180,24 @@ public class AsyncContextTest
@Test
public void testStartFlushCompleteThrow() throws Exception
{
String request = "GET /ctx/startthrow?flush=true&complete=true HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Connection: close\r\n" +
"\r\n";
String responseString = _connector.getResponses(request);
try(StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
String request = "GET /ctx/startthrow?flush=true&complete=true HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Connection: close\r\n" +
"\r\n";
String responseString = _connector.getResponses(request);
BufferedReader br = new BufferedReader(new StringReader(responseString));
BufferedReader br = new BufferedReader(new StringReader(responseString));
assertEquals("HTTP/1.1 200 OK", br.readLine());
br.readLine();// connection close
br.readLine();// server
br.readLine();// empty
assertEquals("HTTP/1.1 200 OK",br.readLine());
br.readLine();// connection close
br.readLine();// server
br.readLine();// empty
Assert.assertEquals("error servlet", "completeBeforeThrow", br.readLine());
Assert.assertEquals("error servlet","completeBeforeThrow",br.readLine());
}
}
@Test

View File

@ -47,6 +47,7 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
@ -57,6 +58,7 @@ import org.eclipse.jetty.toolchain.test.AdvancedRunner;
import org.eclipse.jetty.toolchain.test.http.SimpleHttpParser;
import org.eclipse.jetty.toolchain.test.http.SimpleHttpResponse;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
@ -69,13 +71,17 @@ public class AsyncIOServletTest
private ServerConnector connector;
private ServletContextHandler context;
private String path = "/path";
private static final ThreadLocal<String> scope = new ThreadLocal<>();
private static final ThreadLocal<Throwable> scope = new ThreadLocal<>();
public void startServer(HttpServlet servlet) throws Exception
{
startServer(servlet,30000);
}
public void startServer(HttpServlet servlet, long idleTimeout) throws Exception
{
server = new Server();
connector = new ServerConnector(server);
connector.setIdleTimeout(30000);
connector.setIdleTimeout(idleTimeout);
connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration().setDelayDispatchUntilContent(false);
server.addConnector(connector);
@ -90,8 +96,12 @@ public class AsyncIOServletTest
public void enterScope(Context context, Request request, Object reason)
{
if (scope.get()!=null)
{
System.err.println(Thread.currentThread()+" Already entered scope!!!");
scope.get().printStackTrace();
throw new IllegalStateException();
scope.set("SCOPPED");
}
scope.set(new Throwable());
}
@Override
@ -106,6 +116,8 @@ public class AsyncIOServletTest
server.start();
}
private static void assertScope()
{
if (scope.get()==null)
@ -116,6 +128,13 @@ public class AsyncIOServletTest
public void stopServer() throws Exception
{
server.stop();
if (scope.get()!=null)
{
System.err.println("Still in scope after stop!");
scope.get().printStackTrace();
throw new IllegalStateException("Didn't leave scope");
}
scope.set(null);
}
@Test
@ -241,11 +260,7 @@ public class AsyncIOServletTest
}
});
}
});
server.stop();
long idleTimeout = 1000;
connector.setIdleTimeout(idleTimeout);
server.start();
},1000);
String data1 = "0123456789";
String data2 = "ABCDEF";
@ -323,7 +338,8 @@ public class AsyncIOServletTest
"\r\n" +
data;
try (Socket client = new Socket("localhost", connector.getLocalPort()))
try (Socket client = new Socket("localhost", connector.getLocalPort());
StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
OutputStream output = client.getOutputStream();
output.write(request.getBytes("UTF-8"));

View File

@ -18,6 +18,12 @@
package org.eclipse.jetty.servlet;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
@ -59,7 +65,7 @@ import org.eclipse.jetty.toolchain.test.AdvancedRunner;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
@ -67,13 +73,6 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.eclipse.jetty.util.log.Log.getLogger;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
@RunWith(AdvancedRunner.class)
public class AsyncServletTest
@ -201,8 +200,7 @@ public class AsyncServletTest
@Test
public void testAsyncNotSupportedAsync() throws Exception
{
((StdErrLog)getLogger(HttpChannel.class)).setHideStacks(true);
try
try (StacklessLogging stackless = new StacklessLogging(ServletHandler.class))
{
_expectedCode="500 ";
String response=process("noasync","start=200",null);
@ -218,10 +216,6 @@ public class AsyncServletTest
assertContains("!asyncSupported",response);
assertContains("AsyncServletTest$AsyncServlet",response);
}
finally
{
((StdErrLog)getLogger(HttpChannel.class)).setHideStacks(false);
}
}
@Test

View File

@ -32,8 +32,7 @@ import org.eclipse.jetty.server.Dispatcher;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.QuietServletException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
@ -46,6 +45,7 @@ public class ErrorPageTest
{
private Server _server;
private LocalConnector _connector;
private StacklessLogging _stackless;
@Before
public void init() throws Exception
@ -70,13 +70,13 @@ public class ErrorPageTest
error.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE,"/error/GlobalErrorPage");
_server.start();
((StdErrLog)Log.getLogger(ServletHandler.class)).setHideStacks(true);
_stackless=new StacklessLogging(ServletHandler.class);
}
@After
public void destroy() throws Exception
{
((StdErrLog)Log.getLogger(ServletHandler.class)).setHideStacks(false);
_stackless.close();
_server.stop();
_server.join();
}

View File

@ -177,6 +177,8 @@ public class MultiPartFilter implements Filter
while (itor.hasNext() && params.size() < _maxFormKeys)
{
Part p = itor.next();
if (LOG.isDebugEnabled())
LOG.debug("{}",p);
MultiPartInputStreamParser.MultiPart mp = (MultiPartInputStreamParser.MultiPart)p;
if (mp.getFile() != null)
{

View File

@ -31,6 +31,7 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;
@ -43,9 +44,16 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.MultiPartInputStreamParser;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.log.StdErrLog;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -100,7 +108,7 @@ public class MultipartFilterTest
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
assertNotNull(req.getParameter("fileup"));
System.err.println("Fileup="+req.getParameter("fileup"));
// System.err.println("Fileup="+req.getParameter("fileup"));
assertNotNull(req.getParameter("fileup"+MultiPartFilter.CONTENT_TYPE_SUFFIX));
assertEquals(req.getParameter("fileup"+MultiPartFilter.CONTENT_TYPE_SUFFIX), "application/octet-stream");
super.doPost(req, resp);
@ -162,8 +170,11 @@ public class MultipartFilterTest
request.setContent(content);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,response.getStatus());
try(StacklessLogging stackless = new StacklessLogging(ServletHandler.class))
{
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,response.getStatus());
}
}
@ -611,10 +622,13 @@ public class MultipartFilterTest
request.setHeader("Host","tester");
request.setURI("/context/dump");
request.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus());
assertTrue(response.getContent().indexOf("Missing content")>=0);
try(StacklessLogging stackless = new StacklessLogging(ServletHandler.class))
{
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus());
assertTrue(response.getContent().indexOf("Missing content")>=0);
}
}
@Test
@ -634,9 +648,12 @@ public class MultipartFilterTest
request.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
request.setContent(whitespace);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus());
assertTrue(response.getContent().indexOf("Missing initial")>=0);
try(StacklessLogging stackless = new StacklessLogging(ServletHandler.class))
{
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus());
assertTrue(response.getContent().indexOf("Missing initial")>=0);
}
}
@ -656,10 +673,13 @@ public class MultipartFilterTest
request.setURI("/context/dump");
request.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
request.setContent(whitespace);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus());
assertTrue(response.getContent().indexOf("Missing initial")>=0);
try(StacklessLogging stackless = new StacklessLogging(ServletHandler.class))
{
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus());
assertTrue(response.getContent().indexOf("Missing initial")>=0);
}
}
@Test
@ -785,9 +805,12 @@ public class MultipartFilterTest
}
request.setContent(baos.toString());
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertTrue(response.getContent().contains("Buffer size exceeded"));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus());
try(StacklessLogging stackless = new StacklessLogging(ServletHandler.class))
{
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertTrue(response.getContent().contains("Buffer size exceeded"));
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus());
}
}
public static class TestServletParameterMap extends DumpServlet
@ -844,30 +867,34 @@ public class MultipartFilterTest
public static class TestServletCharSet extends HttpServlet
{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
//test that the multipart content bytes were converted correctly from their charset to unicode
String content = (String)req.getParameter("ttt");
assertNotNull(content);
assertEquals("ttt\u01FCzzz",content);
assertEquals("application/octet-stream; charset=UTF-8",req.getParameter("ttt"+MultiPartFilter.CONTENT_TYPE_SUFFIX));
String filename = req.getParameter("ttt");
assertEquals("ttt.txt",filename);
String contentType = (String)req.getParameter("ttt"+MultiPartFilter.CONTENT_TYPE_SUFFIX);
assertEquals("application/octet-stream; charset=UTF-8",contentType);
String charset=MimeTypes.getCharsetFromContentType(contentType);
assertEquals("utf-8",charset);
//test that the parameter map retrieves values as String[]
Map map = req.getParameterMap();
Object o = map.get("ttt");
assertTrue(o.getClass().isArray());
super.doPost(req, resp);
File file = (File)req.getAttribute("ttt");
String content=IO.toString(new InputStreamReader(new FileInputStream(file),charset));
assertEquals("ttt\u01FCzzz",content);
resp.setStatus(200);
resp.setContentType(contentType);
resp.getWriter().print(content);
}
}
@Test
public void testWithCharSet()
throws Exception
{
((StdErrLog)Log.getLogger(MultiPartFilter.class)).setDebugEnabled(true);
((StdErrLog)Log.getLogger(MultiPartInputStreamParser.class)).setDebugEnabled(true);
// generated and parsed test
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
@ -885,14 +912,18 @@ public class MultipartFilterTest
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(("--" + boundary + "\r\n"+
"Content-Disposition: form-data; name=\"ttt\"\r\n"+
"Content-Disposition: form-data; name=\"ttt\"; filename=\"ttt.txt\"\r\n"+
"Content-Type: application/octet-stream; charset=UTF-8\r\n\r\n").getBytes());
baos.write("ttt\u01FCzzz".getBytes(StandardCharsets.UTF_8));
baos.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
request.setContent(baos.toByteArray());
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
assertEquals("ttt\u01FCzzz",response.getContent());
}

View File

@ -38,11 +38,8 @@ import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletException;
@ -62,8 +59,7 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.TestTracker;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Assert;
@ -246,10 +242,8 @@ public class ThreadStarvationTest
@Test
public void testFailureStarvation() throws Exception
{
try
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class))
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
int acceptors = 0;
int selectors = 1;
int maxThreads = 10;
@ -412,9 +406,5 @@ public class ThreadStarvationTest
_server.stop();
}
finally
{
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
}
}
}

View File

@ -87,6 +87,11 @@ public class MultiPartInputStreamParser
_filename = filename;
}
@Override
public String toString()
{
return String.format("Part{n=%s,fn=%s,ct=%s,s=%d,t=%b,f=%s}",_name,_filename,_contentType,_size,_temporary,_file);
}
protected void setContentType (String contentType)
{
_contentType = contentType;

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.util.log;
import java.util.HashSet;
import java.util.Set;
/**
* A try-with-resources compatible layer for {@link StdErrLog#setHideStacks(boolean) hiding stacktraces} within the scope of the <code>try</code> block when
* logging with {@link StdErrLog} implementation.
@ -35,35 +38,47 @@ package org.eclipse.jetty.util.log;
*/
public class StacklessLogging implements AutoCloseable
{
private final Class<?> clazzes[];
private final Set<StdErrLog> squelched = new HashSet<>();
public StacklessLogging(Class<?>... classesToSquelch)
{
this.clazzes = classesToSquelch;
hideStacks(true);
}
@Override
public void close() throws Exception
{
hideStacks(false);
}
private void hideStacks(boolean hide)
{
for (Class<?> clazz : clazzes)
for (Class<?> clazz : classesToSquelch)
{
Logger log = Log.getLogger(clazz);
if (log == null)
{
// not interested in classes without loggers
continue;
}
Logger log = Log.getLogger(clazz);
// only operate on loggers that are of type StdErrLog
if (log instanceof StdErrLog)
{
// only operate on loggers that are of type StdErrLog
((StdErrLog)log).setHideStacks(hide);
StdErrLog stdErrLog=((StdErrLog)log);
if (!stdErrLog.isHideStacks())
{
stdErrLog.setHideStacks(true);
squelched.add(stdErrLog);
}
}
}
}
public StacklessLogging(Logger... logs)
{
for (Logger log : logs)
{
// only operate on loggers that are of type StdErrLog
if (log instanceof StdErrLog)
{
StdErrLog stdErrLog=((StdErrLog)log);
if (!stdErrLog.isHideStacks())
{
stdErrLog.setHideStacks(true);
squelched.add(stdErrLog);
}
}
}
}
@Override
public void close()
{
for (StdErrLog log : squelched)
log.setHideStacks(false);
}
}

View File

@ -42,6 +42,7 @@ import javax.servlet.ServletException;
import javax.servlet.http.Part;
import org.eclipse.jetty.util.MultiPartInputStreamParser.MultiPart;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
@ -628,7 +629,7 @@ public class MultiPartInputStreamTest
}
@Test
public void testCharsetEncoding () throws Exception
{
String contentType = "multipart/form-data; boundary=TheBoundary; charset=ISO-8859-1";

View File

@ -22,8 +22,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.Test;
@ -41,9 +40,8 @@ public class LifeCycleListenerTest
lifecycle.setCause(cause);
try
try (StacklessLogging stackless = new StacklessLogging(AbstractLifeCycle.class))
{
StdErrLog.getLogger(AbstractLifeCycle.class).setHideStacks(true);
lifecycle.start();
assertTrue(false);
}
@ -52,10 +50,6 @@ public class LifeCycleListenerTest
assertEquals(cause,e);
assertEquals(cause,listener.getCause());
}
finally
{
StdErrLog.getLogger(AbstractLifeCycle.class).setHideStacks(false);
}
lifecycle.setCause(null);
lifecycle.start();
@ -88,9 +82,8 @@ public class LifeCycleListenerTest
lifecycle.start();
lifecycle.setCause(cause);
try
try (StacklessLogging stackless = new StacklessLogging(AbstractLifeCycle.class))
{
((StdErrLog)Log.getLogger(AbstractLifeCycle.class)).setHideStacks(true);
lifecycle.stop();
assertTrue(false);
}
@ -99,10 +92,6 @@ public class LifeCycleListenerTest
assertEquals(cause,e);
assertEquals(cause,listener.getCause());
}
finally
{
((StdErrLog)Log.getLogger(AbstractLifeCycle.class)).setHideStacks(false);
}
lifecycle.setCause(null);

View File

@ -161,41 +161,42 @@ public class StdErrLogTest
/**
* Test to make sure that using a Null parameter on parameterized messages does not result in a NPE
* @throws NullPointerException failed test
* @throws Exception failed test
*/
@Test
public void testParameterizedMessage_NullValues() throws NullPointerException
public void testParameterizedMessage_NullValues() throws Exception
{
StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(),new Properties());
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
log.info("Testing info(msg,null,null) - {} {}","arg0","arg1");
log.info("Testing info(msg,null,null) - {} {}",null,null);
log.info("Testing info(msg,null,null) - {}",null,null);
log.info("Testing info(msg,null,null)",null,null);
log.info(null,"Testing","info(null,arg0,arg1)");
log.info(null,null,null);
log.info("Testing info(msg,null,null) - {} {}","arg0","arg1");
log.info("Testing info(msg,null,null) - {} {}",null,null);
log.info("Testing info(msg,null,null) - {}",null,null);
log.info("Testing info(msg,null,null)",null,null);
log.info(null,"Testing","info(null,arg0,arg1)");
log.info(null,null,null);
log.debug("Testing debug(msg,null,null) - {} {}","arg0","arg1");
log.debug("Testing debug(msg,null,null) - {} {}",null,null);
log.debug("Testing debug(msg,null,null) - {}",null,null);
log.debug("Testing debug(msg,null,null)",null,null);
log.debug(null,"Testing","debug(null,arg0,arg1)");
log.debug(null,null,null);
log.debug("Testing debug(msg,null,null) - {} {}","arg0","arg1");
log.debug("Testing debug(msg,null,null) - {} {}",null,null);
log.debug("Testing debug(msg,null,null) - {}",null,null);
log.debug("Testing debug(msg,null,null)",null,null);
log.debug(null,"Testing","debug(null,arg0,arg1)");
log.debug(null,null,null);
log.debug("Testing debug(msg,null)");
log.debug(null,new Throwable("Testing debug(null,thrw)").fillInStackTrace());
log.debug("Testing debug(msg,null)");
log.debug(null,new Throwable("Testing debug(null,thrw)").fillInStackTrace());
log.warn("Testing warn(msg,null,null) - {} {}","arg0","arg1");
log.warn("Testing warn(msg,null,null) - {} {}",null,null);
log.warn("Testing warn(msg,null,null) - {}",null,null);
log.warn("Testing warn(msg,null,null)",null,null);
log.warn(null,"Testing","warn(msg,arg0,arg1)");
log.warn(null,null,null);
log.warn("Testing warn(msg,null,null) - {} {}","arg0","arg1");
log.warn("Testing warn(msg,null,null) - {} {}",null,null);
log.warn("Testing warn(msg,null,null) - {}",null,null);
log.warn("Testing warn(msg,null,null)",null,null);
log.warn(null,"Testing","warn(msg,arg0,arg1)");
log.warn(null,null,null);
log.warn("Testing warn(msg,null)");
log.warn(null,new Throwable("Testing warn(msg,thrw)").fillInStackTrace());
log.warn("Testing warn(msg,null)");
log.warn(null,new Throwable("Testing warn(msg,thrw)").fillInStackTrace());
}
}
@Test
@ -314,232 +315,241 @@ public class StdErrLogTest
public void testWarnFiltering() throws UnsupportedEncodingException
{
StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(),new Properties());
log.setHideStacks(false);
try (StacklessLogging stackless = new StacklessLogging(log))
{
StdErrCapture output = new StdErrCapture(log);
StdErrCapture output = new StdErrCapture(log);
// Start with default level
log.warn("See Me");
// Start with default level
log.warn("See Me");
// Set to debug level
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.warn("Hear Me");
// Set to debug level
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.warn("Hear Me");
// Set to warn level
log.setLevel(StdErrLog.LEVEL_WARN);
log.warn("Cheer Me");
// Set to warn level
log.setLevel(StdErrLog.LEVEL_WARN);
log.warn("Cheer Me");
log.warn("<zoom>", new Throwable("out of focus"));
log.warn(new Throwable("scene lost"));
log.warn("<zoom>", new Throwable("out of focus"));
log.warn(new Throwable("scene lost"));
// Validate Output
// System.err.print(output);
output.assertContains("See Me");
output.assertContains("Hear Me");
output.assertContains("Cheer Me");
// Validate Output
// System.err.print(output);
output.assertContains("See Me");
output.assertContains("Hear Me");
output.assertContains("Cheer Me");
// Validate Stack Traces
output.assertContains(".StdErrLogTest:tname: <zoom>");
output.assertContains("java.lang.Throwable: out of focus");
output.assertContains("java.lang.Throwable: scene lost");
// Validate Stack Traces
output.assertContains(".StdErrLogTest:tname: <zoom>");
output.assertContains("java.lang.Throwable: out of focus");
output.assertContains("java.lang.Throwable: scene lost");
}
}
/**
* Tests StdErrLog.info() methods with level filtering.
* <p>
* Should only see INFO level messages when level is set to {@link StdErrLog#LEVEL_INFO} and below.
* @throws UnsupportedEncodingException failed test
* @throws Exception failed test
*/
@Test
public void testInfoFiltering() throws UnsupportedEncodingException
public void testInfoFiltering() throws Exception
{
StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(),new Properties());
log.setHideStacks(false);
try (StacklessLogging stackless = new StacklessLogging(log))
{
StdErrCapture output = new StdErrCapture(log);
StdErrCapture output = new StdErrCapture(log);
// Normal/Default behavior
log.info("I will not buy");
// Normal/Default behavior
log.info("I will not buy");
// Level Debug
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.info("this record");
// Level Debug
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.info("this record");
// Level All
log.setLevel(StdErrLog.LEVEL_ALL);
log.info("it is scratched.");
// Level All
log.setLevel(StdErrLog.LEVEL_ALL);
log.info("it is scratched.");
log.info("<zoom>", new Throwable("out of focus"));
log.info(new Throwable("scene lost"));
log.info("<zoom>", new Throwable("out of focus"));
log.info(new Throwable("scene lost"));
// Level Warn
log.setLevel(StdErrLog.LEVEL_WARN);
log.info("sorry?");
log.info("<spoken line>", new Throwable("on editing room floor"));
// Level Warn
log.setLevel(StdErrLog.LEVEL_WARN);
log.info("sorry?");
log.info("<spoken line>", new Throwable("on editing room floor"));
// Validate Output
output.assertContains("I will not buy");
output.assertContains("this record");
output.assertContains("it is scratched.");
output.assertNotContains("sorry?");
// Validate Output
output.assertContains("I will not buy");
output.assertContains("this record");
output.assertContains("it is scratched.");
output.assertNotContains("sorry?");
// Validate Stack Traces
output.assertNotContains("<spoken line>");
output.assertNotContains("on editing room floor");
// Validate Stack Traces
output.assertNotContains("<spoken line>");
output.assertNotContains("on editing room floor");
output.assertContains(".StdErrLogTest:tname: <zoom>");
output.assertContains("java.lang.Throwable: out of focus");
output.assertContains("java.lang.Throwable: scene lost");
output.assertContains(".StdErrLogTest:tname: <zoom>");
output.assertContains("java.lang.Throwable: out of focus");
output.assertContains("java.lang.Throwable: scene lost");
}
}
/**
* Tests {@link StdErrLog#LEVEL_OFF} filtering.
* @throws UnsupportedEncodingException failed test
* @throws Exception failed test
*/
@Test
public void testOffFiltering() throws UnsupportedEncodingException
public void testOffFiltering() throws Exception
{
StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(),new Properties());
log.setHideStacks(false);
log.setLevel(StdErrLog.LEVEL_OFF);
try (StacklessLogging stackless = new StacklessLogging(log))
{
log.setLevel(StdErrLog.LEVEL_OFF);
StdErrCapture output = new StdErrCapture(log);
StdErrCapture output = new StdErrCapture(log);
// Various logging events
log.debug("Squelch");
log.debug("Squelch", new RuntimeException("Squelch"));
log.info("Squelch");
log.info("Squelch", new IllegalStateException("Squelch"));
log.warn("Squelch");
log.warn("Squelch", new Exception("Squelch"));
log.ignore(new Throwable("Squelch"));
// Various logging events
log.debug("Squelch");
log.debug("Squelch", new RuntimeException("Squelch"));
log.info("Squelch");
log.info("Squelch", new IllegalStateException("Squelch"));
log.warn("Squelch");
log.warn("Squelch", new Exception("Squelch"));
log.ignore(new Throwable("Squelch"));
// Validate Output
output.assertNotContains("Squelch");
// Validate Output
output.assertNotContains("Squelch");
}
}
/**
* Tests StdErrLog.debug() methods with level filtering.
* <p>
* Should only see DEBUG level messages when level is set to {@link StdErrLog#LEVEL_DEBUG} and below.
* @throws UnsupportedEncodingException failed test
* @throws Exception failed test
*/
@Test
public void testDebugFiltering() throws UnsupportedEncodingException
public void testDebugFiltering() throws Exception
{
StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(),new Properties());
log.setHideStacks(true);
try(StacklessLogging stackless = new StacklessLogging(log))
{
StdErrCapture output = new StdErrCapture(log);
StdErrCapture output = new StdErrCapture(log);
// Normal/Default behavior
log.debug("Tobacconist");
log.debug("<spoken line>", new Throwable("on editing room floor"));
// Normal/Default behavior
log.debug("Tobacconist");
log.debug("<spoken line>", new Throwable("on editing room floor"));
// Level Debug
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.debug("my hovercraft is");
// Level Debug
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.debug("my hovercraft is");
log.debug("<zoom>", new Throwable("out of focus"));
log.debug(new Throwable("scene lost"));
log.debug("<zoom>", new Throwable("out of focus"));
log.debug(new Throwable("scene lost"));
// Level All
log.setLevel(StdErrLog.LEVEL_ALL);
log.debug("full of eels.");
// Level All
log.setLevel(StdErrLog.LEVEL_ALL);
log.debug("full of eels.");
// Level Warn
log.setLevel(StdErrLog.LEVEL_WARN);
log.debug("what?");
// Level Warn
log.setLevel(StdErrLog.LEVEL_WARN);
log.debug("what?");
// Validate Output
// System.err.print(output);
output.assertNotContains("Tobacconist");
output.assertContains("my hovercraft is");
output.assertContains("full of eels.");
output.assertNotContains("what?");
// Validate Output
// System.err.print(output);
output.assertNotContains("Tobacconist");
output.assertContains("my hovercraft is");
output.assertContains("full of eels.");
output.assertNotContains("what?");
// Validate Stack Traces
output.assertNotContains("<spoken line>");
output.assertNotContains("on editing room floor");
// Validate Stack Traces
output.assertNotContains("<spoken line>");
output.assertNotContains("on editing room floor");
output.assertContains(".StdErrLogTest:tname: <zoom>");
output.assertContains("java.lang.Throwable: out of focus");
output.assertContains("java.lang.Throwable: scene lost");
output.assertContains(".StdErrLogTest:tname: <zoom>");
output.assertContains("java.lang.Throwable: out of focus");
output.assertContains("java.lang.Throwable: scene lost");
}
}
/**
* Tests StdErrLog with {@link Logger#ignore(Throwable)} use.
* <p>
* Should only see IGNORED level messages when level is set to {@link StdErrLog#LEVEL_ALL}.
* @throws UnsupportedEncodingException failed test
* @throws Exception failed test
*/
@Test
public void testIgnores() throws UnsupportedEncodingException
public void testIgnores() throws Exception
{
StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(),new Properties());
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
StdErrCapture output = new StdErrCapture(log);
StdErrCapture output = new StdErrCapture(log);
// Normal/Default behavior
log.ignore(new Throwable("IGNORE ME"));
// Normal/Default behavior
log.ignore(new Throwable("IGNORE ME"));
// Show Ignored
log.setLevel(StdErrLog.LEVEL_ALL);
log.ignore(new Throwable("Don't ignore me"));
// Show Ignored
log.setLevel(StdErrLog.LEVEL_ALL);
log.ignore(new Throwable("Don't ignore me"));
// Set to Debug level
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.ignore(new Throwable("Debug me"));
// Set to Debug level
log.setLevel(StdErrLog.LEVEL_DEBUG);
log.ignore(new Throwable("Debug me"));
// Validate Output
// System.err.print(output);
output.assertNotContains("IGNORE ME");
output.assertContains("Don't ignore me");
output.assertNotContains("Debug me");
// Validate Output
// System.err.print(output);
output.assertNotContains("IGNORE ME");
output.assertContains("Don't ignore me");
output.assertNotContains("Debug me");
}
}
@Test
public void testIsDebugEnabled() {
public void testIsDebugEnabled() throws Exception
{
StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(),new Properties());
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
log.setLevel(StdErrLog.LEVEL_ALL);
Assert.assertThat("log.level(all).isDebugEnabled", log.isDebugEnabled(), is(true));
log.setLevel(StdErrLog.LEVEL_ALL);
Assert.assertThat("log.level(all).isDebugEnabled", log.isDebugEnabled(), is(true));
log.setLevel(StdErrLog.LEVEL_DEBUG);
Assert.assertThat("log.level(debug).isDebugEnabled", log.isDebugEnabled(), is(true));
log.setLevel(StdErrLog.LEVEL_DEBUG);
Assert.assertThat("log.level(debug).isDebugEnabled", log.isDebugEnabled(), is(true));
log.setLevel(StdErrLog.LEVEL_INFO);
Assert.assertThat("log.level(info).isDebugEnabled", log.isDebugEnabled(), is(false));
log.setLevel(StdErrLog.LEVEL_INFO);
Assert.assertThat("log.level(info).isDebugEnabled", log.isDebugEnabled(), is(false));
log.setLevel(StdErrLog.LEVEL_WARN);
Assert.assertThat("log.level(warn).isDebugEnabled", log.isDebugEnabled(), is(false));
log.setLevel(StdErrLog.LEVEL_WARN);
Assert.assertThat("log.level(warn).isDebugEnabled", log.isDebugEnabled(), is(false));
log.setLevel(StdErrLog.LEVEL_OFF);
Assert.assertThat("log.level(off).isDebugEnabled", log.isDebugEnabled(), is(false));
log.setLevel(StdErrLog.LEVEL_OFF);
Assert.assertThat("log.level(off).isDebugEnabled", log.isDebugEnabled(), is(false));
}
}
@Test
public void testSetGetLevel()
{
StdErrLog log = new StdErrLog(StdErrLogTest.class.getName(),new Properties());
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
log.setLevel(StdErrLog.LEVEL_ALL);
Assert.assertThat("log.level(all).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_ALL));
log.setLevel(StdErrLog.LEVEL_ALL);
Assert.assertThat("log.level(all).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_ALL));
log.setLevel(StdErrLog.LEVEL_DEBUG);
Assert.assertThat("log.level(debug).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_DEBUG));
log.setLevel(StdErrLog.LEVEL_DEBUG);
Assert.assertThat("log.level(debug).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_DEBUG));
log.setLevel(StdErrLog.LEVEL_INFO);
Assert.assertThat("log.level(info).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_INFO));
log.setLevel(StdErrLog.LEVEL_INFO);
Assert.assertThat("log.level(info).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_INFO));
log.setLevel(StdErrLog.LEVEL_WARN);
Assert.assertThat("log.level(warn).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_WARN));
log.setLevel(StdErrLog.LEVEL_WARN);
Assert.assertThat("log.level(warn).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_WARN));
log.setLevel(StdErrLog.LEVEL_OFF);
Assert.assertThat("log.level(off).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_OFF));
log.setLevel(StdErrLog.LEVEL_OFF);
Assert.assertThat("log.level(off).getLevel()", log.getLevel(), is(StdErrLog.LEVEL_OFF));
}
}
@Test
@ -547,12 +557,13 @@ public class StdErrLogTest
{
String baseName = "jetty";
StdErrLog log = new StdErrLog(baseName,new Properties());
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
Logger log2 = log.getLogger("child");
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty.child"));
Logger log2 = log.getLogger("child");
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty.child"));
}
}
@Test
@ -560,12 +571,13 @@ public class StdErrLogTest
{
String baseName = "jetty";
StdErrLog log = new StdErrLog(baseName,new Properties());
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
Logger log2 = log.getLogger("child.of.the.sixties");
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty.child.of.the.sixties"));
Logger log2 = log.getLogger("child.of.the.sixties");
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty.child.of.the.sixties"));
}
}
@Test
@ -573,14 +585,15 @@ public class StdErrLogTest
{
String baseName = "jetty";
StdErrLog log = new StdErrLog(baseName,new Properties());
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
// Pass null as child reference, should return parent logger
Logger log2 = log.getLogger((String)null);
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty"));
Assert.assertSame("Should have returned same logger", log2, log);
// Pass null as child reference, should return parent logger
Logger log2 = log.getLogger((String)null);
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty"));
Assert.assertSame("Should have returned same logger", log2, log);
}
}
@Test
@ -588,14 +601,15 @@ public class StdErrLogTest
{
String baseName = "jetty";
StdErrLog log = new StdErrLog(baseName,new Properties());
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
// Pass empty name as child reference, should return parent logger
Logger log2 = log.getLogger("");
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty"));
Assert.assertSame("Should have returned same logger", log2, log);
// Pass empty name as child reference, should return parent logger
Logger log2 = log.getLogger("");
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty"));
Assert.assertSame("Should have returned same logger", log2, log);
}
}
@Test
@ -603,14 +617,15 @@ public class StdErrLogTest
{
String baseName = "jetty";
StdErrLog log = new StdErrLog(baseName,new Properties());
log.setHideStacks(true);
try (StacklessLogging stackless = new StacklessLogging(log))
{
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
Assert.assertThat("Logger.name", log.getName(), is("jetty"));
// Pass empty name as child reference, should return parent logger
Logger log2 = log.getLogger(" ");
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty"));
Assert.assertSame("Should have returned same logger", log2, log);
// Pass empty name as child reference, should return parent logger
Logger log2 = log.getLogger(" ");
Assert.assertThat("Logger.child.name", log2.getName(), is("jetty"));
Assert.assertSame("Should have returned same logger", log2, log);
}
}
@Test

View File

@ -18,9 +18,9 @@
package org.eclipse.jetty.util.ssl;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
@ -34,10 +34,8 @@ import java.util.Arrays;
import javax.net.ssl.SSLEngine;
import org.eclipse.jetty.toolchain.test.JDK;
import org.eclipse.jetty.toolchain.test.OS;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.resource.Resource;
import org.hamcrest.Matchers;
import org.junit.Assert;
@ -157,9 +155,8 @@ public class SslContextFactoryTest
cf.setKeyManagerPassword("wrong_keypwd");
cf.setTrustStorePassword("storepwd");
try
try (StacklessLogging stackless = new StacklessLogging(AbstractLifeCycle.class))
{
((StdErrLog)Log.getLogger(AbstractLifeCycle.class)).setHideStacks(true);
cf.start();
Assert.fail();
}
@ -181,9 +178,8 @@ public class SslContextFactoryTest
cf.setKeyManagerPassword("keypwd");
cf.setTrustStorePassword("wrong_storepwd");
try
try (StacklessLogging stackless = new StacklessLogging(AbstractLifeCycle.class))
{
((StdErrLog)Log.getLogger(AbstractLifeCycle.class)).setHideStacks(true);
cf.start();
Assert.fail();
}
@ -196,9 +192,8 @@ public class SslContextFactoryTest
@Test
public void testNoKeyConfig() throws Exception
{
try
try (StacklessLogging stackless = new StacklessLogging(AbstractLifeCycle.class))
{
((StdErrLog)Log.getLogger(AbstractLifeCycle.class)).setHideStacks(true);
cf.setTrustStorePath("/foo");
cf.start();
Assert.fail();

View File

@ -29,8 +29,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.toolchain.test.AdvancedRunner;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -271,9 +270,8 @@ public class QueuedThreadPoolTest
tp.setMaxThreads(10);
tp.setIdleTimeout(1000);
tp.start();
try
try (StacklessLogging stackless = new StacklessLogging(QueuedThreadPool.class))
{
((StdErrLog)Log.getLogger(QueuedThreadPool.class)).setHideStacks(true);
tp.execute(new Runnable(){ public void run () { throw new IllegalStateException(); } });
tp.execute(new Runnable(){ public void run () { throw new Error(); } });
tp.execute(new Runnable(){ public void run () { throw new RuntimeException(); } });
@ -282,10 +280,6 @@ public class QueuedThreadPoolTest
Thread.sleep(100);
assertThat(tp.getThreads(),greaterThanOrEqualTo(5));
}
finally
{
((StdErrLog)Log.getLogger(QueuedThreadPool.class)).setHideStacks(false);
}
}
@Test

View File

@ -28,6 +28,7 @@ import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.toolchain.perf.PlatformMonitor;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.statistic.SampleStatistic;
import org.hamcrest.Matchers;
import org.junit.After;
@ -171,31 +172,34 @@ public class SchedulerTest
@Test
public void testTaskThrowsException() throws Exception
{
long delay = 500;
_scheduler.schedule(new Runnable()
try (StacklessLogging stackless = new StacklessLogging(TimerScheduler.class))
{
@Override
public void run()
long delay = 500;
_scheduler.schedule(new Runnable()
{
throw new RuntimeException("Thrown by testTaskThrowsException");
}
}, delay, TimeUnit.MILLISECONDS);
@Override
public void run()
{
throw new RuntimeException("Thrown by testTaskThrowsException");
}
}, delay, TimeUnit.MILLISECONDS);
TimeUnit.MILLISECONDS.sleep(2 * delay);
TimeUnit.MILLISECONDS.sleep(2 * delay);
// Check whether after a task throwing an exception, the scheduler is still working
// Check whether after a task throwing an exception, the scheduler is still working
final CountDownLatch latch = new CountDownLatch(1);
_scheduler.schedule(new Runnable()
{
@Override
public void run()
final CountDownLatch latch = new CountDownLatch(1);
_scheduler.schedule(new Runnable()
{
latch.countDown();
}
}, delay, TimeUnit.MILLISECONDS);
@Override
public void run()
{
latch.countDown();
}
}, delay, TimeUnit.MILLISECONDS);
Assert.assertTrue(latch.await(2 * delay, TimeUnit.MILLISECONDS));
Assert.assertTrue(latch.await(2 * delay, TimeUnit.MILLISECONDS));
}
}
@Test

View File

@ -33,6 +33,7 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.websocket.common.WebSocketSession;
import org.eclipse.jetty.websocket.jsr356.EchoHandler;
import org.eclipse.jetty.websocket.jsr356.endpoints.JsrEndpointEventDriver;
import org.junit.AfterClass;
@ -90,7 +91,7 @@ public class MisbehavingClassTest
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
EndpointRuntimeOnOpen socket = new EndpointRuntimeOnOpen();
try (StacklessLogging logging = new StacklessLogging(EndpointRuntimeOnOpen.class,JsrEndpointEventDriver.class))
try (StacklessLogging logging = new StacklessLogging(EndpointRuntimeOnOpen.class,JsrEndpointEventDriver.class,WebSocketSession.class))
{
// expecting ArrayIndexOutOfBoundsException during onOpen
Session session = container.connectToServer(socket,serverUri);
@ -111,7 +112,7 @@ public class MisbehavingClassTest
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
AnnotatedRuntimeOnOpen socket = new AnnotatedRuntimeOnOpen();
try (StacklessLogging logging = new StacklessLogging(AnnotatedRuntimeOnOpen.class))
try (StacklessLogging logging = new StacklessLogging(AnnotatedRuntimeOnOpen.class,WebSocketSession.class))
{
// expecting ArrayIndexOutOfBoundsException during onOpen
Session session = container.connectToServer(socket,serverUri);

View File

@ -34,10 +34,12 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.common.test.LeakTrackingBufferPoolRule;
import org.eclipse.jetty.websocket.jsr356.annotations.JsrEvents;
import org.eclipse.jetty.websocket.jsr356.server.samples.idletimeout.IdleTimeoutContextListener;
import org.eclipse.jetty.websocket.jsr356.server.samples.idletimeout.OnOpenIdleTimeoutEndpoint;
import org.eclipse.jetty.websocket.jsr356.server.samples.idletimeout.OnOpenIdleTimeoutSocket;
@ -127,8 +129,11 @@ public class IdleTimeoutTest
@Test
public void testAnnotated() throws Exception
{
URI uri = server.getServerBaseURI();
assertConnectionTimeout(uri.resolve("idle-onopen-socket"));
try(StacklessLogging stackless = new StacklessLogging(JsrEvents.class))
{
URI uri = server.getServerBaseURI();
assertConnectionTimeout(uri.resolve("idle-onopen-socket"));
}
}
@Test

View File

@ -257,7 +257,7 @@ public class WebSocketCloseTest
{
client.setProtocols("fastfail");
client.setTimeout(1,TimeUnit.SECONDS);
try (StacklessLogging scope = new StacklessLogging(AbstractEventDriver.class))
try (StacklessLogging scope = new StacklessLogging(AbstractEventDriver.class,WebSocketSession.class))
{
client.connect();
client.sendStandardRequest();

View File

@ -74,6 +74,12 @@ public class WebSocketServletRFCTest
server.stop();
}
/**
* @param clazz the class to enable
* @param enabled true to enable the stack traces (or not)
* @deprecated use {@link StacklessLogging} in a try-with-resources block instead
*/
@Deprecated
private void enableStacks(Class<?> clazz, boolean enabled)
{
StdErrLog log = StdErrLog.getLogger(clazz);
@ -203,11 +209,8 @@ public class WebSocketServletRFCTest
@Test
public void testInternalError() throws Exception
{
// Disable Long Stacks from EventDriver (we know this test will throw an exception)
enableStacks(EventDriver.class,false);
BlockheadClient client = new BlockheadClient(server.getServerUri());
try
try (BlockheadClient client = new BlockheadClient(server.getServerUri());
StacklessLogging stackless=new StacklessLogging(EventDriver.class))
{
client.connect();
client.sendStandardRequest();
@ -225,12 +228,6 @@ public class WebSocketServletRFCTest
Assert.assertThat("Close Frame.status code",close.getStatusCode(),is(StatusCode.SERVER_ERROR));
}
}
finally
{
// Reenable Long Stacks from EventDriver
enableStacks(EventDriver.class,true);
client.close();
}
}
/**
@ -279,13 +276,10 @@ public class WebSocketServletRFCTest
@Test
public void testTextNotUTF8() throws Exception
{
// Disable Long Stacks from Parser (we know this test will throw an exception)
enableStacks(Parser.class,false);
BlockheadClient client = new BlockheadClient(server.getServerUri());
client.setProtocols("other");
try
try (StacklessLogging stackless=new StacklessLogging(Parser.class);
BlockheadClient client = new BlockheadClient(server.getServerUri()))
{
client.setProtocols("other");
client.connect();
client.sendStandardRequest();
client.expectUpgradeResponse();
@ -305,12 +299,6 @@ public class WebSocketServletRFCTest
CloseInfo close = new CloseInfo(frame);
Assert.assertThat("Close Status Code",close.getStatusCode(),is(StatusCode.BAD_PAYLOAD));
}
finally
{
// Reenable Long Stacks from Parser
enableStacks(Parser.class,true);
client.close();
}
}
/**

View File

@ -39,9 +39,12 @@ import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http2.FlowControlStrategy;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
@ -277,7 +280,7 @@ public class HttpClientTest extends AbstractTest
}
catch (ExecutionException x)
{
// Buffering capacity exceeded.
Assert.assertThat(x.getMessage(),Matchers.containsString("Buffering capacity exceeded"));
}
// Verify that we can make another request.

View File

@ -18,8 +18,12 @@
package org.eclipse.jetty.test.rfcs;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
@ -42,9 +46,7 @@ import org.eclipse.jetty.test.support.rawhttp.HttpTesting;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.StringAssert;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.hamcrest.Matchers;
import org.junit.AfterClass;
import org.junit.Assert;
@ -1448,10 +1450,8 @@ public abstract class RFC2616BaseTest
public void test14_23_IncompleteHostHeader() throws Exception
{
// HTTP/1.1 - Incomplete (empty) Host header
try
try (StacklessLogging stackless = new StacklessLogging(HttpParser.class))
{
((StdErrLog)Log.getLogger(HttpParser.class)).setHideStacks(true);
StringBuffer req4 = new StringBuffer();
req4.append("GET /tests/R1.txt HTTP/1.1\n");
req4.append("Host:\n");
@ -1461,10 +1461,6 @@ public abstract class RFC2616BaseTest
HttpTester.Response response = http.request(req4);
assertEquals("14.23 HTTP/1.1 - Empty Host", HttpStatus.BAD_REQUEST_400, response.getStatus());
}
finally
{
((StdErrLog)Log.getLogger(HttpParser.class)).setHideStacks(false);
}
}
/**

View File

@ -35,8 +35,7 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.After;
@ -54,7 +53,7 @@ public class ReloadedSessionMissingClassTest
@Test
public void testSessionReloadWithMissingClass() throws Exception
{
((StdErrLog)Log.getLogger("org.eclipse.jetty.server.session")).setHideStacks(true);
((StdErrLog)Log.getLogger(org.eclipse.jetty.server.session.JDBCSessionManager.class)).setHideStacks(true);
Resource.setDefaultUseCaches(false);
String contextPath = "/foo";
@ -96,7 +95,7 @@ public class ReloadedSessionMissingClassTest
webApp.addServlet("Bar", "/bar");
server1.start();
int port1 = server1.getPort();
try
try (StacklessLogging stackless = new StacklessLogging(JDBCSessionManager.class))
{
HttpClient client = new HttpClient();
client.start();

View File

@ -18,6 +18,7 @@
package org.eclipse.jetty.server.session;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.After;
import org.junit.Test;
@ -42,7 +43,10 @@ public class SessionExpiryTest extends AbstractSessionExpiryTest
@Test
public void testSessionExpiry() throws Exception
{
super.testSessionExpiry();
try(StacklessLogging stackless=new StacklessLogging(JDBCSessionManager.class))
{
super.testSessionExpiry();
}
}

View File

@ -39,8 +39,7 @@ import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.thread.Locker.Lock;
import org.junit.Test;
@ -120,7 +119,6 @@ public abstract class AbstractIdleSessionTest
int idlePeriod = 5;
int inspectPeriod = 1;
((StdErrLog)Log.getLogger("org.eclipse.jetty.server.session")).setHideStacks(true);
System.setProperty("org.eclipse.jetty.STACKS", "false");
_server1 = createServer(0, inactivePeriod, scavengePeriod, inspectPeriod, idlePeriod);
@ -130,8 +128,8 @@ public abstract class AbstractIdleSessionTest
_server1.start();
int port1 = _server1.getPort();
try
{
try (StacklessLogging stackless = new StacklessLogging(HashedSession.class))
{
HttpClient client = new HttpClient();
client.start();
String url = "http://localhost:" + port1 + contextPath + servletMapping;

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@ -196,6 +197,18 @@ public abstract class AbstractSessionInvalidateAndCreateTest
//invalidate existing session
session.invalidate();
//now try to access the invalid session
try
{
session.getAttribute("identity");
fail("Session should be invalid");
}
catch (IllegalStateException e)
{
assertNotNull(e.getMessage());
assertTrue(e.getMessage().contains("id"));
}
//now make a new session
session = request.getSession(true);
session.setAttribute("identity", "session2");