Merge remote-tracking branch 'origin/master' into jetty-http2

This commit is contained in:
Greg Wilkins 2014-07-17 11:32:27 +10:00
commit 64e5c1e0ce
35 changed files with 352 additions and 353 deletions

View File

@ -34,7 +34,7 @@ import org.eclipse.jetty.util.log.Logger;
/* ------------------------------------------------------------ */
/** A Parser for 1.0 and 1.1 as defined by RFC7230
* <p>
* The is parser parses HTTP client and server messages from buffers
* This parser parses HTTP client and server messages from buffers
* passed in the {@link #parseNext(ByteBuffer)} method. The parsed
* elements of the HTTP message are passed as event calls to the
* {@link HttpHandler} instance the parser is constructed with.

View File

@ -246,11 +246,9 @@ public class JettyRunForkedMojo extends JettyRunMojo
{
printSystemProperties();
//apply any config from a jetty.xml file first to our "fake" server instance
//TODO probably not necessary
applyJettyXml ();
//do NOT apply the jettyXml configuration - as the jvmArgs may be needed for it to work
//ensure handler structure enabled
server.configureHandlers();
//ensure config of the webapp based on settings in plugin
@ -271,9 +269,10 @@ public class JettyRunForkedMojo extends JettyRunMojo
webApp.setQuickStartWebDescriptor(Resource.newResource(forkWebXml));
//add webapp to our fake server instance
server.addWebApplication(webApp);
//if our server has a thread pool associated we can do any annotation scanning multithreaded,
//if our server has a thread pool associated we can do annotation scanning multithreaded,
//otherwise scanning will be single threaded
QueuedThreadPool tpool = server.getBean(QueuedThreadPool.class);
if (tpool != null)

View File

@ -140,7 +140,7 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co
private final Scheduler _scheduler;
private final ByteBufferPool _byteBufferPool;
private final Thread[] _acceptors;
private final Set<EndPoint> _endpoints = Collections.newSetFromMap(new ConcurrentHashMap());
private final Set<EndPoint> _endpoints = Collections.newSetFromMap(new ConcurrentHashMap<EndPoint, Boolean>());
private final Set<EndPoint> _immutableEndPoints = Collections.unmodifiableSet(_endpoints);
private volatile CountDownLatch _stopping;
private long _idleTimeout = 30000;

View File

@ -103,7 +103,7 @@ public class HttpConfiguration
{
return _customizers;
}
public <T> T getCustomizer(Class<T> type)
{
for (Customizer c : _customizers)

View File

@ -81,7 +81,7 @@ public class InclusiveByteRange
* @param size Size of the resource.
* @return LazyList of satisfiable ranges
*/
public static List<InclusiveByteRange> satisfiableRanges(Enumeration headers, long size)
public static List<InclusiveByteRange> satisfiableRanges(Enumeration<String> headers, long size)
{
Object satRanges=null;
@ -89,7 +89,7 @@ public class InclusiveByteRange
headers:
while (headers.hasMoreElements())
{
String header = (String) headers.nextElement();
String header = headers.nextElement();
StringTokenizer tok = new StringTokenizer(header,"=,",false);
String t=null;
try

View File

@ -606,6 +606,7 @@ public class Server extends HandlerWrapper implements Attributes
/**
* @return The URI of the first {@link NetworkConnector} and first {@link ContextHandler}, or null
*/
@SuppressWarnings("resource")
public URI getURI()
{
NetworkConnector connector=null;

View File

@ -48,126 +48,151 @@ public class ServletRequestHttpWrapper extends ServletRequestWrapper implements
super(request);
}
@Override
public String getAuthType()
{
return null;
}
@Override
public Cookie[] getCookies()
{
return null;
}
@Override
public long getDateHeader(String name)
{
return 0;
}
@Override
public String getHeader(String name)
{
return null;
}
public Enumeration getHeaders(String name)
@Override
public Enumeration<String> getHeaders(String name)
{
return null;
}
public Enumeration getHeaderNames()
@Override
public Enumeration<String> getHeaderNames()
{
return null;
}
@Override
public int getIntHeader(String name)
{
return 0;
}
@Override
public String getMethod()
{
return null;
}
@Override
public String getPathInfo()
{
return null;
}
@Override
public String getPathTranslated()
{
return null;
}
@Override
public String getContextPath()
{
return null;
}
@Override
public String getQueryString()
{
return null;
}
@Override
public String getRemoteUser()
{
return null;
}
@Override
public boolean isUserInRole(String role)
{
return false;
}
@Override
public Principal getUserPrincipal()
{
return null;
}
@Override
public String getRequestedSessionId()
{
return null;
}
@Override
public String getRequestURI()
{
return null;
}
@Override
public StringBuffer getRequestURL()
{
return null;
}
@Override
public String getServletPath()
{
return null;
}
@Override
public HttpSession getSession(boolean create)
{
return null;
}
@Override
public HttpSession getSession()
{
return null;
}
@Override
public boolean isRequestedSessionIdValid()
{
return false;
}
@Override
public boolean isRequestedSessionIdFromCookie()
{
return false;
}
@Override
public boolean isRequestedSessionIdFromURL()
{
return false;
}
@Override
public boolean isRequestedSessionIdFromUrl()
{
return false;
@ -176,6 +201,7 @@ public class ServletRequestHttpWrapper extends ServletRequestWrapper implements
/**
* @see javax.servlet.http.HttpServletRequest#authenticate(javax.servlet.http.HttpServletResponse)
*/
@Override
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException
{
return false;
@ -184,6 +210,7 @@ public class ServletRequestHttpWrapper extends ServletRequestWrapper implements
/**
* @see javax.servlet.http.HttpServletRequest#getPart(java.lang.String)
*/
@Override
public Part getPart(String name) throws IOException, ServletException
{
return null;
@ -192,6 +219,7 @@ public class ServletRequestHttpWrapper extends ServletRequestWrapper implements
/**
* @see javax.servlet.http.HttpServletRequest#getParts()
*/
@Override
public Collection<Part> getParts() throws IOException, ServletException
{
return null;
@ -200,6 +228,7 @@ public class ServletRequestHttpWrapper extends ServletRequestWrapper implements
/**
* @see javax.servlet.http.HttpServletRequest#login(java.lang.String, java.lang.String)
*/
@Override
public void login(String username, String password) throws ServletException
{
@ -208,6 +237,7 @@ public class ServletRequestHttpWrapper extends ServletRequestWrapper implements
/**
* @see javax.servlet.http.HttpServletRequest#logout()
*/
@Override
public void logout() throws ServletException
{

View File

@ -54,20 +54,18 @@ public class ShutdownMonitor
}
/**
* ShutdownMonitorThread
* ShutdownMonitorRunnable
*
* Thread for listening to STOP.PORT for command to stop Jetty.
* If ShowndownMonitor.exitVm is true, then Sytem.exit will also be
* called after the stop.
*
*/
public class ShutdownMonitorThread extends Thread
private class ShutdownMonitorRunnable implements Runnable
{
public ShutdownMonitorThread ()
public ShutdownMonitorRunnable()
{
setDaemon(true);
setName("ShutdownMonitor");
startListenSocket();
}
@Override
@ -102,7 +100,7 @@ public class ShutdownMonitor
// Graceful Shutdown
debug("Issuing graceful shutdown..");
ShutdownThread.getInstance().run();
//Stop accepting any more
close(serverSocket);
serverSocket = null;
@ -148,28 +146,7 @@ public class ShutdownMonitor
}
}
public void start()
{
if (isAlive())
{
// TODO why are we reentrant here?
if (DEBUG)
System.err.printf("ShutdownMonitorThread already started");
return; // cannot start it again
}
startListenSocket();
if (serverSocket == null)
{
return;
}
if (DEBUG)
System.err.println("Starting ShutdownMonitorThread");
super.start();
}
private void startListenSocket()
public void startListenSocket()
{
if (port < 0)
{
@ -217,9 +194,7 @@ public class ShutdownMonitor
private String key;
private boolean exitVm;
private ServerSocket serverSocket;
private ShutdownMonitorThread thread;
private Thread thread;
/**
* Create a ShutdownMonitor using configuration from the System properties.
@ -372,18 +347,20 @@ public class ShutdownMonitor
protected void start() throws Exception
{
ShutdownMonitorThread t = null;
Thread t = null;
synchronized (this)
{
if (thread != null && thread.isAlive())
{
// TODO why are we reentrant here?
if (DEBUG)
System.err.printf("ShutdownMonitorThread already started");
return; // cannot start it again
}
thread = new ShutdownMonitorThread();
thread = new Thread(new ShutdownMonitorRunnable());
thread.setDaemon(true);
thread.setName("ShutdownMonitor");
t = thread;
}

View File

@ -58,6 +58,7 @@ public abstract class AbstractHandlerContainer extends AbstractHandler implement
}
/* ------------------------------------------------------------ */
@SuppressWarnings("unchecked")
@Override
public <T extends Handler> T getChildHandlerByClass(Class<T> byclass)
{
@ -103,6 +104,7 @@ public abstract class AbstractHandlerContainer extends AbstractHandler implement
{
for (Handler h:branches)
{
@SuppressWarnings("unchecked")
T container = (T)h;
Handler[] candidates = container.getChildHandlersByClass(handler.getClass());
if (candidates!=null)

View File

@ -36,7 +36,6 @@ 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;
@ -107,7 +106,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
{
public final static int SERVLET_MAJOR_VERSION=3;
public final static int SERVLET_MINOR_VERSION=0;
public static final Class[] SERVLET_LISTENER_TYPES = new Class[] {ServletContextListener.class,
public static final Class<?>[] SERVLET_LISTENER_TYPES = new Class[] {ServletContextListener.class,
ServletContextAttributeListener.class,
ServletRequestListener.class,
ServletRequestAttributeListener.class};
@ -509,8 +508,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
/*
* @see javax.servlet.ServletContext#getInitParameterNames()
*/
@SuppressWarnings("rawtypes")
public Enumeration getInitParameterNames()
public Enumeration<String> getInitParameterNames()
{
return Collections.enumeration(_initParams.keySet());
}
@ -1128,7 +1126,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
if (!_requestAttributeListeners.isEmpty())
{
ListIterator<ServletRequestAttributeListener> iter = _requestAttributeListeners.listIterator(_requestAttributeListeners.size());
for (int i=_requestAttributeListeners.size();i-->0;)
baseRequest.removeEventListener(_requestAttributeListeners.get(i));
}
@ -1884,7 +1881,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
matched_path = context_path;
}
if (matched_path.equals(context_path))
if (matched_path != null && matched_path.equals(context_path))
contexts.add(ch);
}
}
@ -2062,7 +2059,6 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
/*
* @see javax.servlet.ServletContext#getInitParameterNames()
*/
@SuppressWarnings("unchecked")
@Override
public Enumeration<String> getInitParameterNames()
{
@ -2199,6 +2195,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
try
{
@SuppressWarnings("unchecked")
Class<? extends EventListener> clazz = _classLoader==null?Loader.loadClass(ContextHandler.class,className):_classLoader.loadClass(className);
addListener(clazz);
}
@ -2293,9 +2290,9 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
//classloader, or a parent of it
try
{
Class reflect = Loader.loadClass(getClass(), "sun.reflect.Reflection");
Class<?> reflect = Loader.loadClass(getClass(), "sun.reflect.Reflection");
Method getCallerClass = reflect.getMethod("getCallerClass", Integer.TYPE);
Class caller = (Class)getCallerClass.invoke(null, 2);
Class<?> caller = (Class<?>)getCallerClass.invoke(null, 2);
boolean ok = false;
ClassLoader callerLoader = caller.getClassLoader();

View File

@ -117,62 +117,63 @@ public class DefaultHandler extends AbstractHandler
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.setContentType(MimeTypes.Type.TEXT_HTML.toString());
ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
writer.write("<HTML>\n<HEAD>\n<TITLE>Error 404 - Not Found");
writer.write("</TITLE>\n<BODY>\n<H2>Error 404 - Not Found.</H2>\n");
writer.write("No context on this server matched or handled this request.<BR>");
writer.write("Contexts known to this server are: <ul>");
Server server = getServer();
Handler[] handlers = server==null?null:server.getChildHandlersByClass(ContextHandler.class);
for (int i=0;handlers!=null && i<handlers.length;i++)
try (ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);)
{
ContextHandler context = (ContextHandler)handlers[i];
if (context.isRunning())
{
writer.write("<li><a href=\"");
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("http://"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write(context.getContextPath());
if (context.getContextPath().length()>1 && context.getContextPath().endsWith("/"))
writer.write("/");
writer.write("\">");
writer.write(context.getContextPath());
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write("&nbsp;--->&nbsp;");
writer.write(context.toString());
writer.write("</a></li>\n");
}
else
{
writer.write("<li>");
writer.write(context.getContextPath());
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write("&nbsp;--->&nbsp;");
writer.write(context.toString());
if (context.isFailed())
writer.write(" [failed]");
if (context.isStopped())
writer.write(" [stopped]");
writer.write("</li>\n");
}
}
writer.write("<HTML>\n<HEAD>\n<TITLE>Error 404 - Not Found");
writer.write("</TITLE>\n<BODY>\n<H2>Error 404 - Not Found.</H2>\n");
writer.write("No context on this server matched or handled this request.<BR>");
writer.write("Contexts known to this server are: <ul>");
writer.write("</ul><hr>");
writer.write("<a href=\"http://eclipse.org/jetty\"><img border=0 src=\"/favicon.ico\"/></a>&nbsp;");
writer.write("<a href=\"http://eclipse.org/jetty\">Powered by Jetty:// Java Web Server</a><hr/>\n");
Server server = getServer();
Handler[] handlers = server==null?null:server.getChildHandlersByClass(ContextHandler.class);
writer.write("\n</BODY>\n</HTML>\n");
writer.flush();
response.setContentLength(writer.size());
try (OutputStream out=response.getOutputStream())
{
writer.writeTo(out);
}
for (int i=0;handlers!=null && i<handlers.length;i++)
{
ContextHandler context = (ContextHandler)handlers[i];
if (context.isRunning())
{
writer.write("<li><a href=\"");
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("http://"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write(context.getContextPath());
if (context.getContextPath().length()>1 && context.getContextPath().endsWith("/"))
writer.write("/");
writer.write("\">");
writer.write(context.getContextPath());
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write("&nbsp;--->&nbsp;");
writer.write(context.toString());
writer.write("</a></li>\n");
}
else
{
writer.write("<li>");
writer.write(context.getContextPath());
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write("&nbsp;--->&nbsp;");
writer.write(context.toString());
if (context.isFailed())
writer.write(" [failed]");
if (context.isStopped())
writer.write(" [stopped]");
writer.write("</li>\n");
}
}
writer.write("</ul><hr>");
writer.write("<a href=\"http://eclipse.org/jetty\"><img border=0 src=\"/favicon.ico\"/></a>&nbsp;");
writer.write("<a href=\"http://eclipse.org/jetty\">Powered by Jetty:// Java Web Server</a><hr/>\n");
writer.write("\n</BODY>\n</HTML>\n");
writer.flush();
response.setContentLength(writer.size());
try (OutputStream out=response.getOutputStream())
{
writer.writeTo(out);
}
}
}
/* ------------------------------------------------------------ */

View File

@ -133,6 +133,7 @@ public class ShutdownHandler extends HandlerWrapper
}
}
@SuppressWarnings("resource")
private String getServerUrl()
{
NetworkConnector connector=null;

View File

@ -397,7 +397,6 @@ public abstract class AbstractSession implements AbstractSessionManager.SessionI
}
/* ------------------------------------------------------------ */
@SuppressWarnings({ "unchecked" })
@Override
public Enumeration<String> getAttributeNames()
{

View File

@ -227,10 +227,10 @@ public abstract class AbstractSessionManager extends ContainerLifeCycle implemen
_context=ContextHandler.getCurrentContext();
_loader=Thread.currentThread().getContextClassLoader();
if (_sessionIdManager==null)
final Server server=getSessionHandler().getServer();
synchronized (server)
{
final Server server=getSessionHandler().getServer();
synchronized (server)
if (_sessionIdManager==null)
{
_sessionIdManager=server.getSessionIdManager();
if (_sessionIdManager==null)

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.server.session;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@ -36,7 +35,6 @@ import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.ClassLoadingObjectInputStream;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.eclipse.jetty.util.thread.Scheduler;
@ -307,9 +305,9 @@ public class HashSessionManager extends AbstractSessionManager
_scavengePeriodMs=period;
if (_timer!=null && (period!=old_period || _task==null))
synchronized (this)
{
synchronized (this)
if (_timer!=null && (period!=old_period || _task==null))
{
if (_task!=null)
{
@ -568,18 +566,22 @@ public class HashSessionManager extends AbstractSessionManager
{
File file = new File(_storeDir,idInCuster);
FileInputStream in = null;
Exception error = null;
try
if (!file.exists())
{
if (file.exists())
if (LOG.isDebugEnabled())
{
in = new FileInputStream(file);
HashedSession session = restoreSession(in, null);
addSession(session, false);
session.didActivate();
return session;
LOG.debug("Not loading: {}",file);
}
return null;
}
try (FileInputStream in = new FileInputStream(file))
{
HashedSession session = restoreSession(in,null);
addSession(session,false);
session.didActivate();
return session;
}
catch (Exception e)
{
@ -587,8 +589,6 @@ public class HashSessionManager extends AbstractSessionManager
}
finally
{
if (in != null) IO.close(in);
if (error != null)
{
if (isDeleteUnrestorableSessions() && file.exists() && file.getParentFile().equals(_storeDir) )
@ -602,7 +602,10 @@ public class HashSessionManager extends AbstractSessionManager
}
}
else
file.delete(); //delete successfully restored file
{
// delete successfully restored file
file.delete();
}
}
return null;
}
@ -640,8 +643,10 @@ public class HashSessionManager extends AbstractSessionManager
if (session == null)
session = (HashedSession)newSession(created, accessed, clusterId);
session.setRequests(requests);
// Attributes
int size = di.readInt();
restoreSessionAttributes(di, size, session);
@ -651,7 +656,7 @@ public class HashSessionManager extends AbstractSessionManager
int maxIdle = di.readInt();
session.setMaxInactiveInterval(maxIdle);
}
catch (EOFException e)
catch (IOException e)
{
LOG.debug("No maxInactiveInterval persisted for session "+clusterId);
LOG.ignore(e);
@ -660,12 +665,14 @@ public class HashSessionManager extends AbstractSessionManager
return session;
}
@SuppressWarnings("resource")
private void restoreSessionAttributes (InputStream is, int size, HashedSession session)
throws Exception
{
if (size>0)
{
// input stream should not be closed here
ClassLoadingObjectInputStream ois = new ClassLoadingObjectInputStream(is);
for (int i=0; i<size;i++)
{

View File

@ -145,24 +145,23 @@ public class HashedSession extends MemSession
throws Exception
{
File file = null;
FileOutputStream fos = null;
if (!_saveFailed && _hashSessionManager._storeDir != null)
{
try
file = new File(_hashSessionManager._storeDir, super.getId());
if (file.exists())
{
file.delete();
}
try(FileOutputStream fos = new FileOutputStream(file,false))
{
file = new File(_hashSessionManager._storeDir, super.getId());
if (file.exists())
file.delete();
file.createNewFile();
fos = new FileOutputStream(file);
save(fos);
IO.close(fos);
}
catch (Exception e)
{
saveFailed(); // We won't try again for this session
if (fos != null) IO.close(fos);
if (file != null) file.delete(); // No point keeping the file if we didn't save the whole session
if (file != null)
file.delete(); // No point keeping the file if we didn't save the whole session
throw e;
}
}

View File

@ -778,10 +778,10 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
if (LOG.isDebugEnabled())
LOG.debug("Scavenging every "+_scavengeIntervalMs+" ms");
//if (_timer!=null && (period!=old_period || _task==null))
if (_scheduler != null && (period!=old_period || _task==null))
synchronized (this)
{
synchronized (this)
//if (_timer!=null && (period!=old_period || _task==null))
if (_scheduler != null && (period!=old_period || _task==null))
{
if (_task!=null)
_task.cancel();

View File

@ -49,10 +49,12 @@ public class SessionHandler extends ScopedHandler
final static Logger LOG = Log.getLogger("org.eclipse.jetty.server.session");
public final static EnumSet<SessionTrackingMode> DEFAULT_TRACKING = EnumSet.of(SessionTrackingMode.COOKIE,SessionTrackingMode.URL);
public static final Class[] SESSION_LISTENER_TYPES = new Class[] {HttpSessionAttributeListener.class,
HttpSessionIdListener.class,
HttpSessionListener.class};
@SuppressWarnings("unchecked")
public static final Class<? extends EventListener>[] SESSION_LISTENER_TYPES =
new Class[] {HttpSessionAttributeListener.class,
HttpSessionIdListener.class,
HttpSessionListener.class};

View File

@ -26,43 +26,36 @@ import java.io.LineNumberReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
/**
* ShutdownMonitorTest
*
*
*
*/
public class ShutdownMonitorTest
{
@Test
public void testShutdown ()
throws Exception
public void testShutdown() throws Exception
{
//test port and key assignment
// test port and key assignment
ShutdownMonitor.getInstance().setPort(0);
ShutdownMonitor.getInstance().setExitVm(false);
ShutdownMonitor.getInstance().start();
String key = ShutdownMonitor.getInstance().getKey();
int port = ShutdownMonitor.getInstance().getPort();
//try starting a 2nd time (should be ignored)
ShutdownMonitor.getInstance().start();
// try starting a 2nd time (should be ignored)
ShutdownMonitor.getInstance().start();
stop(port,key,true);
assertTrue(!ShutdownMonitor.getInstance().isAlive());
//should be able to change port and key because it is stopped
// should be able to change port and key because it is stopped
ShutdownMonitor.getInstance().setPort(0);
ShutdownMonitor.getInstance().setKey("foo");
ShutdownMonitor.getInstance().setKey("foo");
ShutdownMonitor.getInstance().start();
key = ShutdownMonitor.getInstance().getKey();
port = ShutdownMonitor.getInstance().getPort();
assertTrue(ShutdownMonitor.getInstance().isAlive());
@ -71,41 +64,34 @@ public class ShutdownMonitorTest
assertTrue(!ShutdownMonitor.getInstance().isAlive());
}
public void stop (int port, String key, boolean check)
throws Exception
public void stop(int port, String key, boolean check) throws Exception
{
Socket s = null;
try
System.out.printf("Attempting stop to localhost:%d (%b)%n",port,check);
try (Socket s = new Socket(InetAddress.getByName("127.0.0.1"),port))
{
//send stop command
s = new Socket(InetAddress.getByName("127.0.0.1"),port);
OutputStream out = s.getOutputStream();
out.write((key + "\r\nstop\r\n").getBytes());
out.flush();
if (check)
// send stop command
try (OutputStream out = s.getOutputStream())
{
//wait a little
Thread.currentThread().sleep(600);
out.write((key + "\r\nstop\r\n").getBytes());
out.flush();
//check for stop confirmation
LineNumberReader lin = new LineNumberReader(new InputStreamReader(s.getInputStream()));
String response;
if ((response = lin.readLine()) != null)
if (check)
{
assertEquals("Stopped", response);
// wait a little
TimeUnit.MILLISECONDS.sleep(600);
// check for stop confirmation
LineNumberReader lin = new LineNumberReader(new InputStreamReader(s.getInputStream()));
String response;
if ((response = lin.readLine()) != null)
{
assertEquals("Stopped",response);
}
else
throw new IllegalStateException("No stop confirmation");
}
else
throw new IllegalStateException("No stop confirmation");
}
}
finally
{
if (s != null) s.close();
}
}
}

View File

@ -22,6 +22,7 @@ import java.io.File;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.Log;
@ -33,24 +34,6 @@ import org.junit.Test;
public class HashSessionManagerTest
{
@After
public void enableStacks()
{
enableStacks(true);
}
@Before
public void quietStacks()
{
enableStacks(false);
}
protected void enableStacks(boolean enabled)
{
StdErrLog log = (StdErrLog)Log.getLogger("org.eclipse.jetty.server.session");
log.setHideStacks(!enabled);
}
@Test
public void testDangerousSessionIdRemoval() throws Exception
{
@ -78,7 +61,8 @@ public class HashSessionManagerTest
manager.setDeleteUnrestorableSessions(true);
manager.setLazyLoad(true);
File testDir = MavenTestingUtils.getTargetTestingDir("hashes");
testDir.mkdirs();
FS.ensureEmpty(testDir);
manager.setStoreDirectory(testDir);
Assert.assertTrue(new File(testDir, "validFile.session").createNewFile());
@ -88,7 +72,6 @@ public class HashSessionManagerTest
manager.getSession("validFile.session");
Assert.assertTrue("File shouldn't exist!", !new File(testDir,"validFile.session").exists());
}
@Test
@ -116,7 +99,6 @@ public class HashSessionManagerTest
server.start();
manager.start();
HashedSession session = (HashedSession)manager.newHttpSession(new Request(null, null));
String sessionId = session.getId();
@ -124,7 +106,7 @@ public class HashSessionManagerTest
session.setAttribute("two", new Integer(2));
//stop will persist sessions
manager.setMaxInactiveInterval(30); //change max inactive interval for *new* sessions
manager.setMaxInactiveInterval(30); // change max inactive interval for *new* sessions
manager.stop();
Assert.assertTrue("File should exist!", new File(testDir, session.getId()).exists());

View File

@ -263,11 +263,11 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
try
{
if (_cache==null && max_cached_files>0)
if (_cache==null && (max_cached_files!=-2 || max_cache_size!=-2 || max_cached_file_size!=-2))
{
_cache= new ResourceCache(null,this,_mimeTypes,_useFileMappedBuffer,_etags);
if (max_cache_size>0)
if (max_cache_size>=0)
_cache.setMaxCacheSize(max_cache_size);
if (max_cached_file_size>=-1)
_cache.setMaxCachedFileSize(max_cached_file_size);
@ -294,19 +294,19 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
}
else
{
//.svgz files are gzipped svg files and must be served with Content-Encoding:gzip
_gzipEquivalentFileExtensions.add(".svgz");
}
{
//.svgz files are gzipped svg files and must be served with Content-Encoding:gzip
_gzipEquivalentFileExtensions.add(".svgz");
}
_servletHandler= _contextHandler.getChildHandlerByClass(ServletHandler.class);
for (ServletHolder h :_servletHandler.getServlets())
if (h.getServletInstance()==this)
_defaultHolder=h;
_servletHandler= _contextHandler.getChildHandlerByClass(ServletHandler.class);
for (ServletHolder h :_servletHandler.getServlets())
if (h.getServletInstance()==this)
_defaultHolder=h;
if (LOG.isDebugEnabled())
LOG.debug("resource base = "+_resourceBase);
if (LOG.isDebugEnabled())
LOG.debug("resource base = "+_resourceBase);
}
/**

View File

@ -89,7 +89,7 @@ public class Holder<T> extends BaseHolder<T>
}
/* ------------------------------------------------------------ */
public Enumeration getInitParameterNames()
public Enumeration<String> getInitParameterNames()
{
if (_initParams==null)
return Collections.enumeration(Collections.EMPTY_LIST);
@ -227,7 +227,7 @@ public class Holder<T> extends BaseHolder<T>
}
/* -------------------------------------------------------- */
public Enumeration getInitParameterNames()
public Enumeration<String> getInitParameterNames()
{
return Holder.this.getInitParameterNames();
}

View File

@ -72,8 +72,8 @@ public class Invoker extends HttpServlet
private ContextHandler _contextHandler;
private ServletHandler _servletHandler;
private Map.Entry _invokerEntry;
private Map _parameters;
private Map.Entry<String, ServletHolder> _invokerEntry;
private Map<String, String> _parameters;
private boolean _nonContextServlets;
private boolean _verbose;
@ -87,10 +87,10 @@ public class Invoker extends HttpServlet
while (handler!=null && !(handler instanceof ServletHandler) && (handler instanceof HandlerWrapper))
handler=((HandlerWrapper)handler).getHandler();
_servletHandler = (ServletHandler)handler;
Enumeration e = getInitParameterNames();
Enumeration<String> e = getInitParameterNames();
while(e.hasMoreElements())
{
String param=(String)e.nextElement();
String param=e.nextElement();
String value=getInitParameter(param);
String lvalue=value.toLowerCase(Locale.ENGLISH);
if ("nonContextServlets".equals(param))
@ -104,7 +104,7 @@ public class Invoker extends HttpServlet
else
{
if (_parameters==null)
_parameters=new HashMap();
_parameters=new HashMap<String, String>();
_parameters.put(param,value);
}
}
@ -151,7 +151,7 @@ public class Invoker extends HttpServlet
ServletMapping mapping = new ServletMapping();
mapping.setServletName(servlet);
mapping.setPathSpec(URIUtil.addPaths(servlet_path,servlet)+"/*");
_servletHandler.setServletMappings((ServletMapping[])ArrayUtil.addToArray(_servletHandler.getServletMappings(), mapping, ServletMapping.class));
_servletHandler.setServletMappings(ArrayUtil.addToArray(_servletHandler.getServletMappings(), mapping, ServletMapping.class));
}
else
{
@ -171,7 +171,7 @@ public class Invoker extends HttpServlet
// Check for existing mapping (avoid threaded race).
String path=URIUtil.addPaths(servlet_path,servlet);
Map.Entry entry = _servletHandler.getHolderEntry(path);
Map.Entry<String, ServletHolder> entry = _servletHandler.getHolderEntry(path);
if (entry!=null && !entry.equals(_invokerEntry))
{

View File

@ -125,9 +125,12 @@ public class ServletHandler extends ScopedHandler
private ListenerHolder[] _listeners=new ListenerHolder[0];
protected final ConcurrentMap<?, ?> _chainCache[] = new ConcurrentMap[FilterMapping.ALL];
protected final Queue<?>[] _chainLRU = new Queue[FilterMapping.ALL];
@SuppressWarnings("unchecked")
protected final ConcurrentMap<String, FilterChain> _chainCache[] = new ConcurrentMap[FilterMapping.ALL];
@SuppressWarnings("unchecked")
protected final Queue<String>[] _chainLRU = new Queue[FilterMapping.ALL];
/* ------------------------------------------------------------ */
@ -745,8 +748,8 @@ public class ServletHandler extends ScopedHandler
if (filters.size() > 0)
chain= new CachedChain(filters, servletHolder);
final Map<String,FilterChain> cache=(Map<String, FilterChain>)_chainCache[dispatch];
final Queue<String> lru=(Queue<String>)_chainLRU[dispatch];
final Map<String,FilterChain> cache=_chainCache[dispatch];
final Queue<String> lru=_chainLRU[dispatch];
// Do we have too many cached chains?
while (_maxFilterChainsCacheSize>0 && cache.size()>=_maxFilterChainsCacheSize)

View File

@ -796,7 +796,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
if (_servlet == null)
return false;
Class c = _servlet.getClass();
Class<?> c = _servlet.getClass();
boolean result = false;
while (c != null && !result)
@ -828,7 +828,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
jsp = jsp.substring(i);
try
{
Class jspUtil = Loader.loadClass(Holder.class, "org.apache.jasper.compiler.JspUtil");
Class<?> jspUtil = Loader.loadClass(Holder.class, "org.apache.jasper.compiler.JspUtil");
Method makeJavaIdentifier = jspUtil.getMethod("makeJavaIdentifier", String.class);
return (String)makeJavaIdentifier.invoke(null, jsp);
}
@ -854,7 +854,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
return "";
try
{
Class jspUtil = Loader.loadClass(Holder.class, "org.apache.jasper.compiler.JspUtil");
Class<?> jspUtil = Loader.loadClass(Holder.class, "org.apache.jasper.compiler.JspUtil");
Method makeJavaPackage = jspUtil.getMethod("makeJavaPackage", String.class);
return (String)makeJavaPackage.invoke(null, jsp.substring(0,i));
}

View File

@ -98,7 +98,7 @@ public class ServletTester extends ContainerLifeCycle
return _context.getAttribute(name);
}
public Enumeration getAttributeNames()
public Enumeration<String> getAttributeNames()
{
return _context.getAttributeNames();
}
@ -123,7 +123,7 @@ public class ServletTester extends ContainerLifeCycle
return _context.setInitParameter(name,value);
}
public Enumeration getInitParameterNames()
public Enumeration<String> getInitParameterNames()
{
return _context.getInitParameterNames();
}

View File

@ -52,7 +52,7 @@ public class ELContextCleaner implements ServletContextListener
try
{
//Check that the BeanELResolver class is on the classpath
Class beanELResolver = Loader.loadClass(this.getClass(), "javax.el.BeanELResolver");
Class<?> beanELResolver = Loader.loadClass(this.getClass(), "javax.el.BeanELResolver");
//Get a reference via reflection to the properties field which is holding class references
Field field = getField(beanELResolver);
@ -80,7 +80,7 @@ public class ELContextCleaner implements ServletContextListener
}
protected Field getField (Class beanELResolver)
protected Field getField (Class<?> beanELResolver)
throws SecurityException, NoSuchFieldException
{
if (beanELResolver == null)
@ -98,14 +98,14 @@ public class ELContextCleaner implements ServletContextListener
if (!properties.isAccessible())
properties.setAccessible(true);
ConcurrentHashMap map = (ConcurrentHashMap) properties.get(null);
ConcurrentHashMap<Class<?>, Object> map = (ConcurrentHashMap<Class<?>, Object>) properties.get(null);
if (map == null)
return;
Iterator<Class> itor = map.keySet().iterator();
Iterator<Class<?>> itor = map.keySet().iterator();
while (itor.hasNext())
{
Class clazz = itor.next();
Class<?> clazz = itor.next();
if (LOG.isDebugEnabled())
LOG.debug("Clazz: "+clazz+" loaded by "+clazz.getClassLoader());
if (Thread.currentThread().getContextClassLoader().equals(clazz.getClassLoader()))

View File

@ -71,7 +71,7 @@ public class ArrayTernaryTrie<V> extends AbstractTrie<V>
* The value (if any) for a Trie row.
* A row may be a leaf, a node or both in the Trie tree.
*/
private final Object[] _value;
private final V[] _value;
/**
* The number of rows allocated
@ -96,7 +96,7 @@ public class ArrayTernaryTrie<V> extends AbstractTrie<V>
public ArrayTernaryTrie(boolean insensitive, int capacityInNodes)
{
super(insensitive);
_value=new Object[capacityInNodes];
_value=(V[])new Object[capacityInNodes];
_tree=new char[capacityInNodes*ROW_SIZE];
_key=new String[capacityInNodes];
}
@ -216,7 +216,7 @@ public class ArrayTernaryTrie<V> extends AbstractTrie<V>
}
}
return (V)_value[t];
return _value[t];
}

View File

@ -79,7 +79,7 @@ public class ArrayTrie<V> extends AbstractTrie<V>
* The value (if any) for a Trie row.
* A row may be a leaf, a node or both in the Trie tree.
*/
private final Object[] _value;
private final V[] _value;
/**
* A big index for each row.
@ -102,7 +102,7 @@ public class ArrayTrie<V> extends AbstractTrie<V>
public ArrayTrie(int capacityInNodes)
{
super(true);
_value=new Object[capacityInNodes];
_value=(V[])new Object[capacityInNodes];
_rowIndex=new char[capacityInNodes*32];
_key=new String[capacityInNodes];
}
@ -183,7 +183,7 @@ public class ArrayTrie<V> extends AbstractTrie<V>
return null;
}
}
return (V)_value[t];
return _value[t];
}
/* ------------------------------------------------------------ */
@ -374,7 +374,7 @@ public class ArrayTrie<V> extends AbstractTrie<V>
}
private <V> void toString(Appendable out, int t)
private void toString(Appendable out, int t)
{
if (_value[t]!=null)
{

View File

@ -71,10 +71,10 @@ public class ClassLoadingObjectInputStream extends ObjectInputStream
boolean hasNonPublicInterface = false;
// define proxy in class loader of non-public interface(s), if any
Class[] classObjs = new Class[interfaces.length];
Class<?>[] classObjs = new Class[interfaces.length];
for (int i = 0; i < interfaces.length; i++)
{
Class cl = Class.forName(interfaces[i], false, loader);
Class<?> cl = Class.forName(interfaces[i], false, loader);
if ((cl.getModifiers() & Modifier.PUBLIC) == 0)
{
if (hasNonPublicInterface)

View File

@ -166,6 +166,7 @@ public class ConcurrentArrayQueue<T> extends AbstractQueue<T>
return _blocks.compareAndSet(TAIL_OFFSET,current,update);
}
@SuppressWarnings("unchecked")
@Override
public T poll()
{
@ -274,7 +275,7 @@ public class ConcurrentArrayQueue<T> extends AbstractQueue<T>
}
else
{
Object element = currentHeadBlock.peek(head);
T element = currentHeadBlock.peek(head);
if (element == REMOVED_ELEMENT)
{
// Already removed, try next index
@ -282,7 +283,7 @@ public class ConcurrentArrayQueue<T> extends AbstractQueue<T>
}
else
{
return (T)element;
return element;
}
}
}
@ -419,8 +420,11 @@ public class ConcurrentArrayQueue<T> extends AbstractQueue<T>
advance();
if (element != REMOVED_ELEMENT)
return (T)element;
if (element != REMOVED_ELEMENT) {
@SuppressWarnings("unchecked")
T e = (T)element;
return e;
}
}
}
@ -516,9 +520,10 @@ public class ConcurrentArrayQueue<T> extends AbstractQueue<T>
elements = new AtomicReferenceArray<>(blockSize);
}
public Object peek(int index)
@SuppressWarnings("unchecked")
public E peek(int index)
{
return elements.get(index);
return (E)elements.get(index);
}
public boolean store(int index, E item)

View File

@ -57,7 +57,7 @@ public class MultiPartInputStreamParser
protected InputStream _in;
protected MultipartConfigElement _config;
protected String _contentType;
protected MultiMap _parts;
protected MultiMap<Part> _parts;
protected File _tmpDir;
protected File _contextTmpDir;
protected boolean _deleteOnExit;
@ -72,7 +72,7 @@ public class MultiPartInputStreamParser
protected OutputStream _out;
protected ByteArrayOutputStream2 _bout;
protected String _contentType;
protected MultiMap _headers;
protected MultiMap<String> _headers;
protected long _size = 0;
protected boolean _temporary = true;
@ -161,7 +161,7 @@ public class MultiPartInputStreamParser
protected void setHeaders(MultiMap headers)
protected void setHeaders(MultiMap<String> headers)
{
_headers = headers;
}
@ -359,9 +359,9 @@ public class MultiPartInputStreamParser
if (_parts == null)
return Collections.emptyList();
Collection<Object> values = _parts.values();
Collection<List<Part>> values = _parts.values();
List<Part> parts = new ArrayList<Part>();
for (Object o: values)
for (List<Part> o: values)
{
List<Part> asList = LazyList.getList(o, false);
parts.addAll(asList);
@ -406,9 +406,9 @@ public class MultiPartInputStreamParser
throws IOException, ServletException
{
parse();
Collection<Object> values = _parts.values();
Collection<List<Part>> values = _parts.values();
List<Part> parts = new ArrayList<Part>();
for (Object o: values)
for (List<Part> o: values)
{
List<Part> asList = LazyList.getList(o, false);
parts.addAll(asList);
@ -447,7 +447,7 @@ public class MultiPartInputStreamParser
//initialize
long total = 0; //keep running total of size of bytes read from input and throw an exception if exceeds MultipartConfigElement._maxRequestSize
_parts = new MultiMap();
_parts = new MultiMap<Part>();
//if its not a multipart request, don't parse it
if (_contentType == null || !_contentType.startsWith("multipart/form-data"))
@ -523,7 +523,7 @@ public class MultiPartInputStreamParser
String contentType=null;
String contentTransferEncoding=null;
MultiMap headers = new MultiMap();
MultiMap<String> headers = new MultiMap<String>();
while(true)
{
line=((ReadLineInputStream)_in).readLine();

View File

@ -245,9 +245,15 @@ public class SharedBlockingCallback
}
finally
{
_state = IDLE;
_idle.signalAll();
_lock.unlock();
try
{
_state = IDLE;
_idle.signalAll();
}
finally
{
_lock.unlock();
}
}
}

View File

@ -684,87 +684,89 @@ public class UrlEncoded extends MultiMap<String> implements Cloneable
int c;
int totalLength = 0;
ByteArrayOutputStream2 output = new ByteArrayOutputStream2();
int size=0;
while ((c=in.read())>0)
try(ByteArrayOutputStream2 output = new ByteArrayOutputStream2();)
{
switch ((char) c)
int size=0;
while ((c=in.read())>0)
{
case '&':
size=output.size();
value = size==0?"":output.toString(charset);
output.setCount(0);
if (key != null)
{
map.add(key,value);
}
else if (value!=null&&value.length()>0)
{
map.add(value,"");
}
key = null;
value=null;
if (maxKeys>0 && map.size()>maxKeys)
throw new IllegalStateException("Form too many keys");
break;
case '=':
if (key!=null)
{
switch ((char) c)
{
case '&':
size=output.size();
value = size==0?"":output.toString(charset);
output.setCount(0);
if (key != null)
{
map.add(key,value);
}
else if (value!=null&&value.length()>0)
{
map.add(value,"");
}
key = null;
value=null;
if (maxKeys>0 && map.size()>maxKeys)
throw new IllegalStateException("Form too many keys");
break;
case '=':
if (key!=null)
{
output.write(c);
break;
}
size=output.size();
key = size==0?"":output.toString(charset);
output.setCount(0);
break;
case '+':
output.write(' ');
break;
case '%':
int code0=in.read();
if ('u'==code0)
{
int code1=in.read();
if (code1>=0)
{
int code2=in.read();
if (code2>=0)
{
int code3=in.read();
if (code3>=0)
output.write(new String(Character.toChars((convertHexDigit(code0)<<12)+(convertHexDigit(code1)<<8)+(convertHexDigit(code2)<<4)+convertHexDigit(code3))).getBytes(charset));
}
}
}
else if (code0>=0)
{
int code1=in.read();
if (code1>=0)
output.write((convertHexDigit(code0)<<4)+convertHexDigit(code1));
}
break;
default:
output.write(c);
break;
}
size=output.size();
key = size==0?"":output.toString(charset);
output.setCount(0);
break;
case '+':
output.write(' ');
break;
case '%':
int code0=in.read();
if ('u'==code0)
{
int code1=in.read();
if (code1>=0)
{
int code2=in.read();
if (code2>=0)
{
int code3=in.read();
if (code3>=0)
output.write(new String(Character.toChars((convertHexDigit(code0)<<12)+(convertHexDigit(code1)<<8)+(convertHexDigit(code2)<<4)+convertHexDigit(code3))).getBytes(charset));
}
}
}
else if (code0>=0)
{
int code1=in.read();
if (code1>=0)
output.write((convertHexDigit(code0)<<4)+convertHexDigit(code1));
}
break;
default:
output.write(c);
break;
}
totalLength++;
if (maxLength>=0 && totalLength > maxLength)
throw new IllegalStateException("Form too large");
}
}
size=output.size();
if (key != null)
{
value = size==0?"":output.toString(charset);
output.setCount(0);
map.add(key,value);
totalLength++;
if (maxLength>=0 && totalLength > maxLength)
throw new IllegalStateException("Form too large");
}
size=output.size();
if (key != null)
{
value = size==0?"":output.toString(charset);
output.setCount(0);
map.add(key,value);
}
else if (size>0)
map.add(output.toString(charset),"");
}
else if (size>0)
map.add(output.toString(charset),"");
}
}

View File

@ -47,7 +47,7 @@ public class GCThreadLeakPreventer extends AbstractLeakPreventer
{
try
{
Class clazz = Class.forName("sun.misc.GC");
Class<?> clazz = Class.forName("sun.misc.GC");
Method requestLatency = clazz.getMethod("requestLatency", new Class[] {long.class});
requestLatency.invoke(null, Long.valueOf(Long.MAX_VALUE-1));
}