diff options
author | Jesse McConnell | 2009-06-18 14:15:26 +0000 |
---|---|---|
committer | Jesse McConnell | 2009-06-18 14:15:26 +0000 |
commit | 670fac3f3305b160c791480dee8cb4a645714bd2 (patch) | |
tree | b20b1b2bba99f2c7144812a552bfd94df3454662 | |
parent | 3a3540f42a90dd2f84de77bd283def3b1f9fa63d (diff) | |
parent | d825ba729bc1b90a67ae1ab09bf5b21c3a2b16bf (diff) | |
download | org.eclipse.jetty.project-670fac3f3305b160c791480dee8cb4a645714bd2.tar.gz org.eclipse.jetty.project-670fac3f3305b160c791480dee8cb4a645714bd2.tar.xz org.eclipse.jetty.project-670fac3f3305b160c791480dee8cb4a645714bd2.zip |
[maven-release-plugin] copy for tag jetty-7.0.0.M3jetty-7.0.0.M3
git-svn-id: svn+ssh://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/tags/jetty-7.0.0.M3@423 7e9141cc-0065-0410-87d8-b60c137991c4
77 files changed, 760 insertions, 624 deletions
diff --git a/VERSION.txt b/VERSION.txt index fbb32760ab..3da5b23381 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -11,6 +11,8 @@ jetty-7.0.0.M3-SNAPSHOT + 276545 Quoted cookie paths + 279725 Support 100 and 102 expectations + Refactored AbstractBuffers to HttpBuffers for performance + + Numerous cleanups from static code analysis + + 280707 client.HttpConnection does not catch and handle non-IOExceptions jetty-7.0.0.M2 18 May 2009 + JETTY-937 Work around Sun JVM bugs diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java index 5555ff2e50..ac09392372 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java @@ -285,8 +285,11 @@ public class HttpConnection implements Connection return; } } - catch (IOException e) - { + catch (Throwable e) + { + if (e instanceof ThreadDeath) + throw (ThreadDeath)e; + synchronized (this) { if (_exchange != null) @@ -295,9 +298,18 @@ public class HttpConnection implements Connection _exchange.setStatus(HttpExchange.STATUS_EXCEPTED); } } - failed = true; Log.warn("IOE on "+_exchange); - throw e; + failed = true; + if (e instanceof IOException) + throw (IOException)e; + + if (e instanceof Error) + throw (Error)e; + + if (e instanceof RuntimeException) + throw (RuntimeException)e; + + throw new RuntimeException(e); } finally { diff --git a/jetty-distribution/src/main/resources/resources/jetty.policy b/jetty-distribution/src/main/resources/resources/jetty.policy deleted file mode 100644 index 8ac984260a..0000000000 --- a/jetty-distribution/src/main/resources/resources/jetty.policy +++ /dev/null @@ -1,107 +0,0 @@ -// basic policy file for jetty - -// TODO update with greg's latest property changes and set better reasonable defaults for various jetty codeBases - -grant codeBase "file:${jetty.home}${/}-" { - permission java.io.FilePermission "${jetty.home}${/}-", "read"; - - permission java.io.FilePermission "${jetty.home}${/}logs${/}-", "read, write"; - - permission java.lang.RuntimePermission "createClassLoader"; - permission java.lang.RuntimePermission "setContextClassLoader"; - - permission java.security.SecurityPermission "getPolicy"; - permission java.lang.RuntimePermission "accessDeclaredMembers"; - - // makes everything work as a crutch to work on startup - permission java.security.AllPermission; -}; - -// default permissions granted to all domains - -grant { - // Allows any thread to stop itself using the java.lang.Thread.stop() - // method that takes no argument. - // Note that this permission is granted by default only to remain - // backwards compatible. - // It is strongly recommended that you either remove this permission - // from this policy file or further restrict it to code sources - // that you specify, because Thread.stop() is potentially unsafe. - // See "http://java.sun.com/notes" for more information. - permission java.lang.RuntimePermission "stopThread"; - - // allows anyone to listen on un-privileged ports - permission java.net.SocketPermission "localhost:1024-", "listen"; - - // "standard" properties that can be read by anyone - - permission java.util.PropertyPermission "java.version", "read"; - permission java.util.PropertyPermission "java.vendor", "read"; - permission java.util.PropertyPermission "java.vendor.url", "read"; - permission java.util.PropertyPermission "java.class.version", "read"; - permission java.util.PropertyPermission "os.name", "read"; - permission java.util.PropertyPermission "os.version", "read"; - permission java.util.PropertyPermission "os.arch", "read"; - permission java.util.PropertyPermission "file.separator", "read"; - permission java.util.PropertyPermission "path.separator", "read"; - permission java.util.PropertyPermission "line.separator", "read"; - - permission java.util.PropertyPermission "java.specification.version", "read"; - permission java.util.PropertyPermission "java.specification.vendor", "read"; - permission java.util.PropertyPermission "java.specification.name", "read"; - - permission java.util.PropertyPermission "java.vm.specification.version", "read"; - permission java.util.PropertyPermission "java.vm.specification.vendor", "read"; - permission java.util.PropertyPermission "java.vm.specification.name", "read"; - permission java.util.PropertyPermission "java.vm.version", "read"; - permission java.util.PropertyPermission "java.vm.vendor", "read"; - permission java.util.PropertyPermission "java.vm.name", "read"; - - // jetty specific properties - permission java.util.PropertyPermission "DEBUG", "read"; - permission java.util.PropertyPermission "START", "read"; - permission java.util.PropertyPermission "VERBOSE", "read"; - permission java.util.PropertyPermission "STOP.PORT", "read"; - permission java.util.PropertyPermission "STOP.KEY", "read"; - permission java.util.PropertyPermission "IGNORED", "read"; - permission java.util.PropertyPermission "CLASSPATH", "read"; - permission java.util.PropertyPermission "OPTIONS", "read"; - permission java.util.PropertyPermission "JETTY_NO_SHUTDOWN_HOOK", "read"; - permission java.util.PropertyPermission "ISO_8859_1", "read"; - permission java.util.PropertyPermission "jetty.home", "read, write"; - - permission java.util.PropertyPermission "user.home", "read"; - - permission java.util.PropertyPermission "jetty.class.path", "read, write"; - permission java.util.PropertyPermission "java.class.path", "read, write"; - - permission java.util.PropertyPermission "repository", "read, write"; - - permission java.util.PropertyPermission "jetty.lib", "read"; - permission java.util.PropertyPermission "jetty.server", "read"; - permission java.util.PropertyPermission "jetty.host", "read"; - permission java.util.PropertyPermission "jetty.port", "read"; - permission java.util.PropertyPermission "start.class", "read"; - - permission java.util.PropertyPermission "main.class", "read"; - - permission java.util.PropertyPermission "org.eclipse.jetty.util.log.class", "read"; - - permission java.util.PropertyPermission "org.eclipse.jetty.util.URI.charset", "read"; - - permission java.util.PropertyPermission "org.eclipse.jetty.util.FileResource.checkAliases", "read"; - - permission java.util.PropertyPermission "org.eclipse.jetty.xml.XmlParser.Validating", "read"; - - permission java.util.PropertyPermission "org.eclipse.jetty.io.nio.JVMBUG_THRESHHOLD", "read, write"; - - permission java.util.PropertyPermission "org.eclipse.jetty.util.TypeUtil.IntegerCacheSize", "read, write"; - - permission java.util.PropertyPermission "org.eclipse.jetty.util.TypeUtil.LongCacheSize", "read"; - - // provides access to webapps - permission java.io.FilePermission "${jetty.home}${/}webapps${/}-", "read"; // Ought to go up a specific codebase - -}; - - diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/AbstractGenerator.java b/jetty-http/src/main/java/org/eclipse/jetty/http/AbstractGenerator.java index 57217e23f1..ca295a7e47 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/AbstractGenerator.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/AbstractGenerator.java @@ -161,13 +161,10 @@ public abstract class AbstractGenerator implements Generator _buffer=_buffers.getBuffer(); if (contentBufferSize > _buffer.capacity()) { - if (_buffer != null) - { - Buffer nb = _buffers.getBuffer(contentBufferSize); - nb.put(_buffer); - _buffers.returnBuffer(_buffer); - _buffer = nb; - } + Buffer nb = _buffers.getBuffer(contentBufferSize); + nb.put(_buffer); + _buffers.returnBuffer(_buffer); + _buffer = nb; } } @@ -346,7 +343,6 @@ public abstract class AbstractGenerator implements Generator { if(_buffer!=null) _buffer.clear(); - return; } else { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/EncodedHttpURI.java b/jetty-http/src/main/java/org/eclipse/jetty/http/EncodedHttpURI.java index 8e31e65e4d..3279fa3031 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/EncodedHttpURI.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/EncodedHttpURI.java @@ -24,7 +24,7 @@ import org.eclipse.jetty.util.Utf8StringBuffer; public class EncodedHttpURI extends HttpURI { - private String _encoding; + private final String _encoding; public EncodedHttpURI(String encoding) { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java index b93213e1d1..21537fc48b 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpFields.java @@ -41,6 +41,7 @@ import org.eclipse.jetty.util.QuotedStringTokenizer; import org.eclipse.jetty.util.StringMap; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.URIUtil; +import org.eclipse.jetty.util.log.Log; /* ------------------------------------------------------------ */ /** @@ -68,9 +69,9 @@ public class HttpFields public final static String __separators = ", \t"; /* ------------------------------------------------------------ */ - private static String[] DAYS = + private static final String[] DAYS = { "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; - private static String[] MONTHS = + private static final String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan"}; @@ -162,7 +163,7 @@ public class HttpFields } /* ------------------------------------------------------------ */ - private static ThreadLocal<DateGenerator> __dateGenerator =new ThreadLocal<DateGenerator>() + private static final ThreadLocal<DateGenerator> __dateGenerator =new ThreadLocal<DateGenerator>() { @Override protected DateGenerator initialValue() @@ -260,7 +261,7 @@ public class HttpFields } /* ------------------------------------------------------------ */ - private static ThreadLocal<DateParser> __dateParser =new ThreadLocal<DateParser>() + private static final ThreadLocal<DateParser> __dateParser =new ThreadLocal<DateParser>() { @Override protected DateParser initialValue() @@ -308,7 +309,7 @@ public class HttpFields if (field != null) return true; while (i < _fields.size()) { - Field f = (Field) _fields.get(i++); + Field f = _fields.get(i++); if (f != null && f._prev == null && f._revision == revision) { field = f; @@ -354,13 +355,13 @@ public class HttpFields /* ------------------------------------------------------------ */ private Field getField(String name) { - return (Field) _bufferMap.get(HttpHeaders.CACHE.lookup(name)); + return _bufferMap.get(HttpHeaders.CACHE.lookup(name)); } /* ------------------------------------------------------------ */ private Field getField(Buffer name) { - return (Field) _bufferMap.get(name); + return _bufferMap.get(name); } /* ------------------------------------------------------------ */ @@ -519,7 +520,7 @@ public class HttpFields if (tok != null && tok.hasMoreElements()) return true; while (e.hasMoreElements()) { - String value = (String) e.nextElement(); + String value = e.nextElement(); tok = new QuotedStringTokenizer(value, separators, false, false); if (tok.hasMoreElements()) return true; } @@ -596,7 +597,7 @@ public class HttpFields if (!(name instanceof BufferCache.CachedBuffer)) name = HttpHeaders.CACHE.lookup(name); - Field field = (Field) _bufferMap.get(name); + Field field = _bufferMap.get(name); // Look for value to replace. if (field != null) @@ -608,7 +609,6 @@ public class HttpFields field.clear(); field = field._next; } - return; } else { @@ -701,7 +701,7 @@ public class HttpFields if (!(name instanceof BufferCache.CachedBuffer)) name = HttpHeaders.CACHE.lookup(name); - Field field = (Field) _bufferMap.get(name); + Field field = _bufferMap.get(name); Field last = null; if (field != null) { @@ -751,7 +751,7 @@ public class HttpFields */ public void remove(Buffer name) { - Field field = (Field) _bufferMap.get(name); + Field field = _bufferMap.get(name); if (field != null) { @@ -960,7 +960,7 @@ public class HttpFields // Format value and params StringBuilder buf = new StringBuilder(128); - String name_value_params = null; + String name_value_params; QuotedStringTokenizer.quoteIfNeeded(buf, name); buf.append('='); if (value != null && value.length() > 0) @@ -1027,7 +1027,7 @@ public class HttpFields { for (int i = 0; i < _fields.size(); i++) { - Field field = (Field) _fields.get(i); + Field field = _fields.get(i); if (field != null && field._revision == _revision) field.put(buffer); } BufferUtil.putCRLF(buffer); @@ -1044,10 +1044,10 @@ public class HttpFields } catch (Exception e) { - e.printStackTrace(); + Log.warn(e); + return e.toString(); } - return null; } /* ------------------------------------------------------------ */ @@ -1062,7 +1062,7 @@ public class HttpFields _revision = 0; for (int i = _fields.size(); i-- > 0;) { - Field field = (Field) _fields.get(i); + Field field = _fields.get(i); if (field != null) field.clear(); } } @@ -1078,11 +1078,11 @@ public class HttpFields { for (int i = _fields.size(); i-- > 0;) { - Field field = (Field) _fields.get(i); + Field field = _fields.get(i); if (field != null) field.destroy(); } + _fields.clear(); } - _fields.clear(); } /* ------------------------------------------------------------ */ @@ -1147,9 +1147,9 @@ public class HttpFields } /* ------------------------------------------------------------ */ - private static Float __one = new Float("1.0"); - private static Float __zero = new Float("0.0"); - private static StringMap __qualities = new StringMap(); + private static final Float __one = new Float("1.0"); + private static final Float __zero = new Float("0.0"); + private static final StringMap __qualities = new StringMap(); static { __qualities.put(null, __one); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java index e17f75cfd7..de9d9d4982 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java @@ -41,7 +41,7 @@ public class HttpGenerator extends AbstractGenerator Buffer _schemeCode; Buffer _responseLine; } - private static Status[] __status = new Status[HttpStatus.MAX_CODE+1]; + private static final Status[] __status = new Status[HttpStatus.MAX_CODE+1]; static { int versionLength=HttpVersions.HTTP_1_1_BUFFER.length(); @@ -60,7 +60,7 @@ public class HttpGenerator extends AbstractGenerator bytes[versionLength+3]=(byte)('0'+(i%10)); bytes[versionLength+4]=' '; for (int j=0;j<reason.length();j++) - bytes[versionLength+5+j]=(byte)reason.charAt(j);; + bytes[versionLength+5+j]=(byte)reason.charAt(j); bytes[versionLength+5+reason.length()]=HttpTokens.CARRIAGE_RETURN; bytes[versionLength+6+reason.length()]=HttpTokens.LINE_FEED; @@ -82,18 +82,18 @@ public class HttpGenerator extends AbstractGenerator // common _content - private static byte[] LAST_CHUNK = + private static final byte[] LAST_CHUNK = { (byte) '0', (byte) '\015', (byte) '\012', (byte) '\015', (byte) '\012'}; - private static byte[] CONTENT_LENGTH_0 = StringUtil.getBytes("Content-Length: 0\015\012"); - private static byte[] CONNECTION_KEEP_ALIVE = StringUtil.getBytes("Connection: keep-alive\015\012"); - private static byte[] CONNECTION_CLOSE = StringUtil.getBytes("Connection: close\015\012"); - private static byte[] CONNECTION_ = StringUtil.getBytes("Connection: "); - private static byte[] CRLF = StringUtil.getBytes("\015\012"); - private static byte[] TRANSFER_ENCODING_CHUNKED = StringUtil.getBytes("Transfer-Encoding: chunked\015\012"); + private static final byte[] CONTENT_LENGTH_0 = StringUtil.getBytes("Content-Length: 0\015\012"); + private static final byte[] CONNECTION_KEEP_ALIVE = StringUtil.getBytes("Connection: keep-alive\015\012"); + private static final byte[] CONNECTION_CLOSE = StringUtil.getBytes("Connection: close\015\012"); + private static final byte[] CONNECTION_ = StringUtil.getBytes("Connection: "); + private static final byte[] CRLF = StringUtil.getBytes("\015\012"); + private static final byte[] TRANSFER_ENCODING_CHUNKED = StringUtil.getBytes("Transfer-Encoding: chunked\015\012"); private static byte[] SERVER = StringUtil.getBytes("Server: Jetty(7.0.x)\015\012"); // other statics - private static int CHUNK_SPACE = 12; + private static final int CHUNK_SPACE = 12; public static void setServerVersion(String version) { @@ -235,7 +235,7 @@ public class HttpGenerator extends AbstractGenerator if (_last || _state==STATE_END) { - Log.debug("Ignoring extra content {}",new Byte(b)); + Log.debug("Ignoring extra content {}",Byte.valueOf(b)); return false; } @@ -303,8 +303,7 @@ public class HttpGenerator extends AbstractGenerator public boolean isBufferFull() { // Should we flush the buffers? - boolean full = super.isBufferFull() || _bufferChunked || _bypass || (_contentLength == HttpTokens.CHUNKED_CONTENT && _buffer != null && _buffer.space() < CHUNK_SPACE); - return full; + return super.isBufferFull() || _bufferChunked || _bypass || (_contentLength == HttpTokens.CHUNKED_CONTENT && _buffer != null && _buffer.space() < CHUNK_SPACE); } /* ------------------------------------------------------------ */ @@ -842,6 +841,7 @@ public class HttpGenerator extends AbstractGenerator _bufferChunked = true; // Did we leave space at the start of the buffer. + //noinspection ConstantConditions if (_buffer.getIndex() == CHUNK_SPACE) { // Oh yes, goodie! let's use it then! diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeaderValues.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeaderValues.java index 5f242250ee..1c500b0b54 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeaderValues.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpHeaderValues.java @@ -76,18 +76,25 @@ public class HttpHeaderValues extends BufferCache CACHE.add("gzip",index++); CACHE.add("gzip,deflate",index++); CACHE.add("deflate",index++); - + + InputStream ua = HttpHeaderValues.class.getResourceAsStream("/org/eclipse/jetty/http/useragents"); try { - InputStream ua = HttpHeaderValues.class.getResourceAsStream("/org/eclipse/jetty/http/useragents"); if (ua!=null) { - LineNumberReader in = new LineNumberReader(new InputStreamReader(ua)); - String line = in.readLine(); - while (line!=null) + try + { + LineNumberReader in = new LineNumberReader(new InputStreamReader(ua)); + String line = in.readLine(); + while (line!=null) + { + CACHE.add(line,index++); + line = in.readLine(); + } + } + finally { - CACHE.add(line,index++); - line = in.readLine(); + ua.close(); } } } diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java index 46cb92940d..308847cba0 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java @@ -162,11 +162,8 @@ public class HttpParser implements Parser public boolean isMoreInBuffer() throws IOException { - if ( _header!=null && _header.hasContent() || - _body!=null && _body.hasContent()) - return true; - - return false; + return ( _header!=null && _header.hasContent() || + _body!=null && _body.hasContent()); } /* ------------------------------------------------------------------------------- */ @@ -447,12 +444,12 @@ public class HttpParser implements Parser Buffer header=_cached!=null?_cached:HttpHeaders.CACHE.lookup(_tok0); _cached=null; - Buffer value=_multiLineValue == null ? (Buffer) _tok1 : (Buffer) new ByteArrayBuffer(_multiLineValue); + Buffer value=_multiLineValue == null ? _tok1 : new ByteArrayBuffer(_multiLineValue); int ho=HttpHeaders.CACHE.getOrdinal(header); if (ho >= 0) { - int vo=-1; + int vo; switch (ho) { @@ -848,7 +845,8 @@ public class HttpParser implements Parser } if (_body!=null && _buffer!=_body) _buffer=_body; - if (_buffer == _body) + if (_buffer == _body) + //noinspection ConstantConditions _buffer.compact(); int space=_buffer.space(); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpStatus.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpStatus.java index 03a1f37af5..84cafc46b4 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpStatus.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpStatus.java @@ -664,7 +664,7 @@ public class HttpStatus public static final int MAX_CODE = 507; - private static Code codeMap[] = new Code[MAX_CODE+1]; + private static final Code[] codeMap = new Code[MAX_CODE+1]; static { @@ -911,7 +911,7 @@ public class HttpStatus { return HttpStatus.isServerError(this._code); } - }; + } /** diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpURI.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpURI.java index c5d9f409d5..cff8e83a59 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpURI.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpURI.java @@ -41,7 +41,7 @@ import org.eclipse.jetty.util.Utf8StringBuilder; */ public class HttpURI { - private static byte[] __empty={}; + private static final byte[] __empty={}; private final static int START=0, AUTH_OR_PATH=1, @@ -68,7 +68,7 @@ public class HttpURI int _end; boolean _encoded=false; - Utf8StringBuilder _utf8b = new Utf8StringBuilder(64); + final Utf8StringBuilder _utf8b = new Utf8StringBuilder(64); public HttpURI() { @@ -487,8 +487,7 @@ public class HttpURI if (bytes==null) { bytes=new byte[length]; - for (int j=0;j<n;j++) - bytes[j]=_raw[_path+j]; + System.arraycopy(_raw,_path,bytes,0,n); } bytes[n++]=b; diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/PathMap.java b/jetty-http/src/main/java/org/eclipse/jetty/http/PathMap.java index 6efdb96e87..f8b8e0f0c6 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/PathMap.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/PathMap.java @@ -51,7 +51,7 @@ import org.eclipse.jetty.util.URIUtil; * as it is assumed they would have been either encoded in the original URL or * stripped from the path. * <P> - * This class is not synchronized for get's. If concurrent modifications are + * This class is not synchronized. If concurrent modifications are * possible then it should be synchronized at a higher level. * * @@ -83,7 +83,7 @@ public class PathMap extends HashMap implements Externalizable List _defaultSingletonList=null; Entry _prefixDefault=null; Entry _default=null; - Set _entrySet; + final Set _entrySet; boolean _nodefault=false; /* --------------------------------------------------------------- */ @@ -145,7 +145,7 @@ public class PathMap extends HashMap implements Externalizable * path specifications. * @param object The object the path maps to */ - public synchronized Object put(Object pathSpec, Object object) + public Object put(Object pathSpec, Object object) { StringTokenizer tok = new StringTokenizer(pathSpec.toString(),__pathSpecSeparators); Object old =null; @@ -337,7 +337,7 @@ public class PathMap extends HashMap implements Externalizable } /* --------------------------------------------------------------- */ - public synchronized Object remove(Object pathSpec) + public Object remove(Object pathSpec) { if (pathSpec!=null) { @@ -510,8 +510,8 @@ public class PathMap extends HashMap implements Externalizable /* ------------------------------------------------------------ */ public static class Entry implements Map.Entry { - private Object key; - private Object value; + private final Object key; + private final Object value; private String mapped; private transient String string; diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/security/B64Code.java b/jetty-http/src/main/java/org/eclipse/jetty/http/security/B64Code.java index 83928bffd9..225ea1de91 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/security/B64Code.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/security/B64Code.java @@ -40,7 +40,7 @@ public class B64Code 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' }; - static byte[] code2nibble=null; + static final byte[] code2nibble; static { diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/security/Constraint.java b/jetty-http/src/main/java/org/eclipse/jetty/http/security/Constraint.java index 23736194c9..3616984396 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/security/Constraint.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/security/Constraint.java @@ -39,13 +39,11 @@ public class Constraint implements Cloneable, Serializable if (method == null) return false; method = method.trim(); - if (method.equals(__FORM_AUTH) + return (method.equals(__FORM_AUTH) || method.equals(__BASIC_AUTH) || method.equals (__DIGEST_AUTH) || method.equals (__CERT_AUTH) - || method.equals(__CERT_AUTH2)) - return true; - return false; + || method.equals(__CERT_AUTH2)); } /* ------------------------------------------------------------ */ diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/security/Credential.java b/jetty-http/src/main/java/org/eclipse/jetty/http/security/Credential.java index 36e222cf45..73c35c642c 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/security/Credential.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/security/Credential.java @@ -74,7 +74,7 @@ public abstract class Credential { public static final String __TYPE = "CRYPT:"; - private String _cooked; + private final String _cooked; Crypt(String cooked) { @@ -110,7 +110,7 @@ public abstract class Credential private static MessageDigest __md; - private byte[] _digest; + private final byte[] _digest; /* ------------------------------------------------------------ */ MD5(String digest) diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/security/Password.java b/jetty-http/src/main/java/org/eclipse/jetty/http/security/Password.java index fa33b2116a..8af5417849 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/security/Password.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/security/Password.java @@ -107,6 +107,7 @@ public class Password extends Credential if (o instanceof Password) { Password p = (Password) o; + //noinspection StringEquality return p._pw == _pw || (null != _pw && _pw.equals(p._pw)); } @@ -223,7 +224,7 @@ public class Password extends Credential System.exit(1); } String p = arg[arg.length == 1 ? 0 : 1]; - Password pw = "?".equals(p) ? new Password(p) : new Password(p); + Password pw = new Password(p); System.err.println(pw.toString()); System.err.println(obfuscate(pw.toString())); System.err.println(Credential.MD5.digest(p)); diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/security/UnixCrypt.java b/jetty-http/src/main/java/org/eclipse/jetty/http/security/UnixCrypt.java index 8979cc0c05..4eb029c966 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/security/UnixCrypt.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/security/UnixCrypt.java @@ -23,6 +23,8 @@ package org.eclipse.jetty.http.security; +import org.eclipse.jetty.util.StringUtil; + /* ------------------------------------------------------------ */ /** * Unix Crypt. Implements the one way cryptography used by Unix systems for @@ -31,7 +33,7 @@ package org.eclipse.jetty.http.security; * @version $Id: UnixCrypt.java,v 1.1 2005/10/05 14:09:14 janb Exp $ * @author Greg Wilkins (gregw) */ -public class UnixCrypt extends Object +public class UnixCrypt { /* (mostly) Standard DES Tables from Tom Truscott */ @@ -104,22 +106,22 @@ public class UnixCrypt extends Object /* ===== Tables that are initialized at run time ==================== */ - private static byte[] A64TOI = new byte[128]; /* ascii-64 => 0..63 */ + private static final byte[] A64TOI = new byte[128]; /* ascii-64 => 0..63 */ /* Initial key schedule permutation */ - private static long[][] PC1ROT = new long[16][16]; + private static final long[][] PC1ROT = new long[16][16]; /* Subsequent key schedule rotation permutations */ - private static long[][][] PC2ROT = new long[2][16][16]; + private static final long[][][] PC2ROT = new long[2][16][16]; /* Initial permutation/expansion table */ - private static long[][] IE3264 = new long[8][16]; + private static final long[][] IE3264 = new long[8][16]; /* Table that combines the S, P, and E operations. */ - private static long[][] SPE = new long[8][64]; + private static final long[][] SPE = new long[8][64]; /* compressed/interleaved => final permutation table */ - private static long[][] CF6464 = new long[16][16]; + private static final long[][] CF6464 = new long[16][16]; /* ==================================== */ @@ -135,7 +137,7 @@ public class UnixCrypt extends Object // PC1ROT - bit reverse, then PC1, then Rotate, then PC2 for (int i = 0; i < 64; i++) perm[i] = (byte) 0; - ; + for (int i = 0; i < 64; i++) { int k; @@ -443,7 +445,7 @@ public class UnixCrypt extends Object rsltblock >>= 6; } - return new String(cryptresult, 0x00, 0, 13); + return new String(cryptresult, 0, 13); } public static void main(String[] arg) diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/ssl/SslSelectChannelEndPoint.java b/jetty-http/src/main/java/org/eclipse/jetty/http/ssl/SslSelectChannelEndPoint.java index e0d28aab4d..6d7d63ad79 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/ssl/SslSelectChannelEndPoint.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/ssl/SslSelectChannelEndPoint.java @@ -43,23 +43,22 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint { private static final ByteBuffer[] __NO_BUFFERS={}; - private Buffers _buffers; + private final Buffers _buffers; - private SSLEngine _engine; - private ByteBuffer _inBuffer; - private NIOBuffer _inNIOBuffer; - private ByteBuffer _outBuffer; - private NIOBuffer _outNIOBuffer; + private final SSLEngine _engine; + private final SSLSession _session; + private final ByteBuffer _inBuffer; + private final NIOBuffer _inNIOBuffer; + private final ByteBuffer _outBuffer; + private final NIOBuffer _outNIOBuffer; - private NIOBuffer[] _reuseBuffer=new NIOBuffer[2]; - private ByteBuffer[] _gather=new ByteBuffer[2]; + private final NIOBuffer[] _reuseBuffer=new NIOBuffer[2]; + private final ByteBuffer[] _gather=new ByteBuffer[2]; private boolean _closing=false; private SSLEngineResult _result; private String _last; - - // ssl - protected SSLSession _session; + // TODO get rid of this // StringBuilder h = new StringBuilder(500); @@ -77,7 +76,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint /* ------------------------------------------------------------ */ public SslSelectChannelEndPoint(Buffers buffers,SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey key, SSLEngine engine) - throws SSLException, IOException + throws IOException { super(channel,selectSet,key); _buffers=buffers; @@ -111,7 +110,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint { try { - _selectSet.getManager().dispatch(new Runnable() + getSelectManager().dispatch(new Runnable() { public void run() { @@ -258,9 +257,10 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint */ public int fill(Buffer buffer) throws IOException { - ByteBuffer bbuf=extractInputBuffer(buffer); + final ByteBuffer bbuf=extractInputBuffer(buffer); int size=buffer.length(); HandshakeStatus initialStatus = _engine.getHandshakeStatus(); + //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (bbuf) { try @@ -508,6 +508,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint if (flushed==0) { Thread.yield(); + //noinspection UnusedAssignment flushed=super.flush(_outNIOBuffer); // h.append("flushed2=").append(flushed).append(" of ").append(_outNIOBuffer.length()).append('\n'); } @@ -590,9 +591,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint case CLOSED: _closing=true; case OK: - boolean progress=total_filled>0 ||_result.bytesConsumed()>0 || _result.bytesProduced()>0; - // h.append("progress=").append(progress).append('\n'); - return progress; + return total_filled>0 ||_result.bytesConsumed()>0 || _result.bytesProduced()>0; default: Log.warn("unwrap "+_result); throw new IOException(_result.toString()); @@ -603,11 +602,9 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint /* ------------------------------------------------------------ */ private ByteBuffer extractOutputBuffer(Buffer buffer,int n) { - NIOBuffer nBuf=null; - if (buffer.buffer() instanceof NIOBuffer) { - nBuf=(NIOBuffer)buffer.buffer(); + NIOBuffer nBuf=(NIOBuffer)buffer.buffer(); return nBuf.getByteBuffer(); } else @@ -622,7 +619,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint } /* ------------------------------------------------------------ */ - private int wrap(Buffer header, Buffer buffer) throws IOException + private int wrap(final Buffer header, final Buffer buffer) throws IOException { _gather[0]=extractOutputBuffer(header,0); synchronized(_gather[0]) @@ -658,7 +655,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint { _outBuffer.position(0); - if (consumed>0 && header!=null) + if (consumed>0) { int len=consumed<header.length()?consumed:header.length(); header.skip(len); @@ -666,7 +663,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint _gather[0].position(0); _gather[0].limit(_gather[0].capacity()); } - if (consumed>0 && buffer!=null) + if (consumed>0) { int len=consumed<buffer.length()?consumed:buffer.length(); buffer.skip(len); @@ -700,7 +697,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint } /* ------------------------------------------------------------ */ - private int wrap(Buffer header) throws IOException + private int wrap(final Buffer header) throws IOException { _gather[0]=extractOutputBuffer(header,0); synchronized(_gather[0]) @@ -728,7 +725,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint { _outBuffer.position(0); - if (consumed>0 && header!=null) + if (consumed>0) { int len=consumed<header.length()?consumed:header.length(); header.skip(len); diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/BufferCache.java b/jetty-io/src/main/java/org/eclipse/jetty/io/BufferCache.java index f1e894957b..5f191dba13 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/BufferCache.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/BufferCache.java @@ -27,9 +27,9 @@ import org.eclipse.jetty.util.StringMap; */ public class BufferCache { - private HashMap _bufferMap=new HashMap(); - private StringMap _stringMap=new StringMap(StringMap.CASE_INSENSTIVE); - private ArrayList _index= new ArrayList(); + private final HashMap _bufferMap=new HashMap(); + private final StringMap _stringMap=new StringMap(StringMap.CASE_INSENSTIVE); + private final ArrayList _index= new ArrayList(); /* ------------------------------------------------------------------------------- */ /** Add a buffer to the cache at the specified index. @@ -112,7 +112,7 @@ public class BufferCache public static class CachedBuffer extends ByteArrayBuffer.CaseInsensitive { - private int _ordinal; + private final int _ordinal; private HashMap _associateMap=null; public CachedBuffer(String value, int ordinal) diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/BufferDateCache.java b/jetty-io/src/main/java/org/eclipse/jetty/io/BufferDateCache.java index 275d2f3b77..c1aebb8882 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/BufferDateCache.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/BufferDateCache.java @@ -46,6 +46,7 @@ public class BufferDateCache extends DateCache public synchronized Buffer formatBuffer(long date) { String d = super.format(date); + //noinspection StringEquality if (d==_last) return _buffer; _last=d; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/BufferUtil.java b/jetty-io/src/main/java/org/eclipse/jetty/io/BufferUtil.java index 91b4d436d0..11e6e65036 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/BufferUtil.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/BufferUtil.java @@ -278,10 +278,10 @@ public class BufferUtil return buf; } - private static int[] decDivisors= + private final static int[] decDivisors= { 1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1 }; - private static int[] hexDivisors= + private final static int[] hexDivisors= { 0x10000000, 0x1000000, 0x100000, 0x10000, 0x1000, 0x100, 0x10, 1 }; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayBuffer.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayBuffer.java index 27991d4447..fd9fca0da2 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayBuffer.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayBuffer.java @@ -292,12 +292,6 @@ public class ByteArrayBuffer extends AbstractBuffer byte[] src_array = src.array(); if (src_array != null) System.arraycopy(src_array, src.getIndex(), _bytes, index, length); - else if (src_array != null) - { - int s=src.getIndex(); - for (int i=0;i<length;i++) - poke(index++,src_array[s++]); - } else { int s=src.getIndex(); @@ -421,7 +415,7 @@ public class ByteArrayBuffer extends AbstractBuffer public boolean equals(Object obj) { - return equalsIgnoreCase((Buffer)obj); + return obj instanceof Buffer && equalsIgnoreCase((Buffer)obj); } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ThreadLocalBuffers.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ThreadLocalBuffers.java index dbc1f24514..e913e35df5 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ThreadLocalBuffers.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ThreadLocalBuffers.java @@ -35,7 +35,7 @@ public abstract class ThreadLocalBuffers implements Buffers public Buffer getBuffer() { - ThreadBuffers buffers = (ThreadBuffers)_buffers.get(); + ThreadBuffers buffers = _buffers.get(); if (buffers._buffer!=null) { Buffer b=buffers._buffer; @@ -55,7 +55,7 @@ public abstract class ThreadLocalBuffers implements Buffers public Buffer getHeader() { - ThreadBuffers buffers = (ThreadBuffers)_buffers.get(); + ThreadBuffers buffers = _buffers.get(); if (buffers._header!=null) { Buffer b=buffers._header; @@ -75,7 +75,7 @@ public abstract class ThreadLocalBuffers implements Buffers public Buffer getBuffer(int size) { - ThreadBuffers buffers = (ThreadBuffers)_buffers.get(); + ThreadBuffers buffers = _buffers.get(); if (buffers._other!=null && buffers._other.capacity()==size) { Buffer b=buffers._other; @@ -94,7 +94,7 @@ public abstract class ThreadLocalBuffers implements Buffers int size=buffer.capacity(); - ThreadBuffers buffers = (ThreadBuffers)_buffers.get(); + ThreadBuffers buffers = _buffers.get(); if (size==_bufferSize && buffers._buffer==null) { diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/View.java b/jetty-io/src/main/java/org/eclipse/jetty/io/View.java index d1418bb687..c1e92bb746 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/View.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/View.java @@ -131,7 +131,7 @@ public class View extends AbstractBuffer */ public boolean equals(Object obj) { - return this==obj ||((obj instanceof Buffer)&&((Buffer)obj).equals(this)) || super.equals(obj); + return this==obj ||((obj instanceof Buffer)&& obj.equals(this)) || super.equals(obj); } /** diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java b/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java index 74d4835c3f..2f024758c2 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java @@ -27,9 +27,9 @@ import java.io.Writer; */ public class WriterOutputStream extends OutputStream { - protected Writer _writer; - protected String _encoding; - private byte[] _buf=new byte[1]; + protected final Writer _writer; + protected final String _encoding; + private final byte[] _buf=new byte[1]; /* ------------------------------------------------------------ */ public WriterOutputStream(Writer writer, String encoding) @@ -42,6 +42,7 @@ public class WriterOutputStream extends OutputStream public WriterOutputStream(Writer writer) { _writer=writer; + _encoding=null; } /* ------------------------------------------------------------ */ @@ -49,8 +50,6 @@ public class WriterOutputStream extends OutputStream throws IOException { _writer.close(); - _writer=null; - _encoding=null; } /* ------------------------------------------------------------ */ diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/bio/StreamEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/bio/StreamEndPoint.java index 324384384e..d215be3260 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/bio/StreamEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/bio/StreamEndPoint.java @@ -102,9 +102,7 @@ public class StreamEndPoint implements EndPoint throw new IOException("FULL"); } - int len = buffer.readFrom(_in,space); - - return len; + return buffer.readFrom(_in,space); } /* (non-Javadoc) diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/bio/StringEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/bio/StringEndPoint.java index d21a35c6aa..047ed75d3e 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/bio/StringEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/bio/StringEndPoint.java @@ -39,7 +39,6 @@ public class StringEndPoint extends StreamEndPoint } public StringEndPoint(String encoding) - throws IOException { this(); if (encoding!=null) diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/ChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/ChannelEndPoint.java index 0d01ad671f..ecd52c091c 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/ChannelEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/ChannelEndPoint.java @@ -36,8 +36,8 @@ import org.eclipse.jetty.util.log.Log; */ public class ChannelEndPoint implements EndPoint { - protected ByteChannel _channel; - protected ByteBuffer[] _gather2=new ByteBuffer[2]; + protected final ByteChannel _channel; + protected final ByteBuffer[] _gather2=new ByteBuffer[2]; protected Socket _socket; protected InetSocketAddress _local; protected InetSocketAddress _remote; @@ -55,9 +55,7 @@ public class ChannelEndPoint implements EndPoint public boolean isBlocking() { - if (_channel instanceof SelectableChannel) - return ((SelectableChannel)_channel).isBlocking(); - return true; + return !(_channel instanceof SelectableChannel) || ((SelectableChannel)_channel).isBlocking(); } public boolean blockReadable(long millisecs) throws IOException @@ -119,9 +117,10 @@ public class ChannelEndPoint implements EndPoint int len=0; if (buf instanceof NIOBuffer) { - NIOBuffer nbuf = (NIOBuffer)buf; - ByteBuffer bbuf=nbuf.getByteBuffer(); - synchronized(nbuf) + final NIOBuffer nbuf = (NIOBuffer)buf; + final ByteBuffer bbuf=nbuf.getByteBuffer(); + //noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized(bbuf) { try { @@ -154,10 +153,10 @@ public class ChannelEndPoint implements EndPoint int len=0; if (buf instanceof NIOBuffer) { - NIOBuffer nbuf = (NIOBuffer)buf; - ByteBuffer bbuf=nbuf.getByteBuffer(); + final NIOBuffer nbuf = (NIOBuffer)buf; + final ByteBuffer bbuf=nbuf.getByteBuffer(); - // TODO synchronize + //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized(bbuf) { try @@ -210,16 +209,18 @@ public class ChannelEndPoint implements EndPoint header!=null && header.length()!=0 && buf0 instanceof NIOBuffer && buffer!=null && buffer.length()!=0 && buf1 instanceof NIOBuffer) { - NIOBuffer nbuf0 = (NIOBuffer)buf0; - ByteBuffer bbuf0=nbuf0.getByteBuffer(); - NIOBuffer nbuf1 = (NIOBuffer)buf1; - ByteBuffer bbuf1=nbuf1.getByteBuffer(); + final NIOBuffer nbuf0 = (NIOBuffer)buf0; + final ByteBuffer bbuf0=nbuf0.getByteBuffer(); + final NIOBuffer nbuf1 = (NIOBuffer)buf1; + final ByteBuffer bbuf1=nbuf1.getByteBuffer(); synchronized(this) { // We must sync because buffers may be shared (eg nbuf1 is likely to be cached content). + //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized(bbuf0) { + //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized(bbuf1) { try @@ -395,8 +396,6 @@ public class ChannelEndPoint implements EndPoint if (_remote==null) _remote=(InetSocketAddress)_socket.getRemoteSocketAddress(); - if (_remote==null) - return -1; return _remote==null?-1:_remote.getPort(); } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/DirectNIOBuffer.java b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/DirectNIOBuffer.java index a40334aaee..e3546f3b9f 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/DirectNIOBuffer.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/DirectNIOBuffer.java @@ -34,7 +34,7 @@ import org.eclipse.jetty.io.Buffer; */ public class DirectNIOBuffer extends AbstractBuffer implements NIOBuffer { - protected ByteBuffer _buf; + protected final ByteBuffer _buf; private ReadableByteChannel _in; private InputStream _inStream; private WritableByteChannel _out; @@ -137,8 +137,7 @@ public class DirectNIOBuffer extends AbstractBuffer implements NIOBuffer byte[] array=src.array(); if (array!=null) { - int length = poke(index,array,src.getIndex(),src.length()); - return length; + return poke(index,array,src.getIndex(),src.length()); } else { @@ -279,7 +278,7 @@ public class DirectNIOBuffer extends AbstractBuffer implements NIOBuffer /* ------------------------------------------------------------ */ public void writeTo(OutputStream out) throws IOException { - if (_out==null || !_out.isOpen() || _out!=_outStream) + if (_out==null || !_out.isOpen() || out!=_outStream) { _out=Channels.newChannel(out); _outStream=out; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/RandomAccessFileBuffer.java b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/RandomAccessFileBuffer.java index 94e5883855..4f5cd248ef 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/RandomAccessFileBuffer.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/RandomAccessFileBuffer.java @@ -24,9 +24,9 @@ import org.eclipse.jetty.io.Buffer; public class RandomAccessFileBuffer extends AbstractBuffer implements Buffer { - RandomAccessFile _file; - FileChannel _channel; - int _capacity=Integer.MAX_VALUE; + final RandomAccessFile _file; + final FileChannel _channel; + final int _capacity; public RandomAccessFileBuffer(File file) throws FileNotFoundException @@ -35,6 +35,7 @@ public class RandomAccessFileBuffer extends AbstractBuffer implements Buffer assert file.length()<=Integer.MAX_VALUE; _file = new RandomAccessFile(file,"rw"); _channel=_file.getChannel(); + _capacity=Integer.MAX_VALUE; setGetIndex(0); setPutIndex((int)file.length()); } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectChannelEndPoint.java index d616ec0bb1..f7e543ea84 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectChannelEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectChannelEndPoint.java @@ -18,6 +18,7 @@ import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; +import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.jetty.io.AsyncEndPoint; import org.eclipse.jetty.io.Buffer; @@ -36,26 +37,21 @@ import org.eclipse.jetty.util.thread.Timeout; */ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, AsyncEndPoint { - protected SelectorManager _manager; - protected SelectorManager.SelectSet _selectSet; - protected boolean _dispatched = false; - protected boolean _redispatched = false; - protected boolean _writable = true; - protected SelectionKey _key; - protected int _interestOps; - protected boolean _readBlocked; - protected boolean _writeBlocked; - protected Connection _connection; + private final SelectorManager.SelectSet _selectSet; + private final Connection _connection; + private final SelectorManager _manager; + private boolean _dispatched = false; + private boolean _redispatched = false; + private volatile boolean _writable = true; + + private SelectionKey _key; + private int _interestOps; + private boolean _readBlocked; + private boolean _writeBlocked; private boolean _open; - private Timeout.Task _idleTask = new IdleTask(); + private final Timeout.Task _idleTask = new IdleTask(); /* ------------------------------------------------------------ */ - public Connection getConnection() - { - return _connection; - } - - /* ------------------------------------------------------------ */ public SelectChannelEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) { super(channel); @@ -71,12 +67,24 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, _key = key; scheduleIdle(); } + + /* ------------------------------------------------------------ */ + public Connection getConnection() + { + return _connection; + } + + /* ------------------------------------------------------------ */ + public SelectorManager getSelectManager() + { + return _manager; + } /* ------------------------------------------------------------ */ /** Called by selectSet to schedule handling * */ - public void schedule() throws IOException + public void schedule() { // If threads are blocked on this synchronized (this) @@ -106,7 +114,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, _key.interestOps(0); return; } - + // Otherwise if we are still dispatched if (!isReadyForDispatch()) { @@ -114,7 +122,8 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, _key.interestOps(0); return; } - + + // Remove writeable op if ((_key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE && (_key.interestOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { @@ -130,7 +139,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, dispatch(); } } - + /* ------------------------------------------------------------ */ public void dispatch() { @@ -140,7 +149,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, _redispatched=true; else { - _dispatched = _manager.dispatch((Runnable)this); + _dispatched = _manager.dispatch(this); if(!_dispatched) { Log.warn("Dispatched Failed!"); @@ -157,7 +166,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, * @return If false is returned, the endpoint has been redispatched and * thread must keep handling the endpoint. */ - protected boolean undispatch() + private boolean undispatch() { synchronized (this) { @@ -321,7 +330,6 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, { synchronized (this) { - int ops=-1; if (getChannel().isOpen()) { @@ -338,6 +346,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, Log.ignore(e); } } + if(_interestOps == ops && getChannel().isOpen()) return; @@ -379,6 +388,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, _key.cancel(); } cancelIdle(); + if (_open) _manager.endPointClosed(this); _open=false; @@ -419,41 +429,52 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, public void run() { boolean dispatched=true; - do + try { - try - { - _connection.handle(); - } - catch (ClosedChannelException e) - { - Log.ignore(e); - } - catch (EofException e) - { - Log.debug("EOF", e); - try{close();} - catch(IOException e2){Log.ignore(e2);} - } - catch (IOException e) - { - Log.warn(e.toString()); - Log.debug(e); - try{close();} - catch(IOException e2){Log.ignore(e2);} - } - catch (Throwable e) + while(dispatched) { - Log.warn("handle failed", e); - try{close();} - catch(IOException e2){Log.ignore(e2);} + try + { + _connection.handle(); + } + catch (ClosedChannelException e) + { + Log.ignore(e); + } + catch (EofException e) + { + Log.debug("EOF", e); + try{close();} + catch(IOException e2){Log.ignore(e2);} + } + catch (IOException e) + { + Log.warn(e.toString()); + Log.debug(e); + try{close();} + catch(IOException e2){Log.ignore(e2);} + } + catch (Throwable e) + { + Log.warn("handle failed", e); + try{close();} + catch(IOException e2){Log.ignore(e2);} + } + dispatched=!undispatch(); } - finally + } + finally + { + if (dispatched) { dispatched=!undispatch(); - } + while (dispatched) + { + Log.warn("SCEP.run() finally DISPATCHED"); + dispatched=!undispatch(); + } + } } - while(dispatched); } /* ------------------------------------------------------------ */ @@ -479,8 +500,11 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, /* ------------------------------------------------------------ */ public String toString() { - return "SCEP@" + hashCode() + "\t[d=" + _dispatched + ",io=" + _interestOps+ - ",w=" + _writable + ",b=" + _readBlocked + "|" + _writeBlocked + "]"; + synchronized(this) + { + return "SCEP@" + hashCode() + "\t[d=" + _dispatched + ",io=" + _interestOps+ + ",w=" + _writable + ",b=" + _readBlocked + "|" + _writeBlocked + "]"; + } } /* ------------------------------------------------------------ */ @@ -498,7 +522,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ - public class IdleTask extends Timeout.Task + private class IdleTask extends Timeout.Task { /* ------------------------------------------------------------ */ /* diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectorManager.java b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectorManager.java index a188f4712b..9375d1225a 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectorManager.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectorManager.java @@ -42,7 +42,7 @@ import org.eclipse.jetty.util.thread.Timeout; */ public abstract class SelectorManager extends AbstractLifeCycle { - private static final int __JVMBUG_THRESHHOLD=Integer.getInteger("org.eclipse.jetty.io.nio.JVMBUG_THRESHHOLD",128).intValue(); + private static final int __JVMBUG_THRESHHOLD=Integer.getInteger("org.eclipse.jetty.io.nio.JVMBUG_THRESHHOLD",128); private static final int __JVMBUG_THRESHHOLD2=__JVMBUG_THRESHHOLD*2; private static final int __JVMBUG_THRESHHOLD1=(__JVMBUG_THRESHHOLD2+__JVMBUG_THRESHHOLD)/2; private long _maxIdleTime; @@ -67,7 +67,7 @@ public abstract class SelectorManager extends AbstractLifeCycle /* ------------------------------------------------------------ */ /** - * @param selectSets + * @param selectSets number of select sets to create */ public void setSelectSets(int selectSets) { @@ -100,7 +100,7 @@ public abstract class SelectorManager extends AbstractLifeCycle * @param att Attached Object * @throws IOException */ - public void register(SocketChannel channel, Object att) throws IOException + public void register(SocketChannel channel, Object att) { int s=_set++; s=s%_selectSets; @@ -119,7 +119,7 @@ public abstract class SelectorManager extends AbstractLifeCycle * @return * @throws IOException */ - public void register(ServerSocketChannel acceptChannel) throws IOException + public void register(ServerSocketChannel acceptChannel) { int s=_set++; s=s%_selectSets; @@ -211,12 +211,13 @@ public abstract class SelectorManager extends AbstractLifeCycle SelectSet[] sets= _selectSet; _selectSet=null; if (sets!=null) - for (int i=0;i<sets.length;i++) + { + for (SelectSet set : sets) { - SelectSet set = sets[i]; if (set!=null) set.stop(); } + } super.doStop(); } @@ -286,14 +287,15 @@ public abstract class SelectorManager extends AbstractLifeCycle /* ------------------------------------------------------------------------------- */ public class SelectSet { - private transient int _change; - private transient List<Object>[] _changes; - private transient Timeout _idleTimeout; - private transient int _nextSet; - private transient Timeout _timeout; - private transient Selector _selector; - private transient int _setID; - private transient int _jvmBug; + private final int _setID; + private final Timeout _idleTimeout; + private final Timeout _timeout; + private final List<Object>[] _changes; + + private int _change; + private int _nextSet; + private Selector _selector; + private int _jvmBug; private volatile Thread _selecting; private long _lastJVMBug; @@ -306,10 +308,10 @@ public abstract class SelectorManager extends AbstractLifeCycle _idleTimeout.setDuration(getMaxIdleTime()); _timeout = new Timeout(this); _timeout.setDuration(0L); + _changes = new List[] {new ArrayList(),new ArrayList()}; // create a selector; _selector = Selector.open(); - _changes = new List[] {new ArrayList(),new ArrayList()}; _change=0; } @@ -435,8 +437,8 @@ public abstract class SelectorManager extends AbstractLifeCycle } changes.clear(); - long idle_next = 0; - long retry_next = 0; + long idle_next; + long retry_next; long now=System.currentTimeMillis(); synchronized (this) { @@ -486,10 +488,8 @@ public abstract class SelectorManager extends AbstractLifeCycle } // BLOODY SUN BUG !!! Try refreshing the entire selector. final Selector new_selector = Selector.open(); - Iterator iterator = _selector.keys().iterator(); - while (iterator.hasNext()) + for (SelectionKey k: selector.keys()) { - SelectionKey k = (SelectionKey)iterator.next(); if (!k.isValid() || k.interestOps()==0) continue; @@ -517,10 +517,8 @@ public abstract class SelectorManager extends AbstractLifeCycle _jvmBug0=true; Log.info("seeing JVM BUG(s) - cancelling interestOps==0"); } - Iterator iter = selector.keys().iterator(); - while(iter.hasNext()) + for (SelectionKey k: selector.keys()) { - SelectionKey k = (SelectionKey) iter.next(); if (k.isValid()&&k.interestOps()==0) { k.cancel(); @@ -716,13 +714,9 @@ public abstract class SelectorManager extends AbstractLifeCycle wakeup(); selecting=_selecting!=null; } - - ArrayList<SelectionKey> keys=new ArrayList<SelectionKey>(_selector.keys()); - Iterator<SelectionKey> iter =keys.iterator(); - while (iter.hasNext()) + for (SelectionKey key:_selector.keys()) { - SelectionKey key = (SelectionKey)iter.next(); if (key==null) continue; Object att=key.attachment(); diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/ThreadLocalBuffersTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/ThreadLocalBuffersTest.java index 204070ddce..b98f6b0673 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/ThreadLocalBuffersTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/ThreadLocalBuffersTest.java @@ -34,18 +34,10 @@ public class ThreadLocalBuffersTest int runTestLength = _stress?5000:1000; - int threadWaitTime = 5; - boolean runTest = false; AtomicLong buffersRetrieved; - private static int __LOCAL = 1; - - private static int __LIST = 2; - - private static int __QUEUE = 3; - protected void setUp() throws Exception { @@ -115,7 +107,7 @@ public class ThreadLocalBuffersTest } - class InnerBuffers extends ThreadLocalBuffers + static class InnerBuffers extends ThreadLocalBuffers { @Override protected Buffer newBuffer(int size) diff --git a/jetty-policy/src/main/java/org/eclipse/jetty/policy/JettyPolicy.java b/jetty-policy/src/main/java/org/eclipse/jetty/policy/JettyPolicy.java index 2490f1fe0b..6aed5149f1 100644 --- a/jetty-policy/src/main/java/org/eclipse/jetty/policy/JettyPolicy.java +++ b/jetty-policy/src/main/java/org/eclipse/jetty/policy/JettyPolicy.java @@ -41,9 +41,6 @@ import org.eclipse.jetty.policy.loader.DefaultPolicyLoader; * permission tweaking or runtime creation and specification of policies for specific webapps * 3) I wanted to have support for specifying multiple policy files to source permissions from * - * Required additions: - * - certificate support - * * Possible additions are: * - directories of policy file support * - jmx enabled a la #2 above diff --git a/jetty-policy/src/main/java/org/eclipse/jetty/policy/loader/DefaultPolicyLoader.java b/jetty-policy/src/main/java/org/eclipse/jetty/policy/loader/DefaultPolicyLoader.java index 670f59cc69..ef19cea01d 100644 --- a/jetty-policy/src/main/java/org/eclipse/jetty/policy/loader/DefaultPolicyLoader.java +++ b/jetty-policy/src/main/java/org/eclipse/jetty/policy/loader/DefaultPolicyLoader.java @@ -16,16 +16,24 @@ package org.eclipse.jetty.policy.loader; //and contributed to that project by Alexey V. Varlamov under the ASL //======================================================================== +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Constructor; +import java.net.MalformedURLException; import java.net.URL; +import java.security.AccessController; import java.security.CodeSource; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.KeyStoreSpi; +import java.security.NoSuchAlgorithmException; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.ProtectionDomain; import java.security.cert.Certificate; +import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -33,6 +41,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.StringTokenizer; import org.eclipse.jetty.policy.PolicyException; import org.eclipse.jetty.policy.PropertyEvaluator; @@ -40,14 +49,14 @@ import org.eclipse.jetty.policy.PropertyEvaluator; /** * Load the policies within the stream and resolve into protection domains and permission collections * - * TODO: currently this loading does not support keystores or certificates */ public class DefaultPolicyLoader { - + public static Map<ProtectionDomain, PermissionCollection> load( InputStream policyStream, PropertyEvaluator evaluator ) throws PolicyException { Map<ProtectionDomain, PermissionCollection> pdMappings = new HashMap<ProtectionDomain, PermissionCollection>(); + KeyStore keystore = null; try { @@ -58,11 +67,16 @@ public class DefaultPolicyLoader loader.scanStream( new InputStreamReader(policyStream), grantEntries, keystoreEntries ); + for ( Iterator<KeystoreEntry> i = keystoreEntries.iterator(); i.hasNext();) + { + keystore = resolveKeyStore( i.next(), evaluator ); + } + for ( Iterator<GrantEntry> i = grantEntries.iterator(); i.hasNext(); ) { GrantEntry grant = i.next(); - Permissions permissions = processPermissions( grant.permissions, evaluator ); + Permissions permissions = processPermissions( grant.permissions, keystore, evaluator ); ProtectionDomain pd; @@ -86,34 +100,31 @@ public class DefaultPolicyLoader } } - private static Permissions processPermissions( Collection<PermissionEntry> collection, PropertyEvaluator evaluator ) throws PolicyException + private static Permissions processPermissions( Collection<PermissionEntry> collection, KeyStore keystore, PropertyEvaluator evaluator ) throws PolicyException { Permissions permissions = new Permissions(); for ( Iterator<PermissionEntry> i = collection.iterator(); i.hasNext(); ) { - PermissionEntry perm = i.next(); + PermissionEntry perm = i.next(); Class clazz; try { clazz = Class.forName( perm.klass ); - if ( perm.name == null && perm.actions == null ) - { - permissions.add( (Permission)clazz.newInstance() ); - } - else if ( perm.name != null && perm.actions == null ) + // if we have perm.signers then we need to validate against the class certificates + if ( perm.signers != null ) { - Constructor c = clazz.getConstructor(new Class[] { String.class }); - permissions.add( (Permission)c.newInstance( evaluator.evaluate( perm.name ) ) ); + if ( validate( resolveToCertificates( keystore, perm.signers ), (Certificate[]) clazz.getSigners() )) + { + permissions.add( resolveToPermission( clazz, perm, evaluator ) ); + } } - else if ( perm.name != null && perm.actions != null ) + else { - Constructor c = clazz.getConstructor(new Class[] { String.class, String.class }); - permissions.add( (Permission)c.newInstance( evaluator.evaluate( perm.name ), perm.actions ) ); + permissions.add( resolveToPermission( clazz, perm, evaluator ) ); } - } catch ( Exception e ) { @@ -123,6 +134,37 @@ public class DefaultPolicyLoader return permissions; } + + private static Permission resolveToPermission(Class clazz, PermissionEntry perm, PropertyEvaluator evaluator ) throws PolicyException + { + try + { + Permission permission = null; + + if ( perm.name == null && perm.actions == null ) + { + permission = (Permission) clazz.newInstance(); + } + else if ( perm.name != null && perm.actions == null ) + { + Constructor c = clazz.getConstructor( new Class[] { String.class } ); + permission = (Permission) c.newInstance( evaluator.evaluate( perm.name ) ); + } + else if ( perm.name != null && perm.actions != null ) + { + Constructor c = clazz.getConstructor( new Class[] { String.class, String.class } ); + permission = (Permission) c.newInstance( evaluator.evaluate( perm.name ), perm.actions ); + } + + return permission; + + } + catch ( Exception e ) + { + throw new PolicyException( e ); + } + + } private static CodeSource resolveToCodeSource( String codeBase, PropertyEvaluator evaluator ) throws PolicyException { @@ -137,9 +179,104 @@ public class DefaultPolicyLoader throw new PolicyException( e ); } } + + /** + * resolve signers into an array of certificates using a given keystore + * + * @param keyStore + * @param signers + * @return + * @throws Exception + */ + private static Certificate[] resolveToCertificates( KeyStore keyStore, String signers ) throws PolicyException + { + StringTokenizer strTok = new StringTokenizer( signers, ","); + + Certificate[] certificates = new Certificate[strTok.countTokens()]; + + for ( int i = 0; strTok.hasMoreTokens(); ++i ) + { + try + { + certificates[i] = keyStore.getCertificate( strTok.nextToken().trim() ); + } + catch ( KeyStoreException kse ) + { + throw new PolicyException( kse ); + } + } + + return certificates; + } + + private static KeyStore resolveKeyStore( KeystoreEntry entry, PropertyEvaluator evaluator ) throws PolicyException + { + try + { + KeyStore keyStore = KeyStore.getInstance( entry.type ); + + URL keyStoreLocation = new URL ( entry.url ); + + InputStream istream = keyStoreLocation.openStream(); + + keyStore.load( istream, null ); + + return keyStore; + } + catch ( KeyStoreException kse ) + { + throw new PolicyException( kse ); + } + catch ( MalformedURLException me ) + { + throw new PolicyException( me ); + } + catch ( IOException ioe ) + { + throw new PolicyException( ioe ); + } + catch ( NoSuchAlgorithmException e ) + { + throw new PolicyException( e ); + } + catch ( CertificateException ce ) + { + throw new PolicyException( ce ); + } + } /** - * Compound token representing <i>keystore </i> clause. See policy format + * validate that all permission certs are present in the class certs + * + * @param permCerts + * @param classCerts + * @return true if the permissions match up + */ + private static boolean validate( Certificate[] permCerts, Certificate[] classCerts ) + { + for ( int i = 0; i < permCerts.length; ++i ) + { + boolean found = false; + for ( int j = 0; j < classCerts.length; ++j ) + { + if ( permCerts[i].equals( classCerts[j] ) ) + { + found = true; + break; + } + } + // if we didn't find the permCert in the classCerts then we don't match up + if ( found == false ) + { + return false; + } + } + // we found all the permCerts in classCerts so return true + return true; + } + + /** + * Compound token representing <i>keystore</i> clause. See policy format * {@link org.apache.harmony.security.DefaultPolicy description}for details. * * @see org.apache.harmony.security.fortress.DefaultPolicyParser diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java index dcf3dd7831..b52e97163a 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java @@ -74,7 +74,7 @@ public abstract class AbstractConnector extends HttpBuffers implements Connector private transient Thread[] _acceptorThread; - Object _statsLock = new Object(); + final Object _statsLock = new Object(); transient long _statsStartedAt=-1; // TODO use concurrents for these! diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContinuation.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContinuation.java index 1b48479920..ede6cb4be0 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContinuation.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncContinuation.java @@ -102,8 +102,7 @@ public class AsyncContinuation implements AsyncContext, Continuation { synchronized(this) { - if ((listener instanceof ContinuationListener)) - _listeners=LazyList.add(_listeners,listener); + _listeners=LazyList.add(_listeners,listener); // _history.append('L'); } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Dispatcher.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Dispatcher.java index 38dc538d38..0608a02885 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/Dispatcher.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Dispatcher.java @@ -68,16 +68,16 @@ public class Dispatcher implements RequestDispatcher public final static String __JSP_FILE="org.apache.catalina.jsp_file"; /* ------------------------------------------------------------ */ - private ContextHandler _contextHandler; - private String _uri; - private String _path; - private String _dQuery; - private String _named; + private final ContextHandler _contextHandler; + private final String _uri; + private final String _path; + private final String _dQuery; + private final String _named; /* ------------------------------------------------------------ */ /** * @param contextHandler - * @param uriInContext + * @param uri * @param pathInContext * @param query */ @@ -87,12 +87,13 @@ public class Dispatcher implements RequestDispatcher _uri=uri; _path=pathInContext; _dQuery=query; + _named=null; } /* ------------------------------------------------------------ */ /** Constructor. - * @param servletHandler + * @param contextHandler * @param name */ public Dispatcher(ContextHandler contextHandler,String name) @@ -100,6 +101,9 @@ public class Dispatcher implements RequestDispatcher { _contextHandler=contextHandler; _named=name; + _uri=null; + _path=null; + _dQuery=null; } /* ------------------------------------------------------------ */ @@ -176,7 +180,7 @@ public class Dispatcher implements RequestDispatcher baseRequest.setAttributes(attr); - _contextHandler.handle(_named==null?_path:_named,baseRequest, (HttpServletRequest)request, (HttpServletResponse)response); + _contextHandler.handle(_path,baseRequest, (HttpServletRequest)request, (HttpServletResponse)response); } } finally @@ -196,7 +200,7 @@ public class Dispatcher implements RequestDispatcher protected void forward(ServletRequest request, ServletResponse response, DispatcherType dispatch) throws ServletException, IOException { Request baseRequest=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest(); - Response base_response=(Response)baseRequest.getResponse(); + Response base_response=baseRequest.getResponse(); base_response.fwdReset(); request.removeAttribute(__JSP_FILE); // TODO remove when glassfish 1044 is fixed @@ -277,7 +281,7 @@ public class Dispatcher implements RequestDispatcher Object values=entry.getValue(); for (int i=0;i<LazyList.size(values);i++) { - overridden_query_string.append("&"+name+"="+LazyList.get(values, i)); + overridden_query_string.append("&").append(name).append("=").append(LazyList.get(values, i)); } } } @@ -300,7 +304,7 @@ public class Dispatcher implements RequestDispatcher //original value. Otherwise, this is the first forward and we need to establish the values. //Note: the established value on the original request for pathInfo and //for queryString is allowed to be null, but cannot be null for the other values. - if ((String)old_attr.getAttribute(FORWARD_REQUEST_URI) != null) + if (old_attr.getAttribute(FORWARD_REQUEST_URI) != null) { attr._pathInfo=(String)old_attr.getAttribute(FORWARD_PATH_INFO); attr._query=(String)old_attr.getAttribute(FORWARD_QUERY_STRING); @@ -357,7 +361,7 @@ public class Dispatcher implements RequestDispatcher /* ------------------------------------------------------------ */ private class ForwardAttributes implements Attributes { - Attributes _attr; + final Attributes _attr; String _requestURI; String _contextPath; @@ -473,7 +477,7 @@ public class Dispatcher implements RequestDispatcher /* ------------------------------------------------------------ */ private class IncludeAttributes implements Attributes { - Attributes _attr; + final Attributes _attr; String _requestURI; String _contextPath; @@ -575,4 +579,4 @@ public class Dispatcher implements RequestDispatcher setAttribute(name,null); } } -}; +} diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java index 6885a05dc8..68ce3aed0e 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpConnection.java @@ -71,13 +71,13 @@ import org.eclipse.jetty.util.thread.Timeout; */ public class HttpConnection implements Connection { - private static int UNKNOWN = -2; - private static ThreadLocal<HttpConnection> __currentConnection = new ThreadLocal<HttpConnection>(); + private static final int UNKNOWN = -2; + private static final ThreadLocal<HttpConnection> __currentConnection = new ThreadLocal<HttpConnection>(); private final long _timeStamp=System.currentTimeMillis(); private int _requests; private volatile boolean _handling; - + protected final Connector _connector; protected final EndPoint _endp; protected final Server _server; @@ -111,7 +111,7 @@ public class HttpConnection implements Connection /* ------------------------------------------------------------ */ public static HttpConnection getCurrentConnection() { - return (HttpConnection) __currentConnection.get(); + return __currentConnection.get(); } /* ------------------------------------------------------------ */ @@ -126,7 +126,7 @@ public class HttpConnection implements Connection */ public HttpConnection(Connector connector, EndPoint endpoint, Server server) { - _uri = URIUtil.__CHARSET==StringUtil.__UTF8?new HttpURI():new EncodedHttpURI(URIUtil.__CHARSET); + _uri = StringUtil.__UTF8.equals(URIUtil.__CHARSET)?new HttpURI():new EncodedHttpURI(URIUtil.__CHARSET); _connector = connector; _endp = endpoint; HttpBuffers ab = (HttpBuffers)_connector; @@ -144,7 +144,7 @@ public class HttpConnection implements Connection protected HttpConnection(Connector connector, EndPoint endpoint, Server server, Parser parser, Generator generator, Request request) { - _uri = URIUtil.__CHARSET==StringUtil.__UTF8?new HttpURI():new EncodedHttpURI(URIUtil.__CHARSET); + _uri = URIUtil.__CHARSET.equals(StringUtil.__UTF8)?new HttpURI():new EncodedHttpURI(URIUtil.__CHARSET); _connector = connector; _endp = endpoint; _parser = parser; @@ -383,9 +383,10 @@ public class HttpConnection implements Connection boolean progress=true; try - { - _handling=true; + { assert getCurrentConnection()==null; + assert _handling==false; + _handling=true; setCurrentConnection(this); while (more_in_buffer) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpWriter.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpWriter.java index 723802d91e..87debfb8cb 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpWriter.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpWriter.java @@ -35,8 +35,8 @@ public class HttpWriter extends Writer private static final int WRITE_ISO1 = 1; private static final int WRITE_UTF8 = 2; - HttpOutput _out; - AbstractGenerator _generator; + final HttpOutput _out; + final AbstractGenerator _generator; int _writeMode; int _surrogate; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java index 4da62b12d3..9734b04f8b 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java @@ -173,7 +173,7 @@ public class Request implements HttpServletRequest /* ------------------------------------------------------------ */ public void addContinuationListener(ContinuationListener listener) { - _async.addContinuationListener((ContinuationListener)listener); + _async.addContinuationListener(listener); } /* ------------------------------------------------------------ */ @@ -558,11 +558,10 @@ public class Request implements HttpServletRequest return Locale.getDefault(); int size=acceptLanguage.size(); - - // convert to locals - for (int i=0; i<size; i++) + + if (size>0) { - String language = (String)acceptLanguage.get(i); + String language = (String)acceptLanguage.get(0); language=HttpFields.valueParameters(language,null); String country = ""; int dash = language.indexOf('-'); @@ -901,7 +900,7 @@ public class Request implements HttpServletRequest */ public StringBuffer getRequestURL() { - StringBuffer url = new StringBuffer(48); + final StringBuffer url = new StringBuffer(48); synchronized (url) { String scheme = getScheme(); @@ -1263,7 +1262,7 @@ public class Request implements HttpServletRequest return false; HttpSession session=getSession(false); - return (session==null?false:_sessionManager.getIdManager().getClusterId(_requestedSessionId).equals(_sessionManager.getClusterId(session))); + return (session != null && _sessionManager.getIdManager().getClusterId(_requestedSessionId).equals(_sessionManager.getClusterId(session))); } /* ------------------------------------------------------------ */ @@ -1294,7 +1293,7 @@ public class Request implements HttpServletRequest { if (_savedNewSessions==null) return null; - return (HttpSession) _savedNewSessions.get(key); + return _savedNewSessions.get(key); } /* ------------------------------------------------------------ */ @@ -1363,7 +1362,7 @@ public class Request implements HttpServletRequest if (listener instanceof ServletRequestAttributeListener) { final ServletRequestAttributeListener l = (ServletRequestAttributeListener)listener; - ((ServletRequestAttributeListener)l).attributeRemoved(event); + l.attributeRemoved(event); } } } @@ -1426,12 +1425,12 @@ public class Request implements HttpServletRequest { try { - ByteBuffer byteBuffer=(ByteBuffer)value; + final ByteBuffer byteBuffer=(ByteBuffer)value; synchronized (byteBuffer) { NIOBuffer buffer = byteBuffer.isDirect() - ?(NIOBuffer)new DirectNIOBuffer(byteBuffer,true) - :(NIOBuffer)new IndirectNIOBuffer(byteBuffer,true); + ?new DirectNIOBuffer(byteBuffer,true) + :new IndirectNIOBuffer(byteBuffer,true); ((HttpConnection.Output)getServletResponse().getOutputStream()).sendResponse(buffer); } } @@ -1501,6 +1500,7 @@ public class Request implements HttpServletRequest // check encoding is supported if (!StringUtil.isUTF8(encoding)) + //noinspection ResultOfMethodCallIgnored "".getBytes(encoding); } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceCache.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceCache.java index e2f1b54598..bfc66994fc 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceCache.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceCache.java @@ -35,24 +35,25 @@ import org.eclipse.jetty.util.resource.ResourceFactory; /** * */ -public class ResourceCache extends AbstractLifeCycle implements Serializable -{ +public class ResourceCache extends AbstractLifeCycle +{ + protected final Map _cache; + private final MimeTypes _mimeTypes; private int _maxCachedFileSize =1024*1024; private int _maxCachedFiles=2048; private int _maxCacheSize =16*1024*1024; - private MimeTypes _mimeTypes; - - protected transient Map _cache; - protected transient int _cachedSize; - protected transient int _cachedFiles; - protected transient Content _mostRecentlyUsed; - protected transient Content _leastRecentlyUsed; + + protected int _cachedSize; + protected int _cachedFiles; + protected Content _mostRecentlyUsed; + protected Content _leastRecentlyUsed; /* ------------------------------------------------------------ */ /** Constructor. */ public ResourceCache(MimeTypes mimeTypes) { + _cache=new HashMap(); _mimeTypes=mimeTypes; } @@ -268,7 +269,7 @@ public class ResourceCache extends AbstractLifeCycle implements Serializable public synchronized void doStart() throws Exception { - _cache=new HashMap(); + _cache.clear(); _cachedSize=0; _cachedFiles=0; } @@ -307,10 +308,10 @@ public class ResourceCache extends AbstractLifeCycle implements Serializable */ public class Content implements HttpContent { + final Resource _resource; + final long _lastModified; boolean _locked; String _key; - Resource _resource; - long _lastModified; Content _prev; Content _next; @@ -455,7 +456,7 @@ public class ResourceCache extends AbstractLifeCycle implements Serializable _cache.remove(_key); _key=null; if (_buffer!=null) - _cachedSize=_cachedSize-(int)_buffer.length(); + _cachedSize=_cachedSize-_buffer.length(); _cachedFiles--; if (_mostRecentlyUsed==this) @@ -470,9 +471,7 @@ public class ResourceCache extends AbstractLifeCycle implements Serializable _prev=null; _next=null; - if (_resource!=null) - _resource.release(); - _resource=null; + _resource.release(); } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Response.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Response.java index d73896b429..f20430a187 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/Response.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Response.java @@ -66,24 +66,18 @@ public class Response implements HttpServletResponse * can be set during include using only {@link #setHeader(String, String)} or * {@link #addHeader(String, String)}. */ - public static String SET_INCLUDE_HEADER_PREFIX = "org.eclipse.jetty.server.include."; + public final static String SET_INCLUDE_HEADER_PREFIX = "org.eclipse.jetty.server.include."; - private static PrintWriter __nullPrintWriter; - private static ServletOutputStream __nullServletOut; + private static final PrintWriter __nullPrintWriter; + private static final ServletOutputStream __nullServletOut; static { - try{ - __nullPrintWriter = new PrintWriter(IO.getNullWriter()); - __nullServletOut = new NullOutput(); - } - catch (Exception e) - { - Log.warn(e); - } + __nullPrintWriter = new PrintWriter(IO.getNullWriter()); + __nullServletOut = new NullOutput(); } - private HttpConnection _connection; + private final HttpConnection _connection; private int _status=SC_OK; private String _reason; private Locale _locale; @@ -172,8 +166,10 @@ public class Response implements HttpServletResponse if (sessionURLPrefix==null) return url; + if (url==null) + return null; // should not encode if cookies in evidence - if (url==null || request==null || request.isRequestedSessionIdFromCookie()) + if (request.isRequestedSessionIdFromCookie()) { int prefix=url.indexOf(sessionURLPrefix); if (prefix!=-1) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java index 459bf0376b..90adcf15c8 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java @@ -56,19 +56,19 @@ import org.eclipse.jetty.util.thread.ThreadPool; */ public class Server extends HandlerWrapper implements Attributes { - private static ShutdownHookThread hookThread = new ShutdownHookThread(); - private static String _version = (Server.class.getPackage()!=null && Server.class.getPackage().getImplementationVersion()!=null) + private static final ShutdownHookThread hookThread = new ShutdownHookThread(); + private static final String _version = (Server.class.getPackage()!=null && Server.class.getPackage().getImplementationVersion()!=null) ?Server.class.getPackage().getImplementationVersion() :"7.0.y.z-SNAPSHOT"; + private final Container _container=new Container(); + private final AttributesMap _attributes = new AttributesMap(); + private final List<Object> _dependentBeans=new ArrayList<Object>(); private ThreadPool _threadPool; private Connector[] _connectors; - private Container _container=new Container(); private SessionIdManager _sessionIdManager; private boolean _sendServerVersion = true; //send Server: header - private boolean _sendDateHeader = false; //send Date: header - private AttributesMap _attributes = new AttributesMap(); - private List<Object> _dependentBeans=new ArrayList<Object>(); + private boolean _sendDateHeader = false; //send Date: header private int _graceful=0; private boolean _stopAtShutdown; @@ -525,7 +525,7 @@ public class Server extends HandlerWrapper implements Attributes private static class ShutdownHookThread extends Thread { private boolean _hooked = false; - private Set<Server> _servers = new CopyOnWriteArraySet<Server>(); + private final Set<Server> _servers = new CopyOnWriteArraySet<Server>(); /** * Hooks this thread for shutdown. @@ -538,10 +538,8 @@ public class Server extends HandlerWrapper implements Attributes { try { - Method shutdownHook = java.lang.Runtime.class.getMethod("addShutdownHook", new Class[] - { java.lang.Thread.class}); - shutdownHook.invoke(Runtime.getRuntime(), new Object[] - { this}); + Method shutdownHook = java.lang.Runtime.class.getMethod("addShutdownHook", Thread.class); + shutdownHook.invoke(Runtime.getRuntime(), this); _hooked = true; } catch (Exception e) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/UserIdentity.java b/jetty-server/src/main/java/org/eclipse/jetty/server/UserIdentity.java index 5baa8fc516..ca7715c9c3 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/UserIdentity.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/UserIdentity.java @@ -87,7 +87,7 @@ public interface UserIdentity /* ------------------------------------------------------------ */ public interface UnauthenticatedUserIdentity extends UserIdentity { - }; + } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/bio/SocketConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/bio/SocketConnector.java index e037027941..51bb674075 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/bio/SocketConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/bio/SocketConnector.java @@ -48,7 +48,7 @@ import org.eclipse.jetty.util.log.Log; public class SocketConnector extends AbstractConnector { protected ServerSocket _serverSocket; - protected Set _connections; + protected final Set _connections; /* ------------------------------------------------------------ */ /** Constructor. @@ -56,6 +56,7 @@ public class SocketConnector extends AbstractConnector */ public SocketConnector() { + _connections=new HashSet(); } /* ------------------------------------------------------------ */ @@ -137,7 +138,7 @@ public class SocketConnector extends AbstractConnector /* ------------------------------------------------------------------------------- */ protected void doStart() throws Exception { - _connections=new HashSet(); + _connections.clear(); super.doStart(); } @@ -178,7 +179,7 @@ public class SocketConnector extends AbstractConnector _socket=socket; } - public void dispatch() throws InterruptedException, IOException + public void dispatch() throws IOException { if (getThreadPool()==null || !getThreadPool().dispatch(this)) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandlerContainer.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandlerContainer.java index 44a306e5fc..d42fd8d1c6 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandlerContainer.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/AbstractHandlerContainer.java @@ -67,7 +67,7 @@ public abstract class AbstractHandlerContainer extends AbstractHandler implement if (handler==null) return list; - if (handler!=null && (byClass==null || byClass.isAssignableFrom(handler.getClass()))) + if (byClass==null || byClass.isAssignableFrom(handler.getClass())) list=LazyList.add(list, handler); if (handler instanceof AbstractHandlerContainer) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java index 9f9d61715a..cf0b27e6cd 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java @@ -83,7 +83,7 @@ import org.eclipse.jetty.util.resource.Resource; */ public class ContextHandler extends ScopedHandler implements Attributes, Server.Graceful, CompleteHandler { - private static ThreadLocal<Context> __context=new ThreadLocal<Context>(); + private static final ThreadLocal<Context> __context=new ThreadLocal<Context>(); public static final String MANAGED_ATTRIBUTES = "org.eclipse.jetty.server.servlet.ManagedAttributes"; /* ------------------------------------------------------------ */ @@ -95,8 +95,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server. */ public static Context getCurrentContext() { - Context context = __context.get(); - return context; + return __context.get(); } protected Context _scontext; @@ -294,7 +293,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server. if (_connectors==null || _connectors.size()==0) return null; - return (String[])_connectors.toArray(new String[_connectors.size()]); + return _connectors.toArray(new String[_connectors.size()]); } /* ------------------------------------------------------------ */ @@ -400,7 +399,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server. */ public String getInitParameter(String name) { - return (String)_initParams.get(name); + return _initParams.get(name); } /* ------------------------------------------------------------ */ @@ -632,9 +631,8 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server. if (managedAttributes!=null) { _managedAttributes=new HashSet<String>(); - String[] attributes = managedAttributes.toString().split(","); - for (String s : attributes) - _managedAttributes.add(s); + String[] attributes = managedAttributes.split(","); + _managedAttributes.addAll(Arrays.asList(attributes)); Enumeration e = _scontext.getAttributeNames(); while(e.hasMoreElements()) @@ -857,6 +855,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server. } // start manual inline of nextScope(target,baseRequest,request,response); + //noinspection ConstantIfStatement if (false) nextScope(target,baseRequest,request,response); else if (_nextScope!=null) @@ -920,6 +919,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server. throw new HttpException(HttpServletResponse.SC_NOT_FOUND); // start manual inline of nextHandle(target,baseRequest,request,response); + //noinspection ConstantIfStatement if (false) nextHandle(target,baseRequest,request,response); else if (_nextScope!=null && _nextScope==_handler) @@ -1319,9 +1319,9 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server. { if (_localeEncodingMap==null) return null; - String encoding = (String)_localeEncodingMap.get(locale.toString()); + String encoding = _localeEncodingMap.get(locale.toString()); if (encoding==null) - encoding = (String)_localeEncodingMap.get(locale.getLanguage()); + encoding = _localeEncodingMap.get(locale.getLanguage()); return encoding; } @@ -1759,7 +1759,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server. } setManagedAttribute(name,value); - Object old_value=_contextAttributes==null?null:_contextAttributes.getAttribute(name); + Object old_value=_contextAttributes.getAttribute(name); if (value==null) _contextAttributes.removeAttribute(name); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandlerCollection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandlerCollection.java index ee0fb81235..cb722cc830 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandlerCollection.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandlerCollection.java @@ -271,7 +271,7 @@ public class ContextHandlerCollection extends HandlerCollection { try { - ContextHandler context = (ContextHandler)_contextClass.newInstance(); + ContextHandler context = _contextClass.newInstance(); context.setContextPath(contextPath); context.setResourceBase(resourceBase); addHandler(context); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java index e1360806e3..5b336c2e92 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/DefaultHandler.java @@ -48,7 +48,7 @@ import org.eclipse.jetty.util.log.Log; */ public class DefaultHandler extends AbstractHandler { - long _faviconModified=(System.currentTimeMillis()/1000)*1000; + final long _faviconModified=(System.currentTimeMillis()/1000)*1000; byte[] _favicon; boolean _serveIcon=true; @@ -165,8 +165,6 @@ public class DefaultHandler extends AbstractHandler OutputStream out=response.getOutputStream(); writer.writeTo(out); out.close(); - - return; } /* ------------------------------------------------------------ */ diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerCollection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerCollection.java index fb49cc857d..fb7f5421b0 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerCollection.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HandlerCollection.java @@ -72,7 +72,7 @@ public class HandlerCollection extends AbstractHandlerContainer if (!_mutableWhenRunning && isStarted()) throw new IllegalStateException(STARTED); - Handler [] old_handlers = _handlers==null?null:(Handler[])_handlers.clone(); + Handler [] old_handlers = _handlers==null?null:_handlers.clone(); if (getServer()!=null) getServer().getContainer().update(this, old_handlers, handlers, "handler"); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java index 111211732b..5c35e0b6ba 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java @@ -89,10 +89,6 @@ public class HotSwapHandler extends AbstractHandlerContainer old_handler.stop(); } - catch(Error e) - { - throw e; - } catch(RuntimeException e) { throw e; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/MovedContextHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/MovedContextHandler.java index 55d9d944ee..219206e2bf 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/MovedContextHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/MovedContextHandler.java @@ -33,11 +33,11 @@ import org.eclipse.jetty.util.URIUtil; */ public class MovedContextHandler extends ContextHandler { + final Redirector _redirector; String _newContextURL; boolean _discardPathInfo; boolean _discardQuery; boolean _permanent; - Redirector _redirector; String _expires; public MovedContextHandler() diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java index 781566143a..debbe29a76 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ResourceHandler.java @@ -202,8 +202,7 @@ public class ResourceHandler extends AbstractHandler try { path=URIUtil.canonicalPath(path); - Resource resource=base.addPath(path); - return resource; + return base.addPath(path); } catch(Exception e) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ScopedHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ScopedHandler.java index 17d925109b..e8709e68b8 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ScopedHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ScopedHandler.java @@ -77,7 +77,7 @@ import org.eclipse.jetty.server.Request; */ public abstract class ScopedHandler extends HandlerWrapper { - private static ThreadLocal<ScopedHandler> __outerScope= new ThreadLocal<ScopedHandler>(); + private static final ThreadLocal<ScopedHandler> __outerScope= new ThreadLocal<ScopedHandler>(); protected ScopedHandler _outerScope; protected ScopedHandler _nextScope; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/StatisticsHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/StatisticsHandler.java index b1ea429ecc..b569a09a0d 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/StatisticsHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/StatisticsHandler.java @@ -88,10 +88,9 @@ public class StatisticsHandler extends HandlerWrapper implements CompleteHandler long timestamp1=timestamp0; try { + AsyncContinuation asyncContextState=baseRequest.getAsyncContinuation(); synchronized(this) { - AsyncContinuation asyncContextState=baseRequest.getAsyncContinuation(); - if(asyncContextState==null) { _requests++; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/nio/BlockingChannelConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/nio/BlockingChannelConnector.java index d167e43ce5..0994ccbcfb 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/nio/BlockingChannelConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/nio/BlockingChannelConnector.java @@ -121,8 +121,8 @@ public class BlockingChannelConnector extends AbstractNIOConnector /* ------------------------------------------------------------------------------- */ private class Connection extends ChannelEndPoint implements Runnable { + final HttpConnection _connection; boolean _dispatched=false; - HttpConnection _connection; int _sotimeout; Connection(ByteChannel channel) @@ -136,7 +136,7 @@ public class BlockingChannelConnector extends AbstractNIOConnector if (!getThreadPool().dispatch(this)) { Log.warn("dispatch failed for {}",_connection); - close(); + Connection.this.close(); } } @@ -166,19 +166,19 @@ public class BlockingChannelConnector extends AbstractNIOConnector catch (EofException e) { Log.debug("EOF", e); - try{close();} + try{Connection.this.close();} catch(IOException e2){Log.ignore(e2);} } catch (HttpException e) { Log.debug("BAD", e); - try{close();} + try{Connection.this.close();} catch(IOException e2){Log.ignore(e2);} } catch(Throwable e) { Log.warn("handle failed",e); - try{close();} + try{Connection.this.close();} catch(IOException e2){Log.ignore(e2);} } finally diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/nio/SelectChannelConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/nio/SelectChannelConnector.java index 99684ba376..b4ecc4cd66 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/nio/SelectChannelConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/nio/SelectChannelConnector.java @@ -61,11 +61,11 @@ import org.eclipse.jetty.util.thread.Timeout.Task; */ public class SelectChannelConnector extends AbstractNIOConnector { - protected transient ServerSocketChannel _acceptChannel; + protected ServerSocketChannel _acceptChannel; private long _lowResourcesConnections; private long _lowResourcesMaxIdleTime; - private SelectorManager _manager = new SelectorManager() + private final SelectorManager _manager = new SelectorManager() { protected SocketChannel acceptChannel(SelectionKey key) throws IOException { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionIdManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionIdManager.java index f02388c7dc..40433178ea 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionIdManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionIdManager.java @@ -33,7 +33,7 @@ public abstract class AbstractSessionIdManager extends AbstractLifeCycle impleme protected Random _random; protected boolean _weakRandom; protected String _workerName; - protected Server _server; + protected final Server _server; public AbstractSessionIdManager(Server server) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionManager.java index 150648f7bb..f429239e41 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/AbstractSessionManager.java @@ -152,7 +152,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement if (_sessionIdManager==null) { - Server server=getSessionHandler().getServer(); + final Server server=getSessionHandler().getServer(); synchronized (server) { _sessionIdManager=server.getSessionIdManager(); @@ -544,6 +544,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement */ protected void addSession(Session session, boolean created) { + //noinspection SynchronizeOnNonFinalField synchronized (_sessionIdManager) { _sessionIdManager.addSession(session); @@ -627,6 +628,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement public void removeSession(Session session, boolean invalidate) { // Remove session from context and global maps + //noinspection SynchronizeOnNonFinalField synchronized (_sessionIdManager) { boolean removed = false; @@ -1082,8 +1084,6 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement if (old_value==null) l.attributeAdded(event); - else if (value==null) - l.attributeRemoved(event); else l.attributeReplaced(event); } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HashSessionIdManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HashSessionIdManager.java index ba72362d3d..ef9543678a 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HashSessionIdManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HashSessionIdManager.java @@ -228,7 +228,7 @@ public class HashSessionIdManager extends AbstractLifeCycle implements SessionId ?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^(((long)request.hashCode())<<32)) :_random.nextLong(); r^=created; - if (request!=null && request.getRemoteAddr()!=null) + if (request.getRemoteAddr()!=null) r^=request.getRemoteAddr().hashCode(); if (r<0) r=-r; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HashSessionManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HashSessionManager.java index a7b7c97727..a82a79d889 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HashSessionManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HashSessionManager.java @@ -286,7 +286,7 @@ public class HashSessionManager extends AbstractSessionManager long idleTime=session._maxIdleMs; if (idleTime>0&&session._accessed+idleTime<System.currentTimeMillis()) { - ((Session)session).timeout(); + session.timeout(); int nbsess=this._sessions.size(); if (nbsess<this._minSessions) this._minSessions=nbsess; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java index 0e386e1f28..2148dde7a3 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionIdManager.java @@ -52,7 +52,7 @@ import org.eclipse.jetty.util.log.Log; */ public class JDBCSessionIdManager extends AbstractSessionIdManager { - protected HashSet<String> _sessionIds = new HashSet(); + protected final HashSet<String> _sessionIds = new HashSet(); protected String _driverClassName; protected String _connectionUrl; protected DataSource _datasource; @@ -353,8 +353,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager Handler[] contexts = _server.getChildHandlersByClass(ContextHandler.class); for (int i=0; contexts!=null && i<contexts.length; i++) { - SessionManager manager = (SessionManager) - ((SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class)).getSessionManager(); + SessionManager manager = ((SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class)).getSessionManager(); if (manager instanceof JDBCSessionManager) { @@ -597,10 +596,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager PreparedStatement statement = connection.prepareStatement(_queryId); statement.setString(1, id); ResultSet result = statement.executeQuery(); - if (result.next()) - return true; - else - return false; + return result.next(); } finally { @@ -651,8 +647,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager Handler[] contexts = _server.getChildHandlersByClass(ContextHandler.class); for (int i=0; contexts!=null && i<contexts.length; i++) { - SessionManager manager = (SessionManager) - ((SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class)).getSessionManager(); + SessionManager manager = ((SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class)).getSessionManager(); if (manager instanceof JDBCSessionManager) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java index 963a0a57dc..18eaa9a86a 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/JDBCSessionManager.java @@ -82,7 +82,7 @@ public class JDBCSessionManager extends AbstractSessionManager */ public class SessionData { - private String _id; + private final String _id; private String _rowId; private long _accessed; private long _lastAccessed; @@ -249,7 +249,7 @@ public class JDBCSessionManager extends AbstractSessionManager */ public class Session extends AbstractSessionManager.Session { - private SessionData _data; + private final SessionData _data; private boolean _dirty=false; /** @@ -622,9 +622,9 @@ public class JDBCSessionManager extends AbstractSessionManager //then session data will be lost. try { - ((JDBCSessionManager.Session)session).willPassivate(); + session.willPassivate(); storeSession(((JDBCSessionManager.Session)session)._data); - ((JDBCSessionManager.Session)session).didActivate(); + session.didActivate(); } catch (Exception e) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/ServletSSL.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/ServletSSL.java index 3c1cabf1d0..47bce46869 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/ServletSSL.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/ServletSSL.java @@ -54,7 +54,7 @@ public class ServletSSL * @param cipherSuite String name of the TLS cipher suite. * @return int indicating the effective key entropy bit-length. */ - public static final int deduceKeyLength(String cipherSuite) + public static int deduceKeyLength(String cipherSuite) { // Roughly ordered from most common to least common. if (cipherSuite == null) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/SslSelectChannelConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/SslSelectChannelConnector.java index bc7f55a049..15cdde74c1 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/SslSelectChannelConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/SslSelectChannelConnector.java @@ -634,9 +634,9 @@ public class SslSelectChannelConnector extends SelectChannelConnector */ private class CachedInfo { - private X509Certificate[] _certs; - private Integer _keySize; - private String _idStr; + private final X509Certificate[] _certs; + private final Integer _keySize; + private final String _idStr; CachedInfo(Integer keySize, X509Certificate[] certs,String idStr) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/SslSocketConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/SslSocketConnector.java index 2919302792..4238526acd 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/SslSocketConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ssl/SslSocketConnector.java @@ -595,9 +595,9 @@ public class SslSocketConnector extends SocketConnector */ private class CachedInfo { - private X509Certificate[] _certs; - private Integer _keySize; - private String _idStr; + private final X509Certificate[] _certs; + private final Integer _keySize; + private final String _idStr; CachedInfo(Integer keySize, X509Certificate[] certs,String id) diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncStressTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncStressTest.java index 80477eeda8..9d16d60ebf 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncStressTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncStressTest.java @@ -169,7 +169,7 @@ public class AsyncStressTest extends TestCase private static class SuspendHandler extends HandlerWrapper { - private Timer _timer; + private final Timer _timer; public SuspendHandler() { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/BusySelectChannelServerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/BusySelectChannelServerTest.java index 038718664d..2a97454c6a 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/BusySelectChannelServerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/BusySelectChannelServerTest.java @@ -91,7 +91,7 @@ public class BusySelectChannelServerTest extends HttpServerTestBase if (x<8) return 0; - if (x<16 & buffer.space()>=1) + if (x<16 && buffer.space()>=1) { NIOBuffer one = new IndirectNIOBuffer(1); int l=super.fill(one); @@ -100,7 +100,7 @@ public class BusySelectChannelServerTest extends HttpServerTestBase return l; } - if (x<24 & buffer.space()>=2) + if (x<24 && buffer.space()>=2) { NIOBuffer two = new IndirectNIOBuffer(2); int l=super.fill(two); @@ -111,7 +111,7 @@ public class BusySelectChannelServerTest extends HttpServerTestBase return l; } - if (x<64 & buffer.space()>=3) + if (x<64 && buffer.space()>=3) { NIOBuffer three = new IndirectNIOBuffer(3); int l=super.fill(three); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java b/jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java index c06da7ec27..1eb452291b 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/DumpHandler.java @@ -127,6 +127,8 @@ public class DumpHandler extends AbstractHandler { String cookie_action=request.getParameter("Button"); try{ + String val=request.getParameter("CookieVal"); + val=val.replaceAll("[ \n\r=<>]","?"); Cookie cookie= new Cookie(cookie_name.trim(), request.getParameter("CookieVal")); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java index 73f89b6a96..c12d896bd8 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java @@ -261,7 +261,7 @@ public class HttpServerTestBase extends TestCase int[] points=new int[pointCount]; StringBuilder message=new StringBuilder(); - message.append("iteration #"+(i+1)); + message.append("iteration #").append(i + 1); // Pick fragment points at random for (int j=0; j<points.length; ++j) @@ -306,7 +306,7 @@ public class HttpServerTestBase extends TestCase int[] points=new int[] { i }; StringBuilder message=new StringBuilder(); - message.append("iteration #"+(i+1)); + message.append("iteration #").append(i + 1); // Sort the list Arrays.sort(points); @@ -358,7 +358,7 @@ public class HttpServerTestBase extends TestCase OutputStream os=client.getOutputStream(); StringBuilder message=new StringBuilder(); - message.append("iteration #"+(i+1)); + message.append("iteration #").append(i + 1); writeFragments(bytes,badPoints[i],message,os); // Read the response @@ -802,7 +802,7 @@ public class HttpServerTestBase extends TestCase Thread.sleep(PAUSE); // Update the log message - message.append(" point #"+(j+1)+": "+point); + message.append(" point #").append(j + 1).append(": ").append(point); } // Write the last fragment diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ResponseTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ResponseTest.java index 66b1aae0c8..9b8d50e22f 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ResponseTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ResponseTest.java @@ -392,7 +392,7 @@ public class ResponseTest extends TestCase while (line!=null && line.length()==0) line = reader.readLine(); - assertTrue(line.startsWith("HTTP/1.1 200 OK")); + assertTrue(line!=null && line.startsWith("HTTP/1.1 200 OK")); } finally diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/StressTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/StressTest.java index 48dd031638..3309f855ca 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/StressTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/StressTest.java @@ -22,6 +22,7 @@ import java.util.Queue; import java.util.Random; import java.util.Timer; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.ServletException; @@ -33,9 +34,12 @@ import junit.framework.TestCase; import org.eclipse.jetty.server.bio.SocketConnector; import org.eclipse.jetty.server.handler.HandlerWrapper; import org.eclipse.jetty.server.nio.SelectChannelConnector; +import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.thread.QueuedThreadPool; +import org.eclipse.jetty.util.thread.ExecutorThreadPool; +import org.eclipse.jetty.util.thread.ThreadPool; public class StressTest extends TestCase { @@ -45,7 +49,8 @@ public class StressTest extends TestCase protected InetAddress _addr; protected int _port; protected volatile AtomicInteger[] _loops; - protected QueuedThreadPool _threads=new QueuedThreadPool(); + protected QueuedThreadPool _threads=new QueuedThreadPool(new BlockingArrayQueue<Runnable>(4,4)); + // protected ExecutorThreadPool _threads=new ExecutorThreadPool(100,500,10000,TimeUnit.MILLISECONDS); protected boolean _stress; private AtomicInteger _handled=new AtomicInteger(0); private ConcurrentLinkedQueue[] _latencies= { @@ -61,6 +66,7 @@ public class StressTest extends TestCase protected void setUp() throws Exception { _stress= Boolean.getBoolean("STRESS"); + _threads.setMaxThreads(500); _server.setThreadPool(_threads); SelectChannelConnector c_connector=new SelectChannelConnector(); @@ -332,10 +338,11 @@ public class StressTest extends TestCase } finally { - int quantums=48; - int[][] count = new int[_latencies.length][quantums]; - int length[] = new int[_latencies.length]; - int other[] = new int[_latencies.length]; + System.err.println(); + final int quantums=48; + final int[][] count = new int[_latencies.length][quantums]; + final int length[] = new int[_latencies.length]; + final int other[] = new int[_latencies.length]; for (int i=0;i<_latencies.length;i++) { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ScopedHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ScopedHandlerTest.java index c8cb181d7e..f4c4568329 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ScopedHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ScopedHandlerTest.java @@ -113,12 +113,12 @@ public class ScopedHandlerTest extends TestCase { try { - _history.append(">S"+_name); + _history.append(">S").append(_name); super.nextScope(target,baseRequest,request, response); } finally { - _history.append("<S"+_name); + _history.append("<S").append(_name); } } @@ -126,12 +126,12 @@ public class ScopedHandlerTest extends TestCase { try { - _history.append(">W"+_name); + _history.append(">W").append(_name); super.nextHandle(target,baseRequest,request,response); } finally { - _history.append("<W"+_name); + _history.append("<W").append(_name); } } @@ -150,12 +150,12 @@ public class ScopedHandlerTest extends TestCase { try { - _history.append(">H"+_name); + _history.append(">H").append(_name); super.handle(target,baseRequest,request, response); } finally { - _history.append("<H"+_name); + _history.append("<H").append(_name); } } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/StatisticsHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/StatisticsHandlerTest.java index 767dd82f3d..e2f421cc41 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/StatisticsHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/StatisticsHandlerTest.java @@ -203,7 +203,7 @@ public class StatisticsHandlerTest extends TestCase private static class ActiveHandler extends HandlerWrapper { - private Object _lock; + private final Object _lock; public ActiveHandler(Object lock) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/BlockingArrayQueue.java b/jetty-util/src/main/java/org/eclipse/jetty/util/BlockingArrayQueue.java index 2a07f45e66..c53e20ae81 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/BlockingArrayQueue.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/BlockingArrayQueue.java @@ -14,13 +14,15 @@ package org.eclipse.jetty.util; import java.util.AbstractList; +import java.util.Collection; import java.util.NoSuchElementException; -import java.util.Queue; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; + /* ------------------------------------------------------------ */ /** Queue backed by a circular array. * @@ -38,17 +40,18 @@ import java.util.concurrent.locks.ReentrantLock; * * @param <E> The element type */ -public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> +public class BlockingArrayQueue<E> extends AbstractList<E> implements BlockingQueue<E> { - public final int DEFAULT_CAPACITY=64; - public final int DEFAULT_GROWTH=32; - protected final int _limit; - protected final AtomicInteger _size=new AtomicInteger(); - protected final int _growCapacity; + public final int DEFAULT_CAPACITY=128; + public final int DEFAULT_GROWTH=64; + private final int _limit; + private final AtomicInteger _size=new AtomicInteger(); + private final int _growCapacity; - protected Object[] _elements; - protected int _head; - protected int _tail; + private volatile int _capacity; + private Object[] _elements; + private int _head; + private int _tail; private final ReentrantLock _headLock = new ReentrantLock(); private final Condition _notEmpty = _headLock.newCondition(); @@ -60,8 +63,9 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> */ public BlockingArrayQueue() { - _elements=new Object[64]; - _growCapacity=32; + _elements=new Object[DEFAULT_CAPACITY]; + _growCapacity=DEFAULT_GROWTH; + _capacity=_elements.length; _limit=Integer.MAX_VALUE; } @@ -72,6 +76,7 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> public BlockingArrayQueue(int limit) { _elements=new Object[limit]; + _capacity=_elements.length; _growCapacity=-1; _limit=limit; } @@ -84,6 +89,7 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> public BlockingArrayQueue(int capacity,int growBy) { _elements=new Object[capacity]; + _capacity=_elements.length; _growCapacity=growBy; _limit=Integer.MAX_VALUE; } @@ -100,6 +106,7 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> throw new IllegalArgumentException(); _elements=new Object[capacity]; + _capacity=_elements.length; _growCapacity=growBy; _limit=limit; } @@ -107,7 +114,7 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> /* ------------------------------------------------------------ */ public int getCapacity() { - return _elements.length; + return _capacity; } /* ------------------------------------------------------------ */ @@ -141,7 +148,6 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> _headLock.lock(); // Size cannot shrink try { - if (_size.get() > 0) e = (E)_elements[_head]; } @@ -165,29 +171,28 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> { if (_size.get() >= _limit) return false; - else + + // should we expand array? + if (_size.get()==_capacity) { - // should we expand array? - if (_size.get()==_elements.length) + _headLock.lock(); // Need to grow array + try { - _headLock.lock(); // Need to grow array - try - { - if (!grow()) - return false; - } - finally - { - _headLock.unlock(); - } + if (!grow()) + return false; + } + finally + { + _headLock.unlock(); } - - // add the element - _elements[_tail]=e; - _tail=(_tail+1)%_elements.length; - - not_empty=0==_size.getAndIncrement(); } + + // add the element + _elements[_tail]=e; + _tail=(_tail+1)%_capacity; + + not_empty=0==_size.getAndIncrement(); + } finally { @@ -225,7 +230,8 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> { final int head=_head; e = (E)_elements[head]; - _head=(head+1)%_elements.length; + _elements[head]=null; + _head=(head+1)%_capacity; if (_size.decrementAndGet()>0) _notEmpty.signal(); @@ -267,7 +273,8 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> final int head=_head; e = (E)_elements[head]; - _head=(head+1)%_elements.length; + _elements[head]=null; + _head=(head+1)%_capacity; if (_size.decrementAndGet()>0) _notEmpty.signal(); @@ -285,7 +292,7 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> * Retrieves and removes the head of this queue, waiting * if necessary up to the specified wait time if no elements are * present on this queue. - * @param timeout how long to wait before giving up, in units of + * @param time how long to wait before giving up, in units of * <tt>unit</tt> * @param unit a <tt>TimeUnit</tt> determining how to interpret the * <tt>timeout</tt> parameter @@ -319,7 +326,8 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> } e = (E)_elements[_head]; - _head=(_head+1)%_elements.length; + _elements[_head]=null; + _head=(_head+1)%_capacity; if (_size.decrementAndGet()>0) _notEmpty.signal(); @@ -389,8 +397,8 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> if (index<0 || index>=_size.get()) throw new IndexOutOfBoundsException("!("+0+"<"+index+"<="+_size+")"); int i = _head+index; - if (i>=_elements.length) - i-=_elements.length; + if (i>=_capacity) + i-=_capacity; return (E)_elements[i]; } finally @@ -418,8 +426,8 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> throw new IndexOutOfBoundsException("!("+0+"<"+index+"<="+_size+")"); int i = _head+index; - if (i>=_elements.length) - i-=_elements.length; + if (i>=_capacity) + i-=_capacity; E old=(E)_elements[i]; if (i<_tail) @@ -430,15 +438,15 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> } else { - System.arraycopy(_elements,i+1,_elements,i,_elements.length-i-1); + System.arraycopy(_elements,i+1,_elements,i,_capacity-i-1); if (_tail>0) { - _elements[_elements.length]=_elements[0]; + _elements[_capacity]=_elements[0]; System.arraycopy(_elements,1,_elements,0,_tail-1); _tail--; } else - _tail=_elements.length-1; + _tail=_capacity-1; _size.decrementAndGet(); } @@ -473,8 +481,8 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> throw new IndexOutOfBoundsException("!("+0+"<"+index+"<="+_size+")"); int i = _head+index; - if (i>=_elements.length) - i-=_elements.length; + if (i>=_capacity) + i-=_capacity; E old=(E)_elements[i]; _elements[i]=e; return old; @@ -517,11 +525,11 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> throw new IllegalStateException("full"); int i = _head+index; - if (i>=_elements.length) - i-=_elements.length; + if (i>=_capacity) + i-=_capacity; _size.incrementAndGet(); - _tail=(_tail+1)%_elements.length; + _tail=(_tail+1)%_capacity; if (i<_tail) @@ -534,10 +542,10 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> if (_tail>0) { System.arraycopy(_elements,0,_elements,1,_tail); - _elements[0]=_elements[_elements.length-1]; + _elements[0]=_elements[_capacity-1]; } - System.arraycopy(_elements,i,_elements,i+1,_elements.length-i-1); + System.arraycopy(_elements,i,_elements,i+1,_capacity-i-1); _elements[i]=e; } } @@ -559,28 +567,97 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements Queue<E> if (_growCapacity<=0) return false; - final int head=_head; - final int tail=_tail; - final int s; - - Object[] elements=new Object[_elements.length+_growCapacity]; + _tailLock.lock(); + try + { + _headLock.lock(); + try + { + final int head=_head; + final int tail=_tail; + final int new_tail; + + Object[] elements=new Object[_capacity+_growCapacity]; + + if (head<tail) + { + new_tail=tail-head; + System.arraycopy(_elements,head,elements,0,new_tail); + } + else if (head>tail || _size.get()>0) + { + new_tail=_capacity+tail-head; + int cut=_capacity-head; + System.arraycopy(_elements,head,elements,0,cut); + System.arraycopy(_elements,0,elements,cut,tail); + } + else + { + new_tail=0; + } + + _elements=elements; + _capacity=_elements.length; + _head=0; + _tail=new_tail; + return true; + } + finally + { + _headLock.unlock(); + } + } + finally + { + _tailLock.unlock(); + } + + } + + /* ------------------------------------------------------------ */ + public int drainTo(Collection<? super E> c) + { + throw new UnsupportedOperationException(); + } + + /* ------------------------------------------------------------ */ + public int drainTo(Collection<? super E> c, int maxElements) + { + throw new UnsupportedOperationException(); + } - if (head<tail) + /* ------------------------------------------------------------ */ + public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException + { + throw new UnsupportedOperationException(); + } + + /* ------------------------------------------------------------ */ + public void put(E o) throws InterruptedException + { + if (!add(o)) + throw new IllegalStateException("full"); + } + + /* ------------------------------------------------------------ */ + public int remainingCapacity() + { + _tailLock.lock(); + try { - s=tail-head; - System.arraycopy(_elements,head,elements,0,s); + _headLock.lock(); + try + { + return getCapacity()-size(); + } + finally + { + _headLock.unlock(); + } } - else + finally { - s=_elements.length+tail-head; - int cut=_elements.length-head; - System.arraycopy(_elements,head,elements,0,cut); - System.arraycopy(_elements,0,elements,cut,tail); + _tailLock.unlock(); } - _elements=elements; - _head=0; - _tail=s; - - return true; } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java index 6d07f329ff..3fcdeda5b3 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java @@ -14,6 +14,9 @@ package org.eclipse.jetty.util.thread; +import java.util.Queue; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; @@ -34,7 +37,7 @@ public class QueuedThreadPool extends AbstractLifeCycle implements ThreadPool, E private final AtomicLong _lastShrink = new AtomicLong(); private final ConcurrentLinkedQueue<Thread> _threads=new ConcurrentLinkedQueue<Thread>(); private final Object _joinLock = new Object(); - private BlockingArrayQueue<Runnable> _jobs; + private BlockingQueue<Runnable> _jobs; private String _name; private int _maxIdleTimeMs=60000; private int _maxThreads=254; @@ -61,6 +64,17 @@ public class QueuedThreadPool extends AbstractLifeCycle implements ThreadPool, E setMaxThreads(maxThreads); } + /* ------------------------------------------------------------------- */ + /* Construct + */ + public QueuedThreadPool(BlockingQueue<Runnable> jobQ) + { + this(); + _jobs=jobQ; + _jobs.clear(); + } + + /* ------------------------------------------------------------ */ @Override protected void doStart() throws Exception @@ -68,8 +82,11 @@ public class QueuedThreadPool extends AbstractLifeCycle implements ThreadPool, E super.doStart(); _threadsStarted.set(0); - _jobs=_maxQueued>0 ?new BlockingArrayQueue<Runnable>(_minThreads,_minThreads,_maxQueued) + if (_jobs==null) + { + _jobs=_maxQueued>0 ?new ArrayBlockingQueue<Runnable>(_maxQueued) :new BlockingArrayQueue<Runnable>(_minThreads,_minThreads); + } int threads=_threadsStarted.get(); while (isRunning() && threads<_minThreads) @@ -207,9 +224,18 @@ public class QueuedThreadPool extends AbstractLifeCycle implements ThreadPool, E */ public int getMaxQueued() { + return _maxQueued; + } + + /* ------------------------------------------------------------ */ + /** + * @param max job queue size + */ + public void setMaxQueued(int max) + { if (isRunning()) throw new IllegalStateException("started"); - return _maxQueued; + _maxQueued=max; } /* ------------------------------------------------------------ */ |