Merge remote-tracking branch 'origin/jetty-9.2.x'

Conflicts:
	jetty-websocket/pom.xml
	tests/test-sessions/test-mongodb-sessions/pom.xml
This commit is contained in:
Greg Wilkins 2014-10-10 08:53:43 +11:00
commit 758ce66c8d
30 changed files with 1552 additions and 89 deletions

View File

@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/usr/bin/env bash
#
# Startup script for jetty under *nix systems (it works under NT/cygwin too).
@ -278,6 +278,12 @@ if [ -z "$JETTY_STATE" ]
then
JETTY_STATE=$JETTY_BASE/${NAME}.state
fi
case "`uname`" in
CYGWIN*) JETTY_STATE="`cygpath -w $JETTY_STATE`";;
esac
JETTY_ARGS+=("jetty.state=$JETTY_STATE")
rm -f $JETTY_STATE
@ -340,6 +346,11 @@ then
fi
if [ "$JETTY_LOGS" ]
then
case "`uname`" in
CYGWIN*) JETTY_LOGS="`cygpath -w $JETTY_LOGS`";;
esac
JAVA_OPTIONS+=("-Djetty.logs=$JETTY_LOGS")
fi
@ -355,6 +366,15 @@ esac
#####################################################
# Add jetty properties to Java VM options.
#####################################################
case "`uname`" in
CYGWIN*)
JETTY_HOME="`cygpath -w $JETTY_HOME`"
JETTY_BASE="`cygpath -w $JETTY_BASE`"
TMPDIR="`cygpath -w $TMPDIR`"
;;
esac
JAVA_OPTIONS+=("-Djetty.home=$JETTY_HOME" "-Djetty.base=$JETTY_BASE" "-Djava.io.tmpdir=$TMPDIR")
#####################################################
@ -369,6 +389,10 @@ then
exit 1
fi
case "`uname`" in
CYGWIN*) JETTY_START="`cygpath -w $JETTY_START`";;
esac
RUN_ARGS=(${JAVA_OPTIONS[@]} -jar "$JETTY_START" ${JETTY_ARGS[*]})
RUN_CMD=("$JAVA" ${RUN_ARGS[@]})
@ -420,7 +444,7 @@ case "$ACTION" in
exit 1
fi
if [ "$JETTY_USER" ]
if [ -n "$JETTY_USER" ]
then
unset SU_SHELL
if [ "$JETTY_SHELL" ]
@ -450,6 +474,7 @@ case "$ACTION" in
echo "OK `date`"
else
echo "FAILED `date`"
exit 1
fi
else
echo "ok `date`"
@ -474,7 +499,16 @@ case "$ACTION" in
rm -f "$JETTY_PID"
echo OK
else
if [ ! -f "$JETTY_PID" ] ; then
echo "ERROR: no pid found at $JETTY_PID"
exit 1
fi
PID=$(cat "$JETTY_PID" 2>/dev/null)
if [ -z "$PID" ] ; then
echo "ERROR: no pid id found in $JETTY_PID"
exit 1
fi
kill "$PID" 2>/dev/null
TIMEOUT=30

View File

@ -98,7 +98,7 @@ public class HttpSpiContextHandler extends ContextHandler
ex.printStackTrace(writer);
writer.println("</pre>");
writer.println("<p><i><small><a href=\"http://jetty.mortbay.org\">Powered by jetty://</a></small></i></p>");
writer.println("<p><i><small><a href=\"http://eclipse.org/jetty\">Powered by jetty://</a></small></i></p>");
writer.close();
}

View File

@ -72,9 +72,10 @@ public class JettyDeployWar extends JettyRunWarMojo
@Override
public void finishConfigurationBeforeStart() throws Exception
{
super.finishConfigurationBeforeStart();
//only stop the server at shutdown if we are blocking
server.setStopAtShutdown(!nonblocking);
super.finishConfigurationBeforeStart();
}
}

View File

@ -30,10 +30,12 @@ import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
@ -137,6 +139,14 @@ public class JettyRunForkedMojo extends JettyRunMojo
* @parameter default-value="50"
*/
private int maxStartupLines;
/**
* Extra environment variables to be passed to the forked process
*
* @parameter
*/
private Map<String,String> env = new HashMap<String,String>();
/**
* The forked jetty instance
@ -344,7 +354,13 @@ public class JettyRunForkedMojo extends JettyRunMojo
PluginLog.getLog().debug(Arrays.toString(cmd.toArray()));
PluginLog.getLog().info("Forked process starting");
//set up extra environment vars if there are any
if (!env.isEmpty())
{
builder.environment().putAll(env);
}
if (waitForChild)
{
forkedProcess = builder.start();

View File

@ -399,8 +399,8 @@ public class MongoSessionManager extends NoSqlSessionManager
// cleanup, remove values from session, that don't exist in data anymore:
for (String str : session.getNames())
{
if (!attrs.keySet().contains(str))
{
if (!attrs.keySet().contains(encodeName(str)))
{
session.doPutOrRemove(str,null);
session.unbindValue(str,session.getAttribute(str));
}

View File

@ -892,7 +892,7 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor
if (defaultNE!=null)
defaultNE.bindToENC(name);
else
throw new IllegalStateException("Nothing to bind for name "+nameInEnvironment);
throw new IllegalStateException("Nothing to bind for name " + name);
}

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.plus.webapp;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@ -50,6 +51,7 @@ public class PlusDescriptorProcessorTest
protected FragmentDescriptor fragDescriptor1;
protected FragmentDescriptor fragDescriptor2;
protected FragmentDescriptor fragDescriptor3;
protected FragmentDescriptor fragDescriptor4;
protected WebAppContext context;
/**
* @throws java.lang.Exception
@ -81,6 +83,9 @@ public class PlusDescriptorProcessorTest
URL frag3Xml = Thread.currentThread().getContextClassLoader().getResource("web-fragment-3.xml");
fragDescriptor3 = new FragmentDescriptor(org.eclipse.jetty.util.resource.Resource.newResource(frag3Xml));
fragDescriptor3.parse();
URL frag4Xml = Thread.currentThread().getContextClassLoader().getResource("web-fragment-4.xml");
fragDescriptor4 = new FragmentDescriptor(org.eclipse.jetty.util.resource.Resource.newResource(frag4Xml));
fragDescriptor4.parse();
}
@After
@ -94,6 +99,32 @@ public class PlusDescriptorProcessorTest
Thread.currentThread().setContextClassLoader(oldLoader);
}
@Test
public void testMissingResourceDeclaration()
throws Exception
{
ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(context.getClassLoader());
try
{
PlusDescriptorProcessor pdp = new PlusDescriptorProcessor();
pdp.process(context, fragDescriptor4);
fail("Expected missing resource declaration");
}
catch (InvocationTargetException ex)
{
Throwable cause = ex.getCause();
assertNotNull(cause);
assertNotNull(cause.getMessage());
assertTrue(cause.getMessage().contains("jdbc/mymissingdatasource"));
}
finally
{
Thread.currentThread().setContextClassLoader(oldLoader);
}
}
@Test
public void testWebXmlResourceDeclarations()
throws Exception

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-fragment
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-fragment_3_0.xsd"
version="3.0">
<name>Fragment 4</name>
<resource-ref>
<res-ref-name>jdbc/mymissingdatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-fragment>

View File

@ -188,8 +188,10 @@ public class ProxyServlet extends HttpServlet
{
String servletName = getServletConfig().getServletName();
servletName = servletName.replace('-', '.');
if (!servletName.startsWith(getClass().getPackage().getName()))
if ((getClass().getPackage() != null) && !servletName.startsWith(getClass().getPackage().getName()))
{
servletName = getClass().getName() + "." + servletName;
}
return Log.getLogger(servletName);
}

View File

@ -0,0 +1,66 @@
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.URIUtil;
/**
* Secured Redirect Handler
* <p>
* Using information present in the {@link HttpConfiguration}, will attempt to redirect to the {@link HttpConfiguration#getSecureScheme()} and
* {@link HttpConfiguration#getSecurePort()} for any request that {@link HttpServletRequest#isSecure()} == false.
*/
public class SecuredRedirectHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
HttpConfiguration httpConfig = HttpChannel.getCurrentHttpChannel().getHttpConfiguration();
if (baseRequest.isSecure())
{
return; // all done
}
if (httpConfig.getSecurePort() > 0)
{
String scheme = httpConfig.getSecureScheme();
int port = httpConfig.getSecurePort();
String url = URIUtil.newURI(scheme,baseRequest.getServerName(),port,baseRequest.getRequestURI(),baseRequest.getQueryString());
response.setContentLength(0);
response.sendRedirect(url);
}
else
{
response.sendError(HttpStatus.FORBIDDEN_403,"Not Secure");
}
baseRequest.setHandled(true);
}
}

View File

@ -85,8 +85,9 @@ public class HashSessionManager extends AbstractSessionManager
}
finally
{
if (_timer != null && _timer.isRunning())
_timer.schedule(this, _scavengePeriodMs, TimeUnit.MILLISECONDS);
if (_timer != null && _timer.isRunning()) {
_task = _timer.schedule(this, _scavengePeriodMs, TimeUnit.MILLISECONDS);
}
}
}
}
@ -111,7 +112,7 @@ public class HashSessionManager extends AbstractSessionManager
finally
{
if (_timer != null && _timer.isRunning())
_timer.schedule(this, _savePeriodMs, TimeUnit.MILLISECONDS);
_saveTask = _timer.schedule(this, _savePeriodMs, TimeUnit.MILLISECONDS);
}
}
}
@ -138,7 +139,7 @@ public class HashSessionManager extends AbstractSessionManager
ServletContext context = ContextHandler.getCurrentContext();
if (context!=null)
_timer = (Scheduler)context.getAttribute("org.eclipse.jetty.server.session.timer");
}
}
if (_timer == null)
{
@ -148,7 +149,7 @@ public class HashSessionManager extends AbstractSessionManager
}
else
addBean(_timer,false);
super.doStart();
setScavengePeriod(getScavengePeriod());
@ -177,12 +178,15 @@ public class HashSessionManager extends AbstractSessionManager
{
if (_saveTask!=null)
_saveTask.cancel();
_saveTask=null;
if (_task!=null)
_task.cancel();
_task=null;
_timer=null;
}
// This will callback invalidate sessions - where we decide if we will save
super.doStop();
@ -314,6 +318,7 @@ public class HashSessionManager extends AbstractSessionManager
_task.cancel();
_task = null;
}
_task = _timer.schedule(new Scavenger(),_scavengePeriodMs, TimeUnit.MILLISECONDS);
}
}

View File

@ -604,7 +604,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
finally
{
if (_scheduler != null && _scheduler.isRunning())
_scheduler.schedule(this, _scavengeIntervalMs, TimeUnit.MILLISECONDS);
_task = _scheduler.schedule(this, _scavengeIntervalMs, TimeUnit.MILLISECONDS);
}
}
}

View File

@ -591,8 +591,11 @@ public class RequestTest
@Override
public boolean check(HttpServletRequest request,HttpServletResponse response) throws IOException
{
request.setCharacterEncoding(StringUtil.__ISO_8859_1);
return "test\u00e4".equals(request.getParameter("name2"));
// Should be "testä"
// "test" followed by a LATIN SMALL LETTER A WITH DIAERESIS
request.setCharacterEncoding(StandardCharsets.ISO_8859_1.name());
String actual = request.getParameter("name2");
return "test\u00e4".equals(actual);
}
};
@ -605,7 +608,8 @@ public class RequestTest
"Connection: close\r\n"+
"\r\n"+
content;
_connector.getResponses(request);
String response = _connector.getResponses(request);
assertThat(response,Matchers.containsString(" 200 OK"));
}
@Test
@ -616,11 +620,15 @@ public class RequestTest
@Override
public boolean check(HttpServletRequest request,HttpServletResponse response) throws IOException
{
return "test\u00e4".equals(request.getParameter("name2"));
// http://www.ltg.ed.ac.uk/~richard/utf-8.cgi?input=00e4&mode=hex
// Should be "testä"
// "test" followed by a LATIN SMALL LETTER A WITH DIAERESIS
String actual = request.getParameter("name2");
return "test\u00e4".equals(actual);
}
};
String content="name1=test&name2=test%C4%A4&name3=&name4=test";
String content="name1=test&name2=test%C3%A4&name3=&name4=test";
String request="POST / HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: "+MimeTypes.Type.FORM_ENCODED.asString()+"\r\n" +
@ -628,7 +636,8 @@ public class RequestTest
"Connection: close\r\n"+
"\r\n"+
content;
_connector.getResponses(request);
String response = _connector.getResponses(request);
assertThat(response,Matchers.containsString(" 200 OK"));
}
@ -749,6 +758,8 @@ public class RequestTest
"Host: myhost\n"+
"Connection: close\n"+
"\n");
assertThat(response,Matchers.containsString(" 302 Found"));
assertThat(response,Matchers.containsString("Location: http://myhost/foo"));
}
@Test
@ -1215,6 +1226,7 @@ public class RequestTest
private class RequestHandler extends AbstractHandler
{
private RequestTester _checker;
@SuppressWarnings("unused")
private String _content;
@Override

View File

@ -0,0 +1,31 @@
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.handler;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class AllowAllVerifier implements HostnameVerifier
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}

View File

@ -0,0 +1,193 @@
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.handler;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
/**
* Testing oddball request scenarios (like error 400) where the error should
* be logged
*/
@RunWith(Parameterized.class)
@Ignore
public class BadRequestLogHandlerTest
{
private static final Logger LOG = Log.getLogger(BadRequestLogHandlerTest.class);
public static class CaptureLog extends AbstractLifeCycle implements RequestLog
{
public List<String> captured = new ArrayList<>();
@Override
public void log(Request request, Response response)
{
captured.add(String.format("%s %s %s %03d",request.getMethod(),request.getUri().toString(),request.getProtocol(),response.getStatus()));
}
}
private static class HelloHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/plain");
response.getWriter().print("Hello World");
baseRequest.setHandled(true);
}
}
@Parameters
public static List<Object[]> data()
{
List<Object[]> data = new ArrayList<>();
data.add(new String[]{ "GET /bad VER\r\n"
+ "Host: localhost\r\n"
+ "Connection: close\r\n\r\n" ,
"GET <invalidrequest> HTTP/1.1 400" });
data.add(new String[]{ "GET /%%adsasd HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Connection: close\r\n\r\n" ,
"GET <invalidrequest> HTTP/1.1 400" });
return data;
}
@Parameter(0)
public String requestHeader;
@Parameter(1)
public String expectedLog;
@Test(timeout=4000)
public void testLogHandler() throws Exception
{
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(0);
server.setConnectors(new Connector[] { connector });
CaptureLog captureLog = new CaptureLog();
RequestLogHandler requestLog = new RequestLogHandler();
requestLog.setRequestLog(captureLog);
requestLog.setHandler(new HelloHandler());
server.setHandler(requestLog);
try
{
server.start();
String host = connector.getHost();
if (host == null)
{
host = "localhost";
}
InetAddress destAddr = InetAddress.getByName(host);
int port = connector.getLocalPort();
SocketAddress endpoint = new InetSocketAddress(destAddr,port);
Socket socket = new Socket();
socket.setSoTimeout(1000);
socket.connect(endpoint);
try(OutputStream out = socket.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out,StandardCharsets.UTF_8);
InputStream in = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(in,StandardCharsets.UTF_8))
{
StringReader request = new StringReader(requestHeader);
IO.copy(request,writer);
writer.flush();
StringWriter response = new StringWriter();
IO.copy(reader,response);
LOG.info("Response: {}",response);
} finally {
socket.close();
}
assertRequestLog(captureLog);
}
finally
{
server.stop();
}
}
private void assertRequestLog(CaptureLog captureLog)
{
int captureCount = captureLog.captured.size();
if (captureCount != 1)
{
LOG.warn("Capture Log size is {}, expected to be 1",captureCount);
if (captureCount > 1)
{
for (int i = 0; i < captureCount; i++)
{
LOG.warn("[{}] {}",i,captureLog.captured.get(i));
}
}
assertThat("Capture Log Entry Count",captureLog.captured.size(),is(1));
}
String actual = captureLog.captured.get(0);
assertThat("Capture Log",actual,is(expectedLog));
}
}

View File

@ -0,0 +1,447 @@
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.handler;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
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.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class RequestLogHandlerTest
{
private static final Logger LOG = Log.getLogger(RequestLogHandlerTest.class);
public static class CaptureLog extends AbstractLifeCycle implements RequestLog
{
public List<String> captured = new ArrayList<>();
@Override
public void log(Request request, Response response)
{
captured.add(String.format("%s %s %s %03d",request.getMethod(),request.getUri().toString(),request.getProtocol(),response.getStatus()));
}
}
private static abstract class AbstractTestHandler extends AbstractHandler
{
@Override
public String toString()
{
return this.getClass().getSimpleName();
}
}
private static class HelloHandler extends AbstractTestHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/plain");
response.getWriter().print("Hello World");
baseRequest.setHandled(true);
}
}
private static class ResponseSendErrorHandler extends AbstractTestHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.sendError(500, "Whoops");
baseRequest.setHandled(true);
}
}
private static class ServletExceptionHandler extends AbstractTestHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
throw new ServletException("Whoops");
}
}
private static class IOExceptionHandler extends AbstractTestHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
throw new IOException("Whoops");
}
}
private static class RuntimeExceptionHandler extends AbstractTestHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
throw new RuntimeException("Whoops");
}
}
private static class AsyncOnTimeoutCompleteHandler extends AbstractTestHandler implements AsyncListener
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
AsyncContext ac = request.startAsync();
ac.setTimeout(1000);
ac.addListener(this);
baseRequest.setHandled(true);
}
@Override
public void onTimeout(AsyncEvent event) throws IOException
{
event.getAsyncContext().complete();
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException
{
}
@Override
public void onError(AsyncEvent event) throws IOException
{
}
@Override
public void onComplete(AsyncEvent event) throws IOException
{
}
}
private static class AsyncOnTimeoutCompleteUnhandledHandler extends AbstractTestHandler implements AsyncListener
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
AsyncContext ac = request.startAsync();
ac.setTimeout(1000);
ac.addListener(this);
}
@Override
public void onTimeout(AsyncEvent event) throws IOException
{
event.getAsyncContext().complete();
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException
{
}
@Override
public void onError(AsyncEvent event) throws IOException
{
}
@Override
public void onComplete(AsyncEvent event) throws IOException
{
}
}
private static class AsyncOnTimeoutDispatchHandler extends AbstractTestHandler implements AsyncListener
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
if(request.getAttribute("deep") == null)
{
AsyncContext ac = request.startAsync();
ac.setTimeout(1000);
ac.addListener(this);
baseRequest.setHandled(true);
request.setAttribute("deep",true);
}
}
@Override
public void onTimeout(AsyncEvent event) throws IOException
{
event.getAsyncContext().dispatch();
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException
{
}
@Override
public void onError(AsyncEvent event) throws IOException
{
}
@Override
public void onComplete(AsyncEvent event) throws IOException
{
}
}
private static class AsyncOnStartIOExceptionHandler extends AbstractTestHandler implements AsyncListener
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
AsyncContext ac = request.startAsync();
ac.setTimeout(1000);
ac.addListener(this);
baseRequest.setHandled(true);
}
@Override
public void onTimeout(AsyncEvent event) throws IOException
{
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException
{
event.getAsyncContext().complete();
throw new IOException("Whoops");
}
@Override
public void onError(AsyncEvent event) throws IOException
{
LOG.warn("onError() -> {}",event);
}
@Override
public void onComplete(AsyncEvent event) throws IOException
{
}
}
@Parameters(name="{0}")
public static List<Object[]> data()
{
List<Object[]> data = new ArrayList<>();
data.add(new Object[] { new HelloHandler(), "/test", "GET /test HTTP/1.1 200" });
data.add(new Object[] { new AsyncOnTimeoutCompleteHandler(), "/test", "GET /test HTTP/1.1 200" });
data.add(new Object[] { new AsyncOnTimeoutCompleteUnhandledHandler(), "/test", "GET /test HTTP/1.1 200" });
data.add(new Object[] { new AsyncOnTimeoutDispatchHandler(), "/test", "GET /test HTTP/1.1 200" });
data.add(new Object[] { new AsyncOnStartIOExceptionHandler(), "/test", "GET /test HTTP/1.1 500" });
data.add(new Object[] { new ResponseSendErrorHandler(), "/test", "GET /test HTTP/1.1 500" });
data.add(new Object[] { new ServletExceptionHandler(), "/test", "GET /test HTTP/1.1 500" });
data.add(new Object[] { new IOExceptionHandler(), "/test", "GET /test HTTP/1.1 500" });
data.add(new Object[] { new RuntimeExceptionHandler(), "/test", "GET /test HTTP/1.1 500" });
return data;
}
@Parameter(0)
public Handler testHandler;
@Parameter(1)
public String requestPath;
@Parameter(2)
public String expectedLogEntry;
@Test(timeout=4000)
@Ignore
public void testLogHandlerCollection() throws Exception
{
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(0);
server.setConnectors(new Connector[] { connector });
CaptureLog captureLog = new CaptureLog();
RequestLogHandler requestLog = new RequestLogHandler();
requestLog.setRequestLog(captureLog);
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] { testHandler, requestLog });
server.setHandler(handlers);
try
{
server.start();
String host = connector.getHost();
if (host == null)
{
host = "localhost";
}
int port = connector.getLocalPort();
URI serverUri = new URI("http",null,host,port,requestPath,null,null);
// Make call to test handler
HttpURLConnection connection = (HttpURLConnection)serverUri.toURL().openConnection();
try
{
connection.setAllowUserInteraction(false);
// log response status code
int statusCode = connection.getResponseCode();
LOG.debug("Response Status Code: {}",statusCode);
if (statusCode == 200)
{
// collect response message and log it
String content = getResponseContent(connection);
LOG.debug("Response Content: {}",content);
}
}
finally
{
connection.disconnect();
}
assertRequestLog(captureLog);
}
finally
{
server.stop();
}
}
@Test(timeout=4000)
public void testLogHandlerWrapped() throws Exception
{
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(0);
server.setConnectors(new Connector[] { connector });
CaptureLog captureLog = new CaptureLog();
RequestLogHandler requestLog = new RequestLogHandler();
requestLog.setRequestLog(captureLog);
requestLog.setHandler(testHandler);
server.setHandler(requestLog);
try
{
server.start();
String host = connector.getHost();
if (host == null)
{
host = "localhost";
}
int port = connector.getLocalPort();
URI serverUri = new URI("http",null,host,port,"/test",null,null);
// Make call to test handler
HttpURLConnection connection = (HttpURLConnection)serverUri.toURL().openConnection();
try
{
connection.setAllowUserInteraction(false);
// log response status code
int statusCode = connection.getResponseCode();
LOG.info("Response Status Code: {}",statusCode);
if (statusCode == 200)
{
// collect response message and log it
String content = getResponseContent(connection);
LOG.info("Response Content: {}",content);
}
}
finally
{
connection.disconnect();
}
assertRequestLog(captureLog);
}
finally
{
server.stop();
}
}
private void assertRequestLog(CaptureLog captureLog)
{
int captureCount = captureLog.captured.size();
if (captureCount != 1)
{
LOG.warn("Capture Log size is {}, expected to be 1",captureCount);
if (captureCount > 1)
{
for (int i = 0; i < captureCount; i++)
{
LOG.warn("[{}] {}",i,captureLog.captured.get(i));
}
}
assertThat("Capture Log Entry Count",captureLog.captured.size(),is(1));
}
String actual = captureLog.captured.get(0);
assertThat("Capture Log",actual,is(expectedLogEntry));
}
private String getResponseContent(HttpURLConnection connection) throws IOException
{
try (InputStream in = connection.getInputStream(); InputStreamReader reader = new InputStreamReader(in))
{
StringWriter writer = new StringWriter();
IO.copy(reader,writer);
return writer.toString();
}
}
}

View File

@ -0,0 +1,288 @@
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.handler;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class SecuredRedirectHandlerTest
{
private static Server server;
private static HostnameVerifier origVerifier;
private static SSLSocketFactory origSsf;
private static URI serverHttpUri;
private static URI serverHttpsUri;
@BeforeClass
public static void startServer() throws Exception
{
// Setup SSL
File keystore = MavenTestingUtils.getTestResourceFile("keystore");
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keystore.getAbsolutePath());
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
sslContextFactory.setTrustStorePath(keystore.getAbsolutePath());
sslContextFactory.setTrustStorePassword("storepwd");
server = new Server();
int port = 32080;
int securePort = 32443;
// Setup HTTP Configuration
HttpConfiguration httpConf = new HttpConfiguration();
httpConf.setSecurePort(securePort);
httpConf.setSecureScheme("https");
ServerConnector httpConnector = new ServerConnector(server,new HttpConnectionFactory(httpConf));
httpConnector.setName("unsecured");
httpConnector.setPort(port);
// Setup HTTPS Configuration
HttpConfiguration httpsConf = new HttpConfiguration(httpConf);
httpsConf.addCustomizer(new SecureRequestCustomizer());
ServerConnector httpsConnector = new ServerConnector(server,new SslConnectionFactory(sslContextFactory,"http/1.1"),new HttpConnectionFactory(httpsConf));
httpsConnector.setName("secured");
httpsConnector.setPort(securePort);
// Add connectors
server.setConnectors(new Connector[] { httpConnector, httpsConnector });
// Wire up contexts
String secureHosts[] = new String[] { "@secured" };
ContextHandler test1Context = new ContextHandler();
test1Context.setContextPath("/test1");
test1Context.setHandler(new HelloHandler("Hello1"));
test1Context.setVirtualHosts(secureHosts);
ContextHandler test2Context = new ContextHandler();
test2Context.setContextPath("/test2");
test2Context.setHandler(new HelloHandler("Hello2"));
test2Context.setVirtualHosts(secureHosts);
ContextHandler rootContext = new ContextHandler();
rootContext.setContextPath("/");
rootContext.setHandler(new RootHandler("/test1","/test2"));
rootContext.setVirtualHosts(secureHosts);
// Wire up context for unsecure handling to only
// the named 'unsecured' connector
ContextHandler redirectHandler = new ContextHandler();
redirectHandler.setContextPath("/");
redirectHandler.setHandler(new SecuredRedirectHandler());
redirectHandler.setVirtualHosts(new String[] { "@unsecured" });
// Establish all handlers that have a context
ContextHandlerCollection contextHandlers = new ContextHandlerCollection();
contextHandlers.setHandlers(new Handler[] { redirectHandler, rootContext, test1Context, test2Context });
// Create server level handler tree
HandlerList handlers = new HandlerList();
handlers.addHandler(contextHandlers);
handlers.addHandler(new DefaultHandler()); // round things out
server.setHandler(handlers);
server.start();
// calculate serverUri
String host = httpConnector.getHost();
if (host == null)
{
host = "localhost";
}
serverHttpUri = new URI(String.format("http://%s:%d/",host,httpConnector.getLocalPort()));
serverHttpsUri = new URI(String.format("https://%s:%d/",host,httpsConnector.getLocalPort()));
origVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
origSsf = HttpsURLConnection.getDefaultSSLSocketFactory();
HttpsURLConnection.setDefaultHostnameVerifier(new AllowAllVerifier());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContextFactory.getSslContext().getSocketFactory());
}
@AfterClass
public static void stopServer() throws Exception
{
HttpsURLConnection.setDefaultSSLSocketFactory(origSsf);
HttpsURLConnection.setDefaultHostnameVerifier(origVerifier);
server.stop();
server.join();
}
@Test
public void testRedirectUnsecuredRoot() throws Exception
{
URL url = serverHttpUri.resolve("/").toURL();
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setAllowUserInteraction(false);
assertThat("response code",connection.getResponseCode(),is(302));
assertThat("location header",connection.getHeaderField("Location"),is(serverHttpsUri.resolve("/").toASCIIString()));
connection.disconnect();
}
@Test
public void testRedirectSecuredRoot() throws Exception
{
URL url = serverHttpsUri.resolve("/").toURL();
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setAllowUserInteraction(false);
assertThat("response code",connection.getResponseCode(),is(200));
String content = getContent(connection);
assertThat("response content",content,containsString("<a href=\"/test1\">"));
connection.disconnect();
}
@Test
public void testAccessUnsecuredHandler() throws Exception
{
URL url = serverHttpUri.resolve("/test1").toURL();
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setAllowUserInteraction(false);
assertThat("response code",connection.getResponseCode(),is(302));
assertThat("location header",connection.getHeaderField("Location"),is(serverHttpsUri.resolve("/test1").toASCIIString()));
connection.disconnect();
}
@Test
public void testAccessUnsecured404() throws Exception
{
URL url = serverHttpUri.resolve("/nothing/here").toURL();
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setAllowUserInteraction(false);
assertThat("response code",connection.getResponseCode(),is(302));
assertThat("location header",connection.getHeaderField("Location"),is(serverHttpsUri.resolve("/nothing/here").toASCIIString()));
connection.disconnect();
}
@Test
public void testAccessSecured404() throws Exception
{
URL url = serverHttpsUri.resolve("/nothing/here").toURL();
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setAllowUserInteraction(false);
assertThat("response code",connection.getResponseCode(),is(404));
connection.disconnect();
}
private String getContent(HttpURLConnection connection) throws IOException
{
try (InputStream in = connection.getInputStream(); InputStreamReader reader = new InputStreamReader(in))
{
StringWriter writer = new StringWriter();
IO.copy(reader,writer);
return writer.toString();
}
}
public static class HelloHandler extends AbstractHandler
{
private final String msg;
public HelloHandler(String msg)
{
this.msg = msg;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/plain");
response.getWriter().printf("%s%n",msg);
baseRequest.setHandled(true);
}
}
public static class RootHandler extends AbstractHandler
{
private final String[] childContexts;
public RootHandler(String... children)
{
this.childContexts = children;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
if (!"/".equals(target))
{
response.sendError(404);
return;
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Contexts</title></head>");
out.println("<body>");
out.println("<h4>Child Contexts</h4>");
out.println("<ul>");
for (String child : childContexts)
{
out.printf("<li><a href=\"%s\">%s</a></li>%n",child,child);
}
out.println("</ul>");
out.println("</body></html>");
baseRequest.setHandled(true);
}
}
}

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.server.ssl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@ -40,6 +41,7 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.AfterClass;
@ -58,12 +60,13 @@ public class SslUploadTest
@BeforeClass
public static void startServer() throws Exception
{
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
File keystore = MavenTestingUtils.getTestResourceFile("keystore");
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keystorePath);
sslContextFactory.setKeyStorePath(keystore.getAbsolutePath());
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
sslContextFactory.setTrustStorePath(keystorePath);
sslContextFactory.setTrustStorePath(keystore.getAbsolutePath());
sslContextFactory.setTrustStorePassword("storepwd");
server = new Server();

View File

@ -60,25 +60,35 @@ import org.eclipse.jetty.util.log.Logger;
/**
* Multipart Form Data Filter.
* <p>
* This class decodes the multipart/form-data stream sent by a HTML form that uses a file input
* This class decodes the <code>multipart/form-data</code> stream sent by a HTML form that uses a file input
* item. Any files sent are stored to a temporary file and a File object added to the request
* as an attribute. All other values are made available via the normal getParameter API and
* the setCharacterEncoding mechanism is respected when converting bytes to Strings.
* <p>
* If the init parameter "delete" is set to "true", any files created will be deleted when the
* current request returns.
* <p>
* The init parameter maxFormKeys sets the maximum number of keys that may be present in a
* form (default set by system property org.eclipse.jetty.server.Request.maxFormKeys or 1000) to protect
* Init Parameters:
* <dl>
* <dt>delete</dt>
* <dd>(boolean)
* If set to "true", any files created will be deleted when the current request returns.</dd>
* <dt>maxFormKeys</dt>
* <dd>(number)
* Sets the maximum number of keys that may be present in a
* form (default set by system property <code>org.eclipse.jetty.server.Request.maxFormKeys</code> or 1000) to protect
* against DOS attacks by bad hash keys.
* <p>
* The init parameter deleteFiles controls if uploaded files are automatically deleted after the request
* completes.
*
* Use init parameter "maxFileSize" to set the max size file that can be uploaded.
*
* Use init parameter "maxRequestSize" to limit the size of the multipart request.
*
* </dd>
* <dt>deleteFiles</dt>
* <dd>(boolean)
* Controls if uploaded files are automatically deleted after the request completes.
* </dd>
* <dt>maxFileSize</dt>
* <dd>(size in bytes)
* Set the max size file that can be uploaded.
* </dd>
* <dt>maxRequestSize</dt>
* <dd>(size in bytes)
* To limit the size of the multipart request.
* </dd>
* </dl>
*/
public class MultiPartFilter implements Filter
{

View File

@ -797,7 +797,7 @@ public class Main
if (args.getProperties().getString("STOP.WAIT") != null)
{
int stopWait = Integer.parseInt(args.getProperties().getString("STOP.PORT"));
int stopWait = Integer.parseInt(args.getProperties().getString("STOP.WAIT"));
stop(stopPort,stopKey,stopWait);
}

View File

@ -42,8 +42,10 @@ public class StringUtil
public static final String ALL_INTERFACES="0.0.0.0";
public static final String CRLF="\015\012";
public static final String __LINE_SEPARATOR=
System.getProperty("line.separator","\n");
/** @deprecated use {@link System#lineSeparator()} instead */
@Deprecated
public static final String __LINE_SEPARATOR = System.lineSeparator();
public static final String __ISO_8859_1="iso-8859-1";
public final static String __UTF8="utf-8";

View File

@ -18,6 +18,7 @@
package org.eclipse.jetty.util.thread;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
@ -38,16 +39,23 @@ public class ScheduledExecutorScheduler extends AbstractLifeCycle implements Sch
private final String name;
private final boolean daemon;
private volatile ScheduledThreadPoolExecutor scheduler;
private ClassLoader classloader;
public ScheduledExecutorScheduler()
{
this(null, false);
}
}
public ScheduledExecutorScheduler(String name, boolean daemon)
{
this (name,daemon, Thread.currentThread().getContextClassLoader());
}
public ScheduledExecutorScheduler(String name, boolean daemon, ClassLoader threadFactoryClassLoader)
{
this.name = name == null ? "Scheduler-" + hashCode() : name;
this.daemon = daemon;
this.classloader = threadFactoryClassLoader;
}
@Override
@ -60,6 +68,7 @@ public class ScheduledExecutorScheduler extends AbstractLifeCycle implements Sch
{
Thread thread = new Thread(r, name);
thread.setDaemon(daemon);
thread.setContextClassLoader(classloader);
return thread;
}
});
@ -67,6 +76,8 @@ public class ScheduledExecutorScheduler extends AbstractLifeCycle implements Sch
super.doStart();
}
@Override
protected void doStop() throws Exception
{
@ -81,6 +92,7 @@ public class ScheduledExecutorScheduler extends AbstractLifeCycle implements Sch
ScheduledFuture<?> result = scheduler.schedule(task, delay, unit);
return new ScheduledFutureTask(result);
}
private class ScheduledFutureTask implements Task
{

View File

@ -27,6 +27,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@ -1249,10 +1250,49 @@ public class StandardDescriptorProcessor extends IterativeDescriptorProcessor
{
String p = iter.next().toString(false, true);
p = normalizePattern(p);
//check if there is already a mapping for this path, and if there is && it is from a defaultdescriptor
//remove it in favour of the new one
ListIterator<ServletMapping> listItor = _servletMappings.listIterator();
boolean found = false;
while (listItor.hasNext() && !found)
{
ServletMapping sm = listItor.next();
if (sm.getPathSpecs() != null)
{
for (String ps:sm.getPathSpecs())
{
if (p.equals(ps) && sm.isDefault())
{
if (LOG.isDebugEnabled()) LOG.debug("{} in mapping {} from defaults descriptor is overridden by ",ps,sm,servletName);
//remove ps from the path specs on the existing mapping
//if the mapping now has no pathspecs, remove it
String[] updatedPaths = ArrayUtil.removeFromArray(sm.getPathSpecs(), ps);
if (updatedPaths == null || updatedPaths.length == 0)
{
if (LOG.isDebugEnabled()) LOG.debug("Removed mapping {} from defaults descriptor",sm);
listItor.remove();
}
else
{
sm.setPathSpecs(updatedPaths);
if (LOG.isDebugEnabled()) LOG.debug("Removed path {} from mapping {} from defaults descriptor ", p,sm);
}
found = true;
break;
}
}
}
}
paths.add(p);
context.getMetaData().setOrigin(servletName+".servlet.mapping."+p, descriptor);
}
mapping.setPathSpecs((String[]) paths.toArray(new String[paths.size()]));
if (LOG.isDebugEnabled()) LOG.debug("Added mapping {} ",mapping);
_servletMappings.add(mapping);
return mapping;
}

View File

@ -50,7 +50,7 @@ public class WebSocketServerContainerInitializer implements ServletContainerInit
* <p>
* Note: this will add the Upgrade filter to the existing list, with no regard for order. It will just be tacked onto the end of the list.
*/
public static ServerContainer configureContext(ServletContextHandler context)
public static ServerContainer configureContext(ServletContextHandler context) throws ServletException
{
// Create Filter
WebSocketUpgradeFilter filter = WebSocketUpgradeFilter.configureContext(context);
@ -70,7 +70,7 @@ public class WebSocketServerContainerInitializer implements ServletContainerInit
* <p>
* This will use Servlet 3.1 techniques on the {@link ServletContext} to add a filter at the start of the filter chain.
*/
public static ServerContainer configureContext(ServletContext context, ServletContextHandler jettyContext)
public static ServerContainer configureContext(ServletContext context, ServletContextHandler jettyContext) throws ServletException
{
// Create Filter
WebSocketUpgradeFilter filter = WebSocketUpgradeFilter.configureContext(context);
@ -84,49 +84,71 @@ public class WebSocketServerContainerInitializer implements ServletContainerInit
return jettyContainer;
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext context) throws ServletException
private boolean isEnabled(Set<Class<?>> c, ServletContext context)
{
Object enable = context.getAttribute(ENABLE_KEY);
// Disable if explicitly disabled
if (TypeUtil.isFalse(enable))
// Try context parameters first
String cp = context.getInitParameter(ENABLE_KEY);
if(TypeUtil.isTrue(cp))
{
if (c.isEmpty())
{
if (LOG.isDebugEnabled())
{
LOG.debug("JSR-356 support disabled via attribute on context {} - {}",context.getContextPath(),context);
}
}
else
{
LOG.warn("JSR-356 support disabled via attribute on context {} - {}",context.getContextPath(),context);
}
return;
// forced on
return true;
}
// Disabled if not explicitly enabled and there are no discovered annotations or interfaces
if (!TypeUtil.isTrue(enable) && c.isEmpty())
if(TypeUtil.isFalse(cp))
{
// forced off
LOG.warn("JSR-356 support disabled via parameter on context {} - {}",context.getContextPath(),context);
return false;
}
// Next, try attribute on context
Object enable = context.getAttribute(ENABLE_KEY);
if(TypeUtil.isTrue(enable))
{
// forced on
return true;
}
if (TypeUtil.isFalse(enable))
{
// forced off
LOG.warn("JSR-356 support disabled via attribute on context {} - {}",context.getContextPath(),context);
return false;
}
// if not forced on or off, determine behavior based on annotations.
if (c.isEmpty())
{
if (LOG.isDebugEnabled())
{
LOG.debug("No JSR-356 annotations or interfaces discovered. JSR-356 support disabled",context.getContextPath(),context);
}
return false;
}
return true;
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext context) throws ServletException
{
if(!isEnabled(c,context))
{
return;
}
ContextHandler handler = ContextHandler.getContextHandler(context);
if (handler == null)
{
throw new ServletException("Not running on Jetty, JSR-356 support disabled");
throw new ServletException("Not running on Jetty, JSR-356 support unavailable");
}
if (!(handler instanceof ServletContextHandler))
{
throw new ServletException("Not running in Jetty ServletContextHandler, JSR-356 support disabled");
throw new ServletException("Not running in Jetty ServletContextHandler, JSR-356 support unavailable");
}
ServletContextHandler jettyContext = (ServletContextHandler)handler;

View File

@ -18,6 +18,7 @@
package org.eclipse.jetty.websocket.jsr356.server.browser;
import javax.servlet.ServletException;
import javax.websocket.DeploymentException;
import org.eclipse.jetty.server.Server;
@ -75,7 +76,7 @@ public class JsrBrowserDebugTool
server.join();
}
private void setupServer(int port) throws DeploymentException
private void setupServer(int port) throws DeploymentException, ServletException
{
server = new Server();
ServerConnector connector = new ServerConnector(server);

View File

@ -43,7 +43,7 @@
</goals>
<configuration>
<instructions>
<Import-Package>javax.servlet.*;version="[3.0,4.0)",org.eclipse.jetty.*;version="[9.0,10.0)",*</Import-Package>
<Import-Package>javax.servlet.*;version="[3.1,4.0)",org.eclipse.jetty.*;version="[9.0,10.0)",*</Import-Package>
<_nouses>true</_nouses>
</instructions>
</configuration>

View File

@ -43,7 +43,6 @@ import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.websocket.api.WebSocketBehavior;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.eclipse.jetty.websocket.server.pathmap.PathMappings;
import org.eclipse.jetty.websocket.server.pathmap.PathMappings.MappedResource;
@ -56,12 +55,21 @@ import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
@ManagedObject("WebSocket Upgrade Filter")
public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter, MappedWebSocketCreator, Dumpable
{
public static final String CONTEXT_ATTRIBUTE_KEY = "contextAttributeKey";
private static final Logger LOG = Log.getLogger(WebSocketUpgradeFilter.class);
public static WebSocketUpgradeFilter configureContext(ServletContextHandler context)
public static WebSocketUpgradeFilter configureContext(ServletContextHandler context) throws ServletException
{
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
WebSocketUpgradeFilter filter = new WebSocketUpgradeFilter(policy);
// Prevent double configure
WebSocketUpgradeFilter filter = (WebSocketUpgradeFilter)context.getAttribute(WebSocketUpgradeFilter.class.getName());
if (filter != null)
{
return filter;
}
// Dynamically add filter
filter = new WebSocketUpgradeFilter();
filter.setToAttribute(context, WebSocketUpgradeFilter.class.getName());
String name = "Jetty_WebSocketUpgradeFilter";
String pathSpec = "/*";
@ -69,6 +77,7 @@ public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter
FilterHolder fholder = new FilterHolder(filter);
fholder.setName(name);
fholder.setInitParameter(CONTEXT_ATTRIBUTE_KEY,WebSocketUpgradeFilter.class.getName());
context.addFilter(fholder,pathSpec,dispatcherTypes);
if (LOG.isDebugEnabled())
@ -76,16 +85,21 @@ public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter
LOG.debug("Adding [{}] {} mapped to {} to {}",name,filter,pathSpec,context);
}
// Store reference to the WebSocketUpgradeFilter
context.setAttribute(WebSocketUpgradeFilter.class.getName(),filter);
return filter;
}
public static WebSocketUpgradeFilter configureContext(ServletContext context)
public static WebSocketUpgradeFilter configureContext(ServletContext context) throws ServletException
{
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
WebSocketUpgradeFilter filter = new WebSocketUpgradeFilter(policy);
// Prevent double configure
WebSocketUpgradeFilter filter = (WebSocketUpgradeFilter)context.getAttribute(WebSocketUpgradeFilter.class.getName());
if (filter != null)
{
return filter;
}
// Dynamically add filter
filter = new WebSocketUpgradeFilter();
filter.setToAttribute(context, WebSocketUpgradeFilter.class.getName());
String name = "Jetty_Dynamic_WebSocketUpgradeFilter";
String pathSpec = "/*";
@ -94,6 +108,7 @@ public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter
String urlPatterns[] = { pathSpec };
FilterRegistration.Dynamic dyn = context.addFilter(name,filter);
dyn.setInitParameter(CONTEXT_ATTRIBUTE_KEY,WebSocketUpgradeFilter.class.getName());
dyn.addMappingForUrlPatterns(dispatcherTypes,isMatchAfter,urlPatterns);
if (LOG.isDebugEnabled())
@ -101,20 +116,19 @@ public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter
LOG.debug("Adding [{}] {} mapped to {} to {}",name,filter,pathSpec,context);
}
// Store reference to the WebSocketUpgradeFilter
context.setAttribute(WebSocketUpgradeFilter.class.getName(),filter);
return filter;
}
private final WebSocketServerFactory factory;
private final PathMappings<WebSocketCreator> pathmap = new PathMappings<>();
private String fname;
private boolean alreadySetToAttribute = false;
public WebSocketUpgradeFilter(WebSocketPolicy policy)
public WebSocketUpgradeFilter()
{
this(policy, new MappedByteBufferPool());
this(WebSocketPolicy.newServerPolicy(),new MappedByteBufferPool());
}
public WebSocketUpgradeFilter(WebSocketPolicy policy, ByteBufferPool bufferPool)
{
factory = new WebSocketServerFactory(policy,bufferPool);
@ -146,6 +160,11 @@ public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter
return;
}
if (LOG.isDebugEnabled())
{
LOG.debug(".doFilter({}) - {}",fname,chain);
}
if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse))
{
HttpServletRequest httpreq = (HttpServletRequest)request;
@ -232,6 +251,8 @@ public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter
@Override
public void init(FilterConfig config) throws ServletException
{
fname = config.getFilterName();
try
{
WebSocketPolicy policy = factory.getPolicy();
@ -260,6 +281,15 @@ public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter
policy.setInputBufferSize(Integer.parseInt(max));
}
String key = config.getInitParameter(CONTEXT_ATTRIBUTE_KEY);
if (key == null)
{
// assume default
key = WebSocketUpgradeFilter.class.getName();
}
setToAttribute(config.getServletContext(), key);
factory.start();
}
catch (Exception x)
@ -267,6 +297,44 @@ public class WebSocketUpgradeFilter extends ContainerLifeCycle implements Filter
throw new ServletException(x);
}
}
private void setToAttribute(ServletContextHandler context, String key) throws ServletException
{
if(alreadySetToAttribute)
{
return;
}
if (context.getAttribute(key) != null)
{
throw new ServletException(WebSocketUpgradeFilter.class.getName() +
" is defined twice for the same context attribute key '" + key
+ "'. Make sure you have different init-param '" +
CONTEXT_ATTRIBUTE_KEY + "' values set");
}
context.setAttribute(key,this);
alreadySetToAttribute = true;
}
public void setToAttribute(ServletContext context, String key) throws ServletException
{
if(alreadySetToAttribute)
{
return;
}
if (context.getAttribute(key) != null)
{
throw new ServletException(WebSocketUpgradeFilter.class.getName() +
" is defined twice for the same context attribute key '" + key
+ "'. Make sure you have different init-param '" +
CONTEXT_ATTRIBUTE_KEY + "' values set");
}
context.setAttribute(key,this);
alreadySetToAttribute = true;
}
@Override
public String toString()

View File

@ -24,7 +24,7 @@
<Bundle-Description>Websocket Servlet Interface</Bundle-Description>
<Bundle-Classpath />
<_nouses>true</_nouses>
<DynamicImport-Package>org.eclipse.jetty.websocket.server.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}"</DynamicImport-Package>
<DynamicImport-Package>org.eclipse.jetty.websocket.server.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}",org.eclipse.jetty.websocket.server.pathmap.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}"</DynamicImport-Package>
</instructions>
</configuration>
</plugin>

View File

@ -34,6 +34,6 @@
<module>test-hash-sessions</module>
<module>test-jdbc-sessions</module>
<!-- Requires mongodb server running -->
<!-- module>test-mongodb-sessions</module -->
<module>test-mongodb-sessions</module>
</modules>
</project>

View File

@ -0,0 +1,163 @@
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.nosql.mongodb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.nosql.NoSqlSession;
import org.eclipse.jetty.server.session.AbstractTestServer;
import org.junit.Test;
/**
* AttributeNameTest
*
* Test that attribute names that have special characters with meaning to mongo (eg ".") are
* properly escaped and not accidentally removed.
* See bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=444595
*/
public class AttributeNameTest
{
public AbstractTestServer createServer(int port, int max, int scavenge)
throws Exception
{
MongoTestServer server = new MongoTestServer(port,max,scavenge,true);
return server;
}
@Test
public void testAttributeNamesWithDots() throws Exception
{
String contextPath = "";
String servletMapping = "/server";
int maxInactivePeriod = 10000;
int scavengePeriod = 20000;
AbstractTestServer server1 = createServer(0,maxInactivePeriod,scavengePeriod);
server1.addContext(contextPath).addServlet(TestServlet.class,servletMapping);
server1.start();
int port1 = server1.getPort();
AbstractTestServer server2 = createServer(0,maxInactivePeriod,scavengePeriod);
server2.addContext(contextPath).addServlet(TestServlet.class,servletMapping);
server2.start();
int port2 = server2.getPort();
try
{
HttpClient client = new HttpClient();
client.start();
try
{
// Perform one request to server1 to create a session with attribute with dotted name
ContentResponse response = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String resp = response.getContentAsString();
String[] sessionTestResponse = resp.split("/");
assertEquals("a.b.c",sessionTestResponse[0]);
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
//Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=","$1\\$Path=");
//Make a request to the 2nd server which will do a refresh, use TestServlet to ensure that the
//session attribute with dotted name is not removed
Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=get");
request2.header("Cookie", sessionCookie);
ContentResponse response2 = request2.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
}
finally
{
client.stop();
}
}
finally
{
server1.stop();
server2.stop();
}
}
public static class TestServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
String action = request.getParameter("action");
if ("init".equals(action))
{
NoSqlSession session = (NoSqlSession)request.getSession(true);
session.setAttribute("a.b.c",System.currentTimeMillis());
sendResult(session,httpServletResponse.getWriter());
}
else
{
NoSqlSession session = (NoSqlSession)request.getSession(false);
assertNotNull(session);
assertNotNull(session.getAttribute("a.b.c"));
sendResult(session,httpServletResponse.getWriter());
}
}
private void sendResult(NoSqlSession session, PrintWriter writer)
{
if (session != null)
{
if (session.getAttribute("a.b.c") != null)
writer.print("a.b.c/"+session.getAttribute("a.b.c"));
else
writer.print("-/0");
}
else
{
writer.print("0/0");
}
}
}
}