static code analysis cleanups

git-svn-id: svn+ssh://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk@411 7e9141cc-0065-0410-87d8-b60c137991c4
This commit is contained in:
Greg Wilkins 2009-06-17 03:56:36 +00:00
parent ce2a2f5a25
commit a8fa5dceef
71 changed files with 401 additions and 417 deletions

View File

@ -11,6 +11,7 @@ jetty-7.0.0.M3-SNAPSHOT
+ 276545 Quoted cookie paths + 276545 Quoted cookie paths
+ 279725 Support 100 and 102 expectations + 279725 Support 100 and 102 expectations
+ Refactored AbstractBuffers to HttpBuffers for performance + Refactored AbstractBuffers to HttpBuffers for performance
+ Numerous cleanups from static code analysis
jetty-7.0.0.M2 18 May 2009 jetty-7.0.0.M2 18 May 2009
+ JETTY-937 Work around Sun JVM bugs + JETTY-937 Work around Sun JVM bugs

View File

@ -161,13 +161,10 @@ public abstract class AbstractGenerator implements Generator
_buffer=_buffers.getBuffer(); _buffer=_buffers.getBuffer();
if (contentBufferSize > _buffer.capacity()) if (contentBufferSize > _buffer.capacity())
{ {
if (_buffer != null) Buffer nb = _buffers.getBuffer(contentBufferSize);
{ nb.put(_buffer);
Buffer nb = _buffers.getBuffer(contentBufferSize); _buffers.returnBuffer(_buffer);
nb.put(_buffer); _buffer = nb;
_buffers.returnBuffer(_buffer);
_buffer = nb;
}
} }
} }
@ -346,7 +343,6 @@ public abstract class AbstractGenerator implements Generator
{ {
if(_buffer!=null) if(_buffer!=null)
_buffer.clear(); _buffer.clear();
return;
} }
else else
{ {

View File

@ -24,7 +24,7 @@ import org.eclipse.jetty.util.Utf8StringBuffer;
public class EncodedHttpURI extends HttpURI public class EncodedHttpURI extends HttpURI
{ {
private String _encoding; private final String _encoding;
public EncodedHttpURI(String encoding) public EncodedHttpURI(String encoding)
{ {

View File

@ -41,6 +41,7 @@ import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.StringMap; import org.eclipse.jetty.util.StringMap;
import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil; 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"; public final static String __separators = ", \t";
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private static String[] DAYS = private static final String[] DAYS =
{ "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; { "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"}; { "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 @Override
protected DateGenerator initialValue() 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 @Override
protected DateParser initialValue() protected DateParser initialValue()
@ -308,7 +309,7 @@ public class HttpFields
if (field != null) return true; if (field != null) return true;
while (i < _fields.size()) while (i < _fields.size())
{ {
Field f = (Field) _fields.get(i++); Field f = _fields.get(i++);
if (f != null && f._prev == null && f._revision == revision) if (f != null && f._prev == null && f._revision == revision)
{ {
field = f; field = f;
@ -354,13 +355,13 @@ public class HttpFields
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private Field getField(String name) 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) 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; if (tok != null && tok.hasMoreElements()) return true;
while (e.hasMoreElements()) while (e.hasMoreElements())
{ {
String value = (String) e.nextElement(); String value = e.nextElement();
tok = new QuotedStringTokenizer(value, separators, false, false); tok = new QuotedStringTokenizer(value, separators, false, false);
if (tok.hasMoreElements()) return true; if (tok.hasMoreElements()) return true;
} }
@ -596,7 +597,7 @@ public class HttpFields
if (!(name instanceof BufferCache.CachedBuffer)) name = HttpHeaders.CACHE.lookup(name); 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. // Look for value to replace.
if (field != null) if (field != null)
@ -608,7 +609,6 @@ public class HttpFields
field.clear(); field.clear();
field = field._next; field = field._next;
} }
return;
} }
else else
{ {
@ -701,7 +701,7 @@ public class HttpFields
if (!(name instanceof BufferCache.CachedBuffer)) name = HttpHeaders.CACHE.lookup(name); if (!(name instanceof BufferCache.CachedBuffer)) name = HttpHeaders.CACHE.lookup(name);
Field field = (Field) _bufferMap.get(name); Field field = _bufferMap.get(name);
Field last = null; Field last = null;
if (field != null) if (field != null)
{ {
@ -751,7 +751,7 @@ public class HttpFields
*/ */
public void remove(Buffer name) public void remove(Buffer name)
{ {
Field field = (Field) _bufferMap.get(name); Field field = _bufferMap.get(name);
if (field != null) if (field != null)
{ {
@ -960,7 +960,7 @@ public class HttpFields
// Format value and params // Format value and params
StringBuilder buf = new StringBuilder(128); StringBuilder buf = new StringBuilder(128);
String name_value_params = null; String name_value_params;
QuotedStringTokenizer.quoteIfNeeded(buf, name); QuotedStringTokenizer.quoteIfNeeded(buf, name);
buf.append('='); buf.append('=');
if (value != null && value.length() > 0) if (value != null && value.length() > 0)
@ -1027,7 +1027,7 @@ public class HttpFields
{ {
for (int i = 0; i < _fields.size(); i++) 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); if (field != null && field._revision == _revision) field.put(buffer);
} }
BufferUtil.putCRLF(buffer); BufferUtil.putCRLF(buffer);
@ -1044,10 +1044,10 @@ public class HttpFields
} }
catch (Exception e) catch (Exception e)
{ {
e.printStackTrace(); Log.warn(e);
return e.toString();
} }
return null;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -1062,7 +1062,7 @@ public class HttpFields
_revision = 0; _revision = 0;
for (int i = _fields.size(); i-- > 0;) for (int i = _fields.size(); i-- > 0;)
{ {
Field field = (Field) _fields.get(i); Field field = _fields.get(i);
if (field != null) field.clear(); if (field != null) field.clear();
} }
} }
@ -1078,11 +1078,11 @@ public class HttpFields
{ {
for (int i = _fields.size(); i-- > 0;) for (int i = _fields.size(); i-- > 0;)
{ {
Field field = (Field) _fields.get(i); Field field = _fields.get(i);
if (field != null) field.destroy(); 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 final Float __one = new Float("1.0");
private static Float __zero = new Float("0.0"); private static final Float __zero = new Float("0.0");
private static StringMap __qualities = new StringMap(); private static final StringMap __qualities = new StringMap();
static static
{ {
__qualities.put(null, __one); __qualities.put(null, __one);

View File

@ -41,7 +41,7 @@ public class HttpGenerator extends AbstractGenerator
Buffer _schemeCode; Buffer _schemeCode;
Buffer _responseLine; Buffer _responseLine;
} }
private static Status[] __status = new Status[HttpStatus.MAX_CODE+1]; private static final Status[] __status = new Status[HttpStatus.MAX_CODE+1];
static static
{ {
int versionLength=HttpVersions.HTTP_1_1_BUFFER.length(); 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+3]=(byte)('0'+(i%10));
bytes[versionLength+4]=' '; bytes[versionLength+4]=' ';
for (int j=0;j<reason.length();j++) 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+5+reason.length()]=HttpTokens.CARRIAGE_RETURN;
bytes[versionLength+6+reason.length()]=HttpTokens.LINE_FEED; bytes[versionLength+6+reason.length()]=HttpTokens.LINE_FEED;
@ -82,18 +82,18 @@ public class HttpGenerator extends AbstractGenerator
// common _content // common _content
private static byte[] LAST_CHUNK = private static final byte[] LAST_CHUNK =
{ (byte) '0', (byte) '\015', (byte) '\012', (byte) '\015', (byte) '\012'}; { (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 final 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 final byte[] CONNECTION_KEEP_ALIVE = StringUtil.getBytes("Connection: keep-alive\015\012");
private static byte[] CONNECTION_CLOSE = StringUtil.getBytes("Connection: close\015\012"); private static final byte[] CONNECTION_CLOSE = StringUtil.getBytes("Connection: close\015\012");
private static byte[] CONNECTION_ = StringUtil.getBytes("Connection: "); private static final byte[] CONNECTION_ = StringUtil.getBytes("Connection: ");
private static byte[] CRLF = StringUtil.getBytes("\015\012"); private static final byte[] CRLF = StringUtil.getBytes("\015\012");
private static byte[] TRANSFER_ENCODING_CHUNKED = StringUtil.getBytes("Transfer-Encoding: chunked\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"); private static byte[] SERVER = StringUtil.getBytes("Server: Jetty(7.0.x)\015\012");
// other statics // other statics
private static int CHUNK_SPACE = 12; private static final int CHUNK_SPACE = 12;
public static void setServerVersion(String version) public static void setServerVersion(String version)
{ {
@ -235,7 +235,7 @@ public class HttpGenerator extends AbstractGenerator
if (_last || _state==STATE_END) if (_last || _state==STATE_END)
{ {
Log.debug("Ignoring extra content {}",new Byte(b)); Log.debug("Ignoring extra content {}",Byte.valueOf(b));
return false; return false;
} }
@ -303,8 +303,7 @@ public class HttpGenerator extends AbstractGenerator
public boolean isBufferFull() public boolean isBufferFull()
{ {
// Should we flush the buffers? // Should we flush the buffers?
boolean full = super.isBufferFull() || _bufferChunked || _bypass || (_contentLength == HttpTokens.CHUNKED_CONTENT && _buffer != null && _buffer.space() < CHUNK_SPACE); return super.isBufferFull() || _bufferChunked || _bypass || (_contentLength == HttpTokens.CHUNKED_CONTENT && _buffer != null && _buffer.space() < CHUNK_SPACE);
return full;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -842,6 +841,7 @@ public class HttpGenerator extends AbstractGenerator
_bufferChunked = true; _bufferChunked = true;
// Did we leave space at the start of the buffer. // Did we leave space at the start of the buffer.
//noinspection ConstantConditions
if (_buffer.getIndex() == CHUNK_SPACE) if (_buffer.getIndex() == CHUNK_SPACE)
{ {
// Oh yes, goodie! let's use it then! // Oh yes, goodie! let's use it then!

View File

@ -77,17 +77,24 @@ public class HttpHeaderValues extends BufferCache
CACHE.add("gzip,deflate",index++); CACHE.add("gzip,deflate",index++);
CACHE.add("deflate",index++); CACHE.add("deflate",index++);
InputStream ua = HttpHeaderValues.class.getResourceAsStream("/org/eclipse/jetty/http/useragents");
try try
{ {
InputStream ua = HttpHeaderValues.class.getResourceAsStream("/org/eclipse/jetty/http/useragents");
if (ua!=null) if (ua!=null)
{ {
LineNumberReader in = new LineNumberReader(new InputStreamReader(ua)); try
String line = in.readLine();
while (line!=null)
{ {
CACHE.add(line,index++); LineNumberReader in = new LineNumberReader(new InputStreamReader(ua));
line = in.readLine(); String line = in.readLine();
while (line!=null)
{
CACHE.add(line,index++);
line = in.readLine();
}
}
finally
{
ua.close();
} }
} }
} }

View File

@ -162,11 +162,8 @@ public class HttpParser implements Parser
public boolean isMoreInBuffer() public boolean isMoreInBuffer()
throws IOException throws IOException
{ {
if ( _header!=null && _header.hasContent() || return ( _header!=null && _header.hasContent() ||
_body!=null && _body.hasContent()) _body!=null && _body.hasContent());
return true;
return false;
} }
/* ------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------- */
@ -447,12 +444,12 @@ public class HttpParser implements Parser
Buffer header=_cached!=null?_cached:HttpHeaders.CACHE.lookup(_tok0); Buffer header=_cached!=null?_cached:HttpHeaders.CACHE.lookup(_tok0);
_cached=null; _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); int ho=HttpHeaders.CACHE.getOrdinal(header);
if (ho >= 0) if (ho >= 0)
{ {
int vo=-1; int vo;
switch (ho) switch (ho)
{ {
@ -849,6 +846,7 @@ public class HttpParser implements Parser
if (_body!=null && _buffer!=_body) if (_body!=null && _buffer!=_body)
_buffer=_body; _buffer=_body;
if (_buffer == _body) if (_buffer == _body)
//noinspection ConstantConditions
_buffer.compact(); _buffer.compact();
int space=_buffer.space(); int space=_buffer.space();

View File

@ -664,7 +664,7 @@ public class HttpStatus
public static final int MAX_CODE = 507; 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 static
{ {
@ -911,7 +911,7 @@ public class HttpStatus
{ {
return HttpStatus.isServerError(this._code); return HttpStatus.isServerError(this._code);
} }
}; }
/** /**

View File

@ -41,7 +41,7 @@ import org.eclipse.jetty.util.Utf8StringBuilder;
*/ */
public class HttpURI public class HttpURI
{ {
private static byte[] __empty={}; private static final byte[] __empty={};
private final static int private final static int
START=0, START=0,
AUTH_OR_PATH=1, AUTH_OR_PATH=1,
@ -68,7 +68,7 @@ public class HttpURI
int _end; int _end;
boolean _encoded=false; boolean _encoded=false;
Utf8StringBuilder _utf8b = new Utf8StringBuilder(64); final Utf8StringBuilder _utf8b = new Utf8StringBuilder(64);
public HttpURI() public HttpURI()
{ {
@ -487,8 +487,7 @@ public class HttpURI
if (bytes==null) if (bytes==null)
{ {
bytes=new byte[length]; bytes=new byte[length];
for (int j=0;j<n;j++) System.arraycopy(_raw,_path,bytes,0,n);
bytes[j]=_raw[_path+j];
} }
bytes[n++]=b; bytes[n++]=b;

View File

@ -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 * as it is assumed they would have been either encoded in the original URL or
* stripped from the path. * stripped from the path.
* <P> * <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. * possible then it should be synchronized at a higher level.
* *
* *
@ -83,7 +83,7 @@ public class PathMap extends HashMap implements Externalizable
List _defaultSingletonList=null; List _defaultSingletonList=null;
Entry _prefixDefault=null; Entry _prefixDefault=null;
Entry _default=null; Entry _default=null;
Set _entrySet; final Set _entrySet;
boolean _nodefault=false; boolean _nodefault=false;
/* --------------------------------------------------------------- */ /* --------------------------------------------------------------- */
@ -145,7 +145,7 @@ public class PathMap extends HashMap implements Externalizable
* path specifications. * path specifications.
* @param object The object the path maps to * @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); StringTokenizer tok = new StringTokenizer(pathSpec.toString(),__pathSpecSeparators);
Object old =null; 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) if (pathSpec!=null)
{ {
@ -510,8 +510,8 @@ public class PathMap extends HashMap implements Externalizable
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public static class Entry implements Map.Entry public static class Entry implements Map.Entry
{ {
private Object key; private final Object key;
private Object value; private final Object value;
private String mapped; private String mapped;
private transient String string; private transient String string;

View File

@ -40,7 +40,7 @@ public class B64Code
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
}; };
static byte[] code2nibble=null; static final byte[] code2nibble;
static static
{ {

View File

@ -39,13 +39,11 @@ public class Constraint implements Cloneable, Serializable
if (method == null) if (method == null)
return false; return false;
method = method.trim(); method = method.trim();
if (method.equals(__FORM_AUTH) return (method.equals(__FORM_AUTH)
|| method.equals(__BASIC_AUTH) || method.equals(__BASIC_AUTH)
|| method.equals (__DIGEST_AUTH) || method.equals (__DIGEST_AUTH)
|| method.equals (__CERT_AUTH) || method.equals (__CERT_AUTH)
|| method.equals(__CERT_AUTH2)) || method.equals(__CERT_AUTH2));
return true;
return false;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -74,7 +74,7 @@ public abstract class Credential
{ {
public static final String __TYPE = "CRYPT:"; public static final String __TYPE = "CRYPT:";
private String _cooked; private final String _cooked;
Crypt(String cooked) Crypt(String cooked)
{ {
@ -110,7 +110,7 @@ public abstract class Credential
private static MessageDigest __md; private static MessageDigest __md;
private byte[] _digest; private final byte[] _digest;
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
MD5(String digest) MD5(String digest)

View File

@ -107,6 +107,7 @@ public class Password extends Credential
if (o instanceof Password) if (o instanceof Password)
{ {
Password p = (Password) o; Password p = (Password) o;
//noinspection StringEquality
return p._pw == _pw || (null != _pw && _pw.equals(p._pw)); return p._pw == _pw || (null != _pw && _pw.equals(p._pw));
} }
@ -223,7 +224,7 @@ public class Password extends Credential
System.exit(1); System.exit(1);
} }
String p = arg[arg.length == 1 ? 0 : 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(pw.toString());
System.err.println(obfuscate(pw.toString())); System.err.println(obfuscate(pw.toString()));
System.err.println(Credential.MD5.digest(p)); System.err.println(Credential.MD5.digest(p));

View File

@ -23,6 +23,8 @@
package org.eclipse.jetty.http.security; package org.eclipse.jetty.http.security;
import org.eclipse.jetty.util.StringUtil;
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/** /**
* Unix Crypt. Implements the one way cryptography used by Unix systems for * 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 $ * @version $Id: UnixCrypt.java,v 1.1 2005/10/05 14:09:14 janb Exp $
* @author Greg Wilkins (gregw) * @author Greg Wilkins (gregw)
*/ */
public class UnixCrypt extends Object public class UnixCrypt
{ {
/* (mostly) Standard DES Tables from Tom Truscott */ /* (mostly) Standard DES Tables from Tom Truscott */
@ -104,22 +106,22 @@ public class UnixCrypt extends Object
/* ===== Tables that are initialized at run time ==================== */ /* ===== 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 */ /* 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 */ /* 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 */ /* 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. */ /* 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 */ /* 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 // PC1ROT - bit reverse, then PC1, then Rotate, then PC2
for (int i = 0; i < 64; i++) for (int i = 0; i < 64; i++)
perm[i] = (byte) 0; perm[i] = (byte) 0;
;
for (int i = 0; i < 64; i++) for (int i = 0; i < 64; i++)
{ {
int k; int k;
@ -443,7 +445,7 @@ public class UnixCrypt extends Object
rsltblock >>= 6; rsltblock >>= 6;
} }
return new String(cryptresult, 0x00, 0, 13); return new String(cryptresult, 0, 13);
} }
public static void main(String[] arg) public static void main(String[] arg)

View File

@ -43,23 +43,22 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
{ {
private static final ByteBuffer[] __NO_BUFFERS={}; private static final ByteBuffer[] __NO_BUFFERS={};
private Buffers _buffers; private final Buffers _buffers;
private SSLEngine _engine; private final SSLEngine _engine;
private ByteBuffer _inBuffer; private final SSLSession _session;
private NIOBuffer _inNIOBuffer; private final ByteBuffer _inBuffer;
private ByteBuffer _outBuffer; private final NIOBuffer _inNIOBuffer;
private NIOBuffer _outNIOBuffer; private final ByteBuffer _outBuffer;
private final NIOBuffer _outNIOBuffer;
private NIOBuffer[] _reuseBuffer=new NIOBuffer[2]; private final NIOBuffer[] _reuseBuffer=new NIOBuffer[2];
private ByteBuffer[] _gather=new ByteBuffer[2]; private final ByteBuffer[] _gather=new ByteBuffer[2];
private boolean _closing=false; private boolean _closing=false;
private SSLEngineResult _result; private SSLEngineResult _result;
private String _last; private String _last;
// ssl
protected SSLSession _session;
// TODO get rid of this // TODO get rid of this
// StringBuilder h = new StringBuilder(500); // 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) public SslSelectChannelEndPoint(Buffers buffers,SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey key, SSLEngine engine)
throws SSLException, IOException throws IOException
{ {
super(channel,selectSet,key); super(channel,selectSet,key);
_buffers=buffers; _buffers=buffers;
@ -111,7 +110,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
{ {
try try
{ {
_selectSet.getManager().dispatch(new Runnable() getSelectManager().dispatch(new Runnable()
{ {
public void run() public void run()
{ {
@ -258,9 +257,10 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
*/ */
public int fill(Buffer buffer) throws IOException public int fill(Buffer buffer) throws IOException
{ {
ByteBuffer bbuf=extractInputBuffer(buffer); final ByteBuffer bbuf=extractInputBuffer(buffer);
int size=buffer.length(); int size=buffer.length();
HandshakeStatus initialStatus = _engine.getHandshakeStatus(); HandshakeStatus initialStatus = _engine.getHandshakeStatus();
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (bbuf) synchronized (bbuf)
{ {
try try
@ -508,6 +508,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
if (flushed==0) if (flushed==0)
{ {
Thread.yield(); Thread.yield();
//noinspection UnusedAssignment
flushed=super.flush(_outNIOBuffer); flushed=super.flush(_outNIOBuffer);
// h.append("flushed2=").append(flushed).append(" of ").append(_outNIOBuffer.length()).append('\n'); // h.append("flushed2=").append(flushed).append(" of ").append(_outNIOBuffer.length()).append('\n');
} }
@ -590,9 +591,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
case CLOSED: case CLOSED:
_closing=true; _closing=true;
case OK: case OK:
boolean progress=total_filled>0 ||_result.bytesConsumed()>0 || _result.bytesProduced()>0; return total_filled>0 ||_result.bytesConsumed()>0 || _result.bytesProduced()>0;
// h.append("progress=").append(progress).append('\n');
return progress;
default: default:
Log.warn("unwrap "+_result); Log.warn("unwrap "+_result);
throw new IOException(_result.toString()); throw new IOException(_result.toString());
@ -603,11 +602,9 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private ByteBuffer extractOutputBuffer(Buffer buffer,int n) private ByteBuffer extractOutputBuffer(Buffer buffer,int n)
{ {
NIOBuffer nBuf=null;
if (buffer.buffer() instanceof NIOBuffer) if (buffer.buffer() instanceof NIOBuffer)
{ {
nBuf=(NIOBuffer)buffer.buffer(); NIOBuffer nBuf=(NIOBuffer)buffer.buffer();
return nBuf.getByteBuffer(); return nBuf.getByteBuffer();
} }
else 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); _gather[0]=extractOutputBuffer(header,0);
synchronized(_gather[0]) synchronized(_gather[0])
@ -658,7 +655,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
{ {
_outBuffer.position(0); _outBuffer.position(0);
if (consumed>0 && header!=null) if (consumed>0)
{ {
int len=consumed<header.length()?consumed:header.length(); int len=consumed<header.length()?consumed:header.length();
header.skip(len); header.skip(len);
@ -666,7 +663,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
_gather[0].position(0); _gather[0].position(0);
_gather[0].limit(_gather[0].capacity()); _gather[0].limit(_gather[0].capacity());
} }
if (consumed>0 && buffer!=null) if (consumed>0)
{ {
int len=consumed<buffer.length()?consumed:buffer.length(); int len=consumed<buffer.length()?consumed:buffer.length();
buffer.skip(len); 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); _gather[0]=extractOutputBuffer(header,0);
synchronized(_gather[0]) synchronized(_gather[0])
@ -728,7 +725,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
{ {
_outBuffer.position(0); _outBuffer.position(0);
if (consumed>0 && header!=null) if (consumed>0)
{ {
int len=consumed<header.length()?consumed:header.length(); int len=consumed<header.length()?consumed:header.length();
header.skip(len); header.skip(len);

View File

@ -27,9 +27,9 @@ import org.eclipse.jetty.util.StringMap;
*/ */
public class BufferCache public class BufferCache
{ {
private HashMap _bufferMap=new HashMap(); private final HashMap _bufferMap=new HashMap();
private StringMap _stringMap=new StringMap(StringMap.CASE_INSENSTIVE); private final StringMap _stringMap=new StringMap(StringMap.CASE_INSENSTIVE);
private ArrayList _index= new ArrayList(); private final ArrayList _index= new ArrayList();
/* ------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------- */
/** Add a buffer to the cache at the specified index. /** Add a buffer to the cache at the specified index.
@ -112,7 +112,7 @@ public class BufferCache
public static class CachedBuffer extends ByteArrayBuffer.CaseInsensitive public static class CachedBuffer extends ByteArrayBuffer.CaseInsensitive
{ {
private int _ordinal; private final int _ordinal;
private HashMap _associateMap=null; private HashMap _associateMap=null;
public CachedBuffer(String value, int ordinal) public CachedBuffer(String value, int ordinal)

View File

@ -46,6 +46,7 @@ public class BufferDateCache extends DateCache
public synchronized Buffer formatBuffer(long date) public synchronized Buffer formatBuffer(long date)
{ {
String d = super.format(date); String d = super.format(date);
//noinspection StringEquality
if (d==_last) if (d==_last)
return _buffer; return _buffer;
_last=d; _last=d;

View File

@ -278,10 +278,10 @@ public class BufferUtil
return buf; return buf;
} }
private static int[] decDivisors= private final static int[] decDivisors=
{ 1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1 }; { 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 }; { 0x10000000, 0x1000000, 0x100000, 0x10000, 0x1000, 0x100, 0x10, 1 };

View File

@ -292,12 +292,6 @@ public class ByteArrayBuffer extends AbstractBuffer
byte[] src_array = src.array(); byte[] src_array = src.array();
if (src_array != null) if (src_array != null)
System.arraycopy(src_array, src.getIndex(), _bytes, index, length); 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 else
{ {
int s=src.getIndex(); int s=src.getIndex();
@ -421,7 +415,7 @@ public class ByteArrayBuffer extends AbstractBuffer
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
return equalsIgnoreCase((Buffer)obj); return obj instanceof Buffer && equalsIgnoreCase((Buffer)obj);
} }
} }

View File

@ -35,7 +35,7 @@ public abstract class ThreadLocalBuffers implements Buffers
public Buffer getBuffer() public Buffer getBuffer()
{ {
ThreadBuffers buffers = (ThreadBuffers)_buffers.get(); ThreadBuffers buffers = _buffers.get();
if (buffers._buffer!=null) if (buffers._buffer!=null)
{ {
Buffer b=buffers._buffer; Buffer b=buffers._buffer;
@ -55,7 +55,7 @@ public abstract class ThreadLocalBuffers implements Buffers
public Buffer getHeader() public Buffer getHeader()
{ {
ThreadBuffers buffers = (ThreadBuffers)_buffers.get(); ThreadBuffers buffers = _buffers.get();
if (buffers._header!=null) if (buffers._header!=null)
{ {
Buffer b=buffers._header; Buffer b=buffers._header;
@ -75,7 +75,7 @@ public abstract class ThreadLocalBuffers implements Buffers
public Buffer getBuffer(int size) public Buffer getBuffer(int size)
{ {
ThreadBuffers buffers = (ThreadBuffers)_buffers.get(); ThreadBuffers buffers = _buffers.get();
if (buffers._other!=null && buffers._other.capacity()==size) if (buffers._other!=null && buffers._other.capacity()==size)
{ {
Buffer b=buffers._other; Buffer b=buffers._other;
@ -94,7 +94,7 @@ public abstract class ThreadLocalBuffers implements Buffers
int size=buffer.capacity(); int size=buffer.capacity();
ThreadBuffers buffers = (ThreadBuffers)_buffers.get(); ThreadBuffers buffers = _buffers.get();
if (size==_bufferSize && buffers._buffer==null) if (size==_bufferSize && buffers._buffer==null)
{ {

View File

@ -131,7 +131,7 @@ public class View extends AbstractBuffer
*/ */
public boolean equals(Object obj) 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);
} }
/** /**

View File

@ -27,9 +27,9 @@ import java.io.Writer;
*/ */
public class WriterOutputStream extends OutputStream public class WriterOutputStream extends OutputStream
{ {
protected Writer _writer; protected final Writer _writer;
protected String _encoding; protected final String _encoding;
private byte[] _buf=new byte[1]; private final byte[] _buf=new byte[1];
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public WriterOutputStream(Writer writer, String encoding) public WriterOutputStream(Writer writer, String encoding)
@ -42,6 +42,7 @@ public class WriterOutputStream extends OutputStream
public WriterOutputStream(Writer writer) public WriterOutputStream(Writer writer)
{ {
_writer=writer; _writer=writer;
_encoding=null;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -49,8 +50,6 @@ public class WriterOutputStream extends OutputStream
throws IOException throws IOException
{ {
_writer.close(); _writer.close();
_writer=null;
_encoding=null;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -102,9 +102,7 @@ public class StreamEndPoint implements EndPoint
throw new IOException("FULL"); throw new IOException("FULL");
} }
int len = buffer.readFrom(_in,space); return buffer.readFrom(_in,space);
return len;
} }
/* (non-Javadoc) /* (non-Javadoc)

View File

@ -39,7 +39,6 @@ public class StringEndPoint extends StreamEndPoint
} }
public StringEndPoint(String encoding) public StringEndPoint(String encoding)
throws IOException
{ {
this(); this();
if (encoding!=null) if (encoding!=null)

View File

@ -36,8 +36,8 @@ import org.eclipse.jetty.util.log.Log;
*/ */
public class ChannelEndPoint implements EndPoint public class ChannelEndPoint implements EndPoint
{ {
protected ByteChannel _channel; protected final ByteChannel _channel;
protected ByteBuffer[] _gather2=new ByteBuffer[2]; protected final ByteBuffer[] _gather2=new ByteBuffer[2];
protected Socket _socket; protected Socket _socket;
protected InetSocketAddress _local; protected InetSocketAddress _local;
protected InetSocketAddress _remote; protected InetSocketAddress _remote;
@ -55,9 +55,7 @@ public class ChannelEndPoint implements EndPoint
public boolean isBlocking() public boolean isBlocking()
{ {
if (_channel instanceof SelectableChannel) return !(_channel instanceof SelectableChannel) || ((SelectableChannel)_channel).isBlocking();
return ((SelectableChannel)_channel).isBlocking();
return true;
} }
public boolean blockReadable(long millisecs) throws IOException public boolean blockReadable(long millisecs) throws IOException
@ -119,9 +117,10 @@ public class ChannelEndPoint implements EndPoint
int len=0; int len=0;
if (buf instanceof NIOBuffer) if (buf instanceof NIOBuffer)
{ {
NIOBuffer nbuf = (NIOBuffer)buf; final NIOBuffer nbuf = (NIOBuffer)buf;
ByteBuffer bbuf=nbuf.getByteBuffer(); final ByteBuffer bbuf=nbuf.getByteBuffer();
synchronized(nbuf) //noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized(bbuf)
{ {
try try
{ {
@ -154,10 +153,10 @@ public class ChannelEndPoint implements EndPoint
int len=0; int len=0;
if (buf instanceof NIOBuffer) if (buf instanceof NIOBuffer)
{ {
NIOBuffer nbuf = (NIOBuffer)buf; final NIOBuffer nbuf = (NIOBuffer)buf;
ByteBuffer bbuf=nbuf.getByteBuffer(); final ByteBuffer bbuf=nbuf.getByteBuffer();
// TODO synchronize //noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized(bbuf) synchronized(bbuf)
{ {
try try
@ -210,16 +209,18 @@ public class ChannelEndPoint implements EndPoint
header!=null && header.length()!=0 && buf0 instanceof NIOBuffer && header!=null && header.length()!=0 && buf0 instanceof NIOBuffer &&
buffer!=null && buffer.length()!=0 && buf1 instanceof NIOBuffer) buffer!=null && buffer.length()!=0 && buf1 instanceof NIOBuffer)
{ {
NIOBuffer nbuf0 = (NIOBuffer)buf0; final NIOBuffer nbuf0 = (NIOBuffer)buf0;
ByteBuffer bbuf0=nbuf0.getByteBuffer(); final ByteBuffer bbuf0=nbuf0.getByteBuffer();
NIOBuffer nbuf1 = (NIOBuffer)buf1; final NIOBuffer nbuf1 = (NIOBuffer)buf1;
ByteBuffer bbuf1=nbuf1.getByteBuffer(); final ByteBuffer bbuf1=nbuf1.getByteBuffer();
synchronized(this) synchronized(this)
{ {
// We must sync because buffers may be shared (eg nbuf1 is likely to be cached content). // We must sync because buffers may be shared (eg nbuf1 is likely to be cached content).
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized(bbuf0) synchronized(bbuf0)
{ {
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized(bbuf1) synchronized(bbuf1)
{ {
try try
@ -395,8 +396,6 @@ public class ChannelEndPoint implements EndPoint
if (_remote==null) if (_remote==null)
_remote=(InetSocketAddress)_socket.getRemoteSocketAddress(); _remote=(InetSocketAddress)_socket.getRemoteSocketAddress();
if (_remote==null)
return -1;
return _remote==null?-1:_remote.getPort(); return _remote==null?-1:_remote.getPort();
} }

View File

@ -34,7 +34,7 @@ import org.eclipse.jetty.io.Buffer;
*/ */
public class DirectNIOBuffer extends AbstractBuffer implements NIOBuffer public class DirectNIOBuffer extends AbstractBuffer implements NIOBuffer
{ {
protected ByteBuffer _buf; protected final ByteBuffer _buf;
private ReadableByteChannel _in; private ReadableByteChannel _in;
private InputStream _inStream; private InputStream _inStream;
private WritableByteChannel _out; private WritableByteChannel _out;
@ -137,8 +137,7 @@ public class DirectNIOBuffer extends AbstractBuffer implements NIOBuffer
byte[] array=src.array(); byte[] array=src.array();
if (array!=null) if (array!=null)
{ {
int length = poke(index,array,src.getIndex(),src.length()); return poke(index,array,src.getIndex(),src.length());
return length;
} }
else else
{ {
@ -279,7 +278,7 @@ public class DirectNIOBuffer extends AbstractBuffer implements NIOBuffer
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public void writeTo(OutputStream out) throws IOException 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); _out=Channels.newChannel(out);
_outStream=out; _outStream=out;

View File

@ -24,9 +24,9 @@ import org.eclipse.jetty.io.Buffer;
public class RandomAccessFileBuffer extends AbstractBuffer implements Buffer public class RandomAccessFileBuffer extends AbstractBuffer implements Buffer
{ {
RandomAccessFile _file; final RandomAccessFile _file;
FileChannel _channel; final FileChannel _channel;
int _capacity=Integer.MAX_VALUE; final int _capacity;
public RandomAccessFileBuffer(File file) public RandomAccessFileBuffer(File file)
throws FileNotFoundException throws FileNotFoundException
@ -35,6 +35,7 @@ public class RandomAccessFileBuffer extends AbstractBuffer implements Buffer
assert file.length()<=Integer.MAX_VALUE; assert file.length()<=Integer.MAX_VALUE;
_file = new RandomAccessFile(file,"rw"); _file = new RandomAccessFile(file,"rw");
_channel=_file.getChannel(); _channel=_file.getChannel();
_capacity=Integer.MAX_VALUE;
setGetIndex(0); setGetIndex(0);
setPutIndex((int)file.length()); setPutIndex((int)file.length());
} }

View File

@ -18,6 +18,7 @@ import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel; import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey; import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.io.AsyncEndPoint; import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.Buffer;
@ -36,24 +37,19 @@ import org.eclipse.jetty.util.thread.Timeout;
*/ */
public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, AsyncEndPoint public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable, AsyncEndPoint
{ {
protected SelectorManager _manager; private final SelectorManager.SelectSet _selectSet;
protected SelectorManager.SelectSet _selectSet; private final Connection _connection;
protected boolean _dispatched = false; private final SelectorManager _manager;
protected boolean _redispatched = false; private boolean _dispatched = false;
protected boolean _writable = true; private boolean _redispatched = false;
protected SelectionKey _key; private volatile boolean _writable = true;
protected int _interestOps;
protected boolean _readBlocked;
protected boolean _writeBlocked;
protected Connection _connection;
private boolean _open;
private Timeout.Task _idleTask = new IdleTask();
/* ------------------------------------------------------------ */ private SelectionKey _key;
public Connection getConnection() private int _interestOps;
{ private boolean _readBlocked;
return _connection; private boolean _writeBlocked;
} private boolean _open;
private final Timeout.Task _idleTask = new IdleTask();
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public SelectChannelEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) public SelectChannelEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key)
@ -72,11 +68,23 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
scheduleIdle(); scheduleIdle();
} }
/* ------------------------------------------------------------ */
public Connection getConnection()
{
return _connection;
}
/* ------------------------------------------------------------ */
public SelectorManager getSelectManager()
{
return _manager;
}
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/** Called by selectSet to schedule handling /** Called by selectSet to schedule handling
* *
*/ */
public void schedule() throws IOException public void schedule()
{ {
// If threads are blocked on this // If threads are blocked on this
synchronized (this) synchronized (this)
@ -140,7 +148,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
_redispatched=true; _redispatched=true;
else else
{ {
_dispatched = _manager.dispatch((Runnable)this); _dispatched = _manager.dispatch(this);
if(!_dispatched) if(!_dispatched)
{ {
Log.warn("Dispatched Failed!"); Log.warn("Dispatched Failed!");
@ -157,7 +165,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
* @return If false is returned, the endpoint has been redispatched and * @return If false is returned, the endpoint has been redispatched and
* thread must keep handling the endpoint. * thread must keep handling the endpoint.
*/ */
protected boolean undispatch() boolean undispatch()
{ {
synchronized (this) synchronized (this)
{ {
@ -419,41 +427,52 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
public void run() public void run()
{ {
boolean dispatched=true; boolean dispatched=true;
do try
{ {
try while(dispatched)
{
_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);}
}
finally
{ {
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(); dispatched=!undispatch();
} }
} }
while(dispatched); finally
{
if (dispatched)
{
dispatched=!undispatch();
while (dispatched)
{
Log.warn("SCEP.run() finally DISPATCHED");
dispatched=!undispatch();
}
}
}
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -479,8 +498,11 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public String toString() public String toString()
{ {
return "SCEP@" + hashCode() + "\t[d=" + _dispatched + ",io=" + _interestOps+ synchronized(this)
",w=" + _writable + ",b=" + _readBlocked + "|" + _writeBlocked + "]"; {
return "SCEP@" + hashCode() + "\t[d=" + _dispatched + ",io=" + _interestOps+
",w=" + _writable + ",b=" + _readBlocked + "|" + _writeBlocked + "]";
}
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -498,7 +520,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public class IdleTask extends Timeout.Task private class IdleTask extends Timeout.Task
{ {
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/* /*

View File

@ -42,7 +42,7 @@ import org.eclipse.jetty.util.thread.Timeout;
*/ */
public abstract class SelectorManager extends AbstractLifeCycle 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_THRESHHOLD2=__JVMBUG_THRESHHOLD*2;
private static final int __JVMBUG_THRESHHOLD1=(__JVMBUG_THRESHHOLD2+__JVMBUG_THRESHHOLD)/2; private static final int __JVMBUG_THRESHHOLD1=(__JVMBUG_THRESHHOLD2+__JVMBUG_THRESHHOLD)/2;
private long _maxIdleTime; 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) public void setSelectSets(int selectSets)
{ {
@ -100,7 +100,7 @@ public abstract class SelectorManager extends AbstractLifeCycle
* @param att Attached Object * @param att Attached Object
* @throws IOException * @throws IOException
*/ */
public void register(SocketChannel channel, Object att) throws IOException public void register(SocketChannel channel, Object att)
{ {
int s=_set++; int s=_set++;
s=s%_selectSets; s=s%_selectSets;
@ -119,7 +119,7 @@ public abstract class SelectorManager extends AbstractLifeCycle
* @return * @return
* @throws IOException * @throws IOException
*/ */
public void register(ServerSocketChannel acceptChannel) throws IOException public void register(ServerSocketChannel acceptChannel)
{ {
int s=_set++; int s=_set++;
s=s%_selectSets; s=s%_selectSets;
@ -211,12 +211,13 @@ public abstract class SelectorManager extends AbstractLifeCycle
SelectSet[] sets= _selectSet; SelectSet[] sets= _selectSet;
_selectSet=null; _selectSet=null;
if (sets!=null) if (sets!=null)
for (int i=0;i<sets.length;i++) {
for (SelectSet set : sets)
{ {
SelectSet set = sets[i];
if (set!=null) if (set!=null)
set.stop(); set.stop();
} }
}
super.doStop(); super.doStop();
} }
@ -286,14 +287,15 @@ public abstract class SelectorManager extends AbstractLifeCycle
/* ------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------- */
public class SelectSet public class SelectSet
{ {
private transient int _change; private final int _setID;
private transient List<Object>[] _changes; private final Timeout _idleTimeout;
private transient Timeout _idleTimeout; private final Timeout _timeout;
private transient int _nextSet; private final List<Object>[] _changes;
private transient Timeout _timeout;
private transient Selector _selector; private int _change;
private transient int _setID; private int _nextSet;
private transient int _jvmBug; private Selector _selector;
private int _jvmBug;
private volatile Thread _selecting; private volatile Thread _selecting;
private long _lastJVMBug; private long _lastJVMBug;
@ -306,10 +308,10 @@ public abstract class SelectorManager extends AbstractLifeCycle
_idleTimeout.setDuration(getMaxIdleTime()); _idleTimeout.setDuration(getMaxIdleTime());
_timeout = new Timeout(this); _timeout = new Timeout(this);
_timeout.setDuration(0L); _timeout.setDuration(0L);
_changes = new List[] {new ArrayList(),new ArrayList()};
// create a selector; // create a selector;
_selector = Selector.open(); _selector = Selector.open();
_changes = new List[] {new ArrayList(),new ArrayList()};
_change=0; _change=0;
} }
@ -435,8 +437,8 @@ public abstract class SelectorManager extends AbstractLifeCycle
} }
changes.clear(); changes.clear();
long idle_next = 0; long idle_next;
long retry_next = 0; long retry_next;
long now=System.currentTimeMillis(); long now=System.currentTimeMillis();
synchronized (this) synchronized (this)
{ {
@ -486,10 +488,8 @@ public abstract class SelectorManager extends AbstractLifeCycle
} }
// BLOODY SUN BUG !!! Try refreshing the entire selector. // BLOODY SUN BUG !!! Try refreshing the entire selector.
final Selector new_selector = Selector.open(); final Selector new_selector = Selector.open();
Iterator iterator = _selector.keys().iterator(); for (SelectionKey k: selector.keys())
while (iterator.hasNext())
{ {
SelectionKey k = (SelectionKey)iterator.next();
if (!k.isValid() || k.interestOps()==0) if (!k.isValid() || k.interestOps()==0)
continue; continue;
@ -517,10 +517,8 @@ public abstract class SelectorManager extends AbstractLifeCycle
_jvmBug0=true; _jvmBug0=true;
Log.info("seeing JVM BUG(s) - cancelling interestOps==0"); Log.info("seeing JVM BUG(s) - cancelling interestOps==0");
} }
Iterator iter = selector.keys().iterator(); for (SelectionKey k: selector.keys())
while(iter.hasNext())
{ {
SelectionKey k = (SelectionKey) iter.next();
if (k.isValid()&&k.interestOps()==0) if (k.isValid()&&k.interestOps()==0)
{ {
k.cancel(); k.cancel();
@ -717,12 +715,8 @@ public abstract class SelectorManager extends AbstractLifeCycle
selecting=_selecting!=null; selecting=_selecting!=null;
} }
ArrayList<SelectionKey> keys=new ArrayList<SelectionKey>(_selector.keys()); for (SelectionKey key:_selector.keys())
Iterator<SelectionKey> iter =keys.iterator();
while (iter.hasNext())
{ {
SelectionKey key = (SelectionKey)iter.next();
if (key==null) if (key==null)
continue; continue;
Object att=key.attachment(); Object att=key.attachment();

View File

@ -34,18 +34,10 @@ public class ThreadLocalBuffersTest
int runTestLength = _stress?5000:1000; int runTestLength = _stress?5000:1000;
int threadWaitTime = 5;
boolean runTest = false; boolean runTest = false;
AtomicLong buffersRetrieved; AtomicLong buffersRetrieved;
private static int __LOCAL = 1;
private static int __LIST = 2;
private static int __QUEUE = 3;
protected void setUp() protected void setUp()
throws Exception throws Exception
{ {
@ -115,7 +107,7 @@ public class ThreadLocalBuffersTest
} }
class InnerBuffers extends ThreadLocalBuffers static class InnerBuffers extends ThreadLocalBuffers
{ {
@Override @Override
protected Buffer newBuffer(int size) protected Buffer newBuffer(int size)

View File

@ -74,7 +74,7 @@ public abstract class AbstractConnector extends HttpBuffers implements Connector
private transient Thread[] _acceptorThread; private transient Thread[] _acceptorThread;
Object _statsLock = new Object(); final Object _statsLock = new Object();
transient long _statsStartedAt=-1; transient long _statsStartedAt=-1;
// TODO use concurrents for these! // TODO use concurrents for these!

View File

@ -102,8 +102,7 @@ public class AsyncContinuation implements AsyncContext, Continuation
{ {
synchronized(this) synchronized(this)
{ {
if ((listener instanceof ContinuationListener)) _listeners=LazyList.add(_listeners,listener);
_listeners=LazyList.add(_listeners,listener);
// _history.append('L'); // _history.append('L');
} }
} }

View File

@ -68,16 +68,16 @@ public class Dispatcher implements RequestDispatcher
public final static String __JSP_FILE="org.apache.catalina.jsp_file"; public final static String __JSP_FILE="org.apache.catalina.jsp_file";
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private ContextHandler _contextHandler; private final ContextHandler _contextHandler;
private String _uri; private final String _uri;
private String _path; private final String _path;
private String _dQuery; private final String _dQuery;
private String _named; private final String _named;
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/** /**
* @param contextHandler * @param contextHandler
* @param uriInContext * @param uri
* @param pathInContext * @param pathInContext
* @param query * @param query
*/ */
@ -87,12 +87,13 @@ public class Dispatcher implements RequestDispatcher
_uri=uri; _uri=uri;
_path=pathInContext; _path=pathInContext;
_dQuery=query; _dQuery=query;
_named=null;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/** Constructor. /** Constructor.
* @param servletHandler * @param contextHandler
* @param name * @param name
*/ */
public Dispatcher(ContextHandler contextHandler,String name) public Dispatcher(ContextHandler contextHandler,String name)
@ -100,6 +101,9 @@ public class Dispatcher implements RequestDispatcher
{ {
_contextHandler=contextHandler; _contextHandler=contextHandler;
_named=name; _named=name;
_uri=null;
_path=null;
_dQuery=null;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -176,7 +180,7 @@ public class Dispatcher implements RequestDispatcher
baseRequest.setAttributes(attr); baseRequest.setAttributes(attr);
_contextHandler.handle(_named==null?_path:_named,baseRequest, (HttpServletRequest)request, (HttpServletResponse)response); _contextHandler.handle(_path,baseRequest, (HttpServletRequest)request, (HttpServletResponse)response);
} }
} }
finally finally
@ -196,7 +200,7 @@ public class Dispatcher implements RequestDispatcher
protected void forward(ServletRequest request, ServletResponse response, DispatcherType dispatch) throws ServletException, IOException protected void forward(ServletRequest request, ServletResponse response, DispatcherType dispatch) throws ServletException, IOException
{ {
Request baseRequest=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest(); Request baseRequest=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest();
Response base_response=(Response)baseRequest.getResponse(); Response base_response=baseRequest.getResponse();
base_response.fwdReset(); base_response.fwdReset();
request.removeAttribute(__JSP_FILE); // TODO remove when glassfish 1044 is fixed request.removeAttribute(__JSP_FILE); // TODO remove when glassfish 1044 is fixed
@ -277,7 +281,7 @@ public class Dispatcher implements RequestDispatcher
Object values=entry.getValue(); Object values=entry.getValue();
for (int i=0;i<LazyList.size(values);i++) 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. //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 //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. //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._pathInfo=(String)old_attr.getAttribute(FORWARD_PATH_INFO);
attr._query=(String)old_attr.getAttribute(FORWARD_QUERY_STRING); attr._query=(String)old_attr.getAttribute(FORWARD_QUERY_STRING);
@ -357,7 +361,7 @@ public class Dispatcher implements RequestDispatcher
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private class ForwardAttributes implements Attributes private class ForwardAttributes implements Attributes
{ {
Attributes _attr; final Attributes _attr;
String _requestURI; String _requestURI;
String _contextPath; String _contextPath;
@ -473,7 +477,7 @@ public class Dispatcher implements RequestDispatcher
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
private class IncludeAttributes implements Attributes private class IncludeAttributes implements Attributes
{ {
Attributes _attr; final Attributes _attr;
String _requestURI; String _requestURI;
String _contextPath; String _contextPath;
@ -575,4 +579,4 @@ public class Dispatcher implements RequestDispatcher
setAttribute(name,null); setAttribute(name,null);
} }
} }
}; }

View File

@ -71,8 +71,8 @@ import org.eclipse.jetty.util.thread.Timeout;
*/ */
public class HttpConnection implements Connection public class HttpConnection implements Connection
{ {
private static int UNKNOWN = -2; private static final int UNKNOWN = -2;
private static ThreadLocal<HttpConnection> __currentConnection = new ThreadLocal<HttpConnection>(); private static final ThreadLocal<HttpConnection> __currentConnection = new ThreadLocal<HttpConnection>();
private final long _timeStamp=System.currentTimeMillis(); private final long _timeStamp=System.currentTimeMillis();
private int _requests; private int _requests;
@ -111,7 +111,7 @@ public class HttpConnection implements Connection
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public static HttpConnection getCurrentConnection() 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) 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; _connector = connector;
_endp = endpoint; _endp = endpoint;
HttpBuffers ab = (HttpBuffers)_connector; HttpBuffers ab = (HttpBuffers)_connector;
@ -144,7 +144,7 @@ public class HttpConnection implements Connection
protected HttpConnection(Connector connector, EndPoint endpoint, Server server, protected HttpConnection(Connector connector, EndPoint endpoint, Server server,
Parser parser, Generator generator, Request request) 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; _connector = connector;
_endp = endpoint; _endp = endpoint;
_parser = parser; _parser = parser;
@ -384,8 +384,9 @@ public class HttpConnection implements Connection
try try
{ {
_handling=true;
assert getCurrentConnection()==null; assert getCurrentConnection()==null;
assert _handling==false;
_handling=true;
setCurrentConnection(this); setCurrentConnection(this);
while (more_in_buffer) while (more_in_buffer)

View File

@ -35,8 +35,8 @@ public class HttpWriter extends Writer
private static final int WRITE_ISO1 = 1; private static final int WRITE_ISO1 = 1;
private static final int WRITE_UTF8 = 2; private static final int WRITE_UTF8 = 2;
HttpOutput _out; final HttpOutput _out;
AbstractGenerator _generator; final AbstractGenerator _generator;
int _writeMode; int _writeMode;
int _surrogate; int _surrogate;

View File

@ -173,7 +173,7 @@ public class Request implements HttpServletRequest
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public void addContinuationListener(ContinuationListener listener) public void addContinuationListener(ContinuationListener listener)
{ {
_async.addContinuationListener((ContinuationListener)listener); _async.addContinuationListener(listener);
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -559,10 +559,9 @@ public class Request implements HttpServletRequest
int size=acceptLanguage.size(); int size=acceptLanguage.size();
// convert to locals if (size>0)
for (int i=0; i<size; i++)
{ {
String language = (String)acceptLanguage.get(i); String language = (String)acceptLanguage.get(0);
language=HttpFields.valueParameters(language,null); language=HttpFields.valueParameters(language,null);
String country = ""; String country = "";
int dash = language.indexOf('-'); int dash = language.indexOf('-');
@ -901,7 +900,7 @@ public class Request implements HttpServletRequest
*/ */
public StringBuffer getRequestURL() public StringBuffer getRequestURL()
{ {
StringBuffer url = new StringBuffer(48); final StringBuffer url = new StringBuffer(48);
synchronized (url) synchronized (url)
{ {
String scheme = getScheme(); String scheme = getScheme();
@ -1263,7 +1262,7 @@ public class Request implements HttpServletRequest
return false; return false;
HttpSession session=getSession(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) if (_savedNewSessions==null)
return 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) if (listener instanceof ServletRequestAttributeListener)
{ {
final ServletRequestAttributeListener l = (ServletRequestAttributeListener)listener; final ServletRequestAttributeListener l = (ServletRequestAttributeListener)listener;
((ServletRequestAttributeListener)l).attributeRemoved(event); l.attributeRemoved(event);
} }
} }
} }
@ -1426,12 +1425,12 @@ public class Request implements HttpServletRequest
{ {
try try
{ {
ByteBuffer byteBuffer=(ByteBuffer)value; final ByteBuffer byteBuffer=(ByteBuffer)value;
synchronized (byteBuffer) synchronized (byteBuffer)
{ {
NIOBuffer buffer = byteBuffer.isDirect() NIOBuffer buffer = byteBuffer.isDirect()
?(NIOBuffer)new DirectNIOBuffer(byteBuffer,true) ?new DirectNIOBuffer(byteBuffer,true)
:(NIOBuffer)new IndirectNIOBuffer(byteBuffer,true); :new IndirectNIOBuffer(byteBuffer,true);
((HttpConnection.Output)getServletResponse().getOutputStream()).sendResponse(buffer); ((HttpConnection.Output)getServletResponse().getOutputStream()).sendResponse(buffer);
} }
} }
@ -1501,6 +1500,7 @@ public class Request implements HttpServletRequest
// check encoding is supported // check encoding is supported
if (!StringUtil.isUTF8(encoding)) if (!StringUtil.isUTF8(encoding))
//noinspection ResultOfMethodCallIgnored
"".getBytes(encoding); "".getBytes(encoding);
} }

View File

@ -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 _maxCachedFileSize =1024*1024;
private int _maxCachedFiles=2048; private int _maxCachedFiles=2048;
private int _maxCacheSize =16*1024*1024; private int _maxCacheSize =16*1024*1024;
private MimeTypes _mimeTypes;
protected transient Map _cache; protected int _cachedSize;
protected transient int _cachedSize; protected int _cachedFiles;
protected transient int _cachedFiles; protected Content _mostRecentlyUsed;
protected transient Content _mostRecentlyUsed; protected Content _leastRecentlyUsed;
protected transient Content _leastRecentlyUsed;
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/** Constructor. /** Constructor.
*/ */
public ResourceCache(MimeTypes mimeTypes) public ResourceCache(MimeTypes mimeTypes)
{ {
_cache=new HashMap();
_mimeTypes=mimeTypes; _mimeTypes=mimeTypes;
} }
@ -268,7 +269,7 @@ public class ResourceCache extends AbstractLifeCycle implements Serializable
public synchronized void doStart() public synchronized void doStart()
throws Exception throws Exception
{ {
_cache=new HashMap(); _cache.clear();
_cachedSize=0; _cachedSize=0;
_cachedFiles=0; _cachedFiles=0;
} }
@ -307,10 +308,10 @@ public class ResourceCache extends AbstractLifeCycle implements Serializable
*/ */
public class Content implements HttpContent public class Content implements HttpContent
{ {
final Resource _resource;
final long _lastModified;
boolean _locked; boolean _locked;
String _key; String _key;
Resource _resource;
long _lastModified;
Content _prev; Content _prev;
Content _next; Content _next;
@ -455,7 +456,7 @@ public class ResourceCache extends AbstractLifeCycle implements Serializable
_cache.remove(_key); _cache.remove(_key);
_key=null; _key=null;
if (_buffer!=null) if (_buffer!=null)
_cachedSize=_cachedSize-(int)_buffer.length(); _cachedSize=_cachedSize-_buffer.length();
_cachedFiles--; _cachedFiles--;
if (_mostRecentlyUsed==this) if (_mostRecentlyUsed==this)
@ -470,9 +471,7 @@ public class ResourceCache extends AbstractLifeCycle implements Serializable
_prev=null; _prev=null;
_next=null; _next=null;
if (_resource!=null) _resource.release();
_resource.release();
_resource=null;
} }
} }

View File

@ -66,24 +66,18 @@ public class Response implements HttpServletResponse
* can be set during include using only {@link #setHeader(String, String)} or * can be set during include using only {@link #setHeader(String, String)} or
* {@link #addHeader(String, String)}. * {@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 final PrintWriter __nullPrintWriter;
private static ServletOutputStream __nullServletOut; private static final ServletOutputStream __nullServletOut;
static static
{ {
try{ __nullPrintWriter = new PrintWriter(IO.getNullWriter());
__nullPrintWriter = new PrintWriter(IO.getNullWriter()); __nullServletOut = new NullOutput();
__nullServletOut = new NullOutput();
}
catch (Exception e)
{
Log.warn(e);
}
} }
private HttpConnection _connection; private final HttpConnection _connection;
private int _status=SC_OK; private int _status=SC_OK;
private String _reason; private String _reason;
private Locale _locale; private Locale _locale;
@ -172,8 +166,10 @@ public class Response implements HttpServletResponse
if (sessionURLPrefix==null) if (sessionURLPrefix==null)
return url; return url;
if (url==null)
return null;
// should not encode if cookies in evidence // should not encode if cookies in evidence
if (url==null || request==null || request.isRequestedSessionIdFromCookie()) if (request.isRequestedSessionIdFromCookie())
{ {
int prefix=url.indexOf(sessionURLPrefix); int prefix=url.indexOf(sessionURLPrefix);
if (prefix!=-1) if (prefix!=-1)

View File

@ -56,19 +56,19 @@ import org.eclipse.jetty.util.thread.ThreadPool;
*/ */
public class Server extends HandlerWrapper implements Attributes public class Server extends HandlerWrapper implements Attributes
{ {
private static ShutdownHookThread hookThread = new ShutdownHookThread(); private static final ShutdownHookThread hookThread = new ShutdownHookThread();
private static String _version = (Server.class.getPackage()!=null && Server.class.getPackage().getImplementationVersion()!=null) private static final String _version = (Server.class.getPackage()!=null && Server.class.getPackage().getImplementationVersion()!=null)
?Server.class.getPackage().getImplementationVersion() ?Server.class.getPackage().getImplementationVersion()
:"7.0.y.z-SNAPSHOT"; :"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 ThreadPool _threadPool;
private Connector[] _connectors; private Connector[] _connectors;
private Container _container=new Container();
private SessionIdManager _sessionIdManager; private SessionIdManager _sessionIdManager;
private boolean _sendServerVersion = true; //send Server: header private boolean _sendServerVersion = true; //send Server: header
private boolean _sendDateHeader = false; //send Date: header private boolean _sendDateHeader = false; //send Date: header
private AttributesMap _attributes = new AttributesMap();
private List<Object> _dependentBeans=new ArrayList<Object>();
private int _graceful=0; private int _graceful=0;
private boolean _stopAtShutdown; private boolean _stopAtShutdown;
@ -525,7 +525,7 @@ public class Server extends HandlerWrapper implements Attributes
private static class ShutdownHookThread extends Thread private static class ShutdownHookThread extends Thread
{ {
private boolean _hooked = false; private boolean _hooked = false;
private Set<Server> _servers = new CopyOnWriteArraySet<Server>(); private final Set<Server> _servers = new CopyOnWriteArraySet<Server>();
/** /**
* Hooks this thread for shutdown. * Hooks this thread for shutdown.
@ -538,10 +538,8 @@ public class Server extends HandlerWrapper implements Attributes
{ {
try try
{ {
Method shutdownHook = java.lang.Runtime.class.getMethod("addShutdownHook", new Class[] Method shutdownHook = java.lang.Runtime.class.getMethod("addShutdownHook", Thread.class);
{ java.lang.Thread.class}); shutdownHook.invoke(Runtime.getRuntime(), this);
shutdownHook.invoke(Runtime.getRuntime(), new Object[]
{ this});
_hooked = true; _hooked = true;
} }
catch (Exception e) catch (Exception e)

View File

@ -87,7 +87,7 @@ public interface UserIdentity
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
public interface UnauthenticatedUserIdentity extends UserIdentity public interface UnauthenticatedUserIdentity extends UserIdentity
{ {
}; }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -48,7 +48,7 @@ import org.eclipse.jetty.util.log.Log;
public class SocketConnector extends AbstractConnector public class SocketConnector extends AbstractConnector
{ {
protected ServerSocket _serverSocket; protected ServerSocket _serverSocket;
protected Set _connections; protected final Set _connections;
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/** Constructor. /** Constructor.
@ -56,6 +56,7 @@ public class SocketConnector extends AbstractConnector
*/ */
public SocketConnector() public SocketConnector()
{ {
_connections=new HashSet();
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
@ -137,7 +138,7 @@ public class SocketConnector extends AbstractConnector
/* ------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------- */
protected void doStart() throws Exception protected void doStart() throws Exception
{ {
_connections=new HashSet(); _connections.clear();
super.doStart(); super.doStart();
} }
@ -178,7 +179,7 @@ public class SocketConnector extends AbstractConnector
_socket=socket; _socket=socket;
} }
public void dispatch() throws InterruptedException, IOException public void dispatch() throws IOException
{ {
if (getThreadPool()==null || !getThreadPool().dispatch(this)) if (getThreadPool()==null || !getThreadPool().dispatch(this))
{ {

View File

@ -67,7 +67,7 @@ public abstract class AbstractHandlerContainer extends AbstractHandler implement
if (handler==null) if (handler==null)
return list; return list;
if (handler!=null && (byClass==null || byClass.isAssignableFrom(handler.getClass()))) if (byClass==null || byClass.isAssignableFrom(handler.getClass()))
list=LazyList.add(list, handler); list=LazyList.add(list, handler);
if (handler instanceof AbstractHandlerContainer) if (handler instanceof AbstractHandlerContainer)

View File

@ -83,7 +83,7 @@ import org.eclipse.jetty.util.resource.Resource;
*/ */
public class ContextHandler extends ScopedHandler implements Attributes, Server.Graceful, CompleteHandler 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"; 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() public static Context getCurrentContext()
{ {
Context context = __context.get(); return __context.get();
return context;
} }
protected Context _scontext; protected Context _scontext;
@ -294,7 +293,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server.
if (_connectors==null || _connectors.size()==0) if (_connectors==null || _connectors.size()==0)
return null; 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) 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) if (managedAttributes!=null)
{ {
_managedAttributes=new HashSet<String>(); _managedAttributes=new HashSet<String>();
String[] attributes = managedAttributes.toString().split(","); String[] attributes = managedAttributes.split(",");
for (String s : attributes) _managedAttributes.addAll(Arrays.asList(attributes));
_managedAttributes.add(s);
Enumeration e = _scontext.getAttributeNames(); Enumeration e = _scontext.getAttributeNames();
while(e.hasMoreElements()) while(e.hasMoreElements())
@ -857,6 +855,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server.
} }
// start manual inline of nextScope(target,baseRequest,request,response); // start manual inline of nextScope(target,baseRequest,request,response);
//noinspection ConstantIfStatement
if (false) if (false)
nextScope(target,baseRequest,request,response); nextScope(target,baseRequest,request,response);
else if (_nextScope!=null) else if (_nextScope!=null)
@ -920,6 +919,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server.
throw new HttpException(HttpServletResponse.SC_NOT_FOUND); throw new HttpException(HttpServletResponse.SC_NOT_FOUND);
// start manual inline of nextHandle(target,baseRequest,request,response); // start manual inline of nextHandle(target,baseRequest,request,response);
//noinspection ConstantIfStatement
if (false) if (false)
nextHandle(target,baseRequest,request,response); nextHandle(target,baseRequest,request,response);
else if (_nextScope!=null && _nextScope==_handler) else if (_nextScope!=null && _nextScope==_handler)
@ -1319,9 +1319,9 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server.
{ {
if (_localeEncodingMap==null) if (_localeEncodingMap==null)
return null; return null;
String encoding = (String)_localeEncodingMap.get(locale.toString()); String encoding = _localeEncodingMap.get(locale.toString());
if (encoding==null) if (encoding==null)
encoding = (String)_localeEncodingMap.get(locale.getLanguage()); encoding = _localeEncodingMap.get(locale.getLanguage());
return encoding; return encoding;
} }
@ -1759,7 +1759,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server.
} }
setManagedAttribute(name,value); setManagedAttribute(name,value);
Object old_value=_contextAttributes==null?null:_contextAttributes.getAttribute(name); Object old_value=_contextAttributes.getAttribute(name);
if (value==null) if (value==null)
_contextAttributes.removeAttribute(name); _contextAttributes.removeAttribute(name);

View File

@ -271,7 +271,7 @@ public class ContextHandlerCollection extends HandlerCollection
{ {
try try
{ {
ContextHandler context = (ContextHandler)_contextClass.newInstance(); ContextHandler context = _contextClass.newInstance();
context.setContextPath(contextPath); context.setContextPath(contextPath);
context.setResourceBase(resourceBase); context.setResourceBase(resourceBase);
addHandler(context); addHandler(context);

View File

@ -48,7 +48,7 @@ import org.eclipse.jetty.util.log.Log;
*/ */
public class DefaultHandler extends AbstractHandler public class DefaultHandler extends AbstractHandler
{ {
long _faviconModified=(System.currentTimeMillis()/1000)*1000; final long _faviconModified=(System.currentTimeMillis()/1000)*1000;
byte[] _favicon; byte[] _favicon;
boolean _serveIcon=true; boolean _serveIcon=true;
@ -165,8 +165,6 @@ public class DefaultHandler extends AbstractHandler
OutputStream out=response.getOutputStream(); OutputStream out=response.getOutputStream();
writer.writeTo(out); writer.writeTo(out);
out.close(); out.close();
return;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */

View File

@ -72,7 +72,7 @@ public class HandlerCollection extends AbstractHandlerContainer
if (!_mutableWhenRunning && isStarted()) if (!_mutableWhenRunning && isStarted())
throw new IllegalStateException(STARTED); throw new IllegalStateException(STARTED);
Handler [] old_handlers = _handlers==null?null:(Handler[])_handlers.clone(); Handler [] old_handlers = _handlers==null?null:_handlers.clone();
if (getServer()!=null) if (getServer()!=null)
getServer().getContainer().update(this, old_handlers, handlers, "handler"); getServer().getContainer().update(this, old_handlers, handlers, "handler");

View File

@ -89,10 +89,6 @@ public class HotSwapHandler extends AbstractHandlerContainer
old_handler.stop(); old_handler.stop();
} }
catch(Error e)
{
throw e;
}
catch(RuntimeException e) catch(RuntimeException e)
{ {
throw e; throw e;

View File

@ -33,11 +33,11 @@ import org.eclipse.jetty.util.URIUtil;
*/ */
public class MovedContextHandler extends ContextHandler public class MovedContextHandler extends ContextHandler
{ {
final Redirector _redirector;
String _newContextURL; String _newContextURL;
boolean _discardPathInfo; boolean _discardPathInfo;
boolean _discardQuery; boolean _discardQuery;
boolean _permanent; boolean _permanent;
Redirector _redirector;
String _expires; String _expires;
public MovedContextHandler() public MovedContextHandler()

View File

@ -202,8 +202,7 @@ public class ResourceHandler extends AbstractHandler
try try
{ {
path=URIUtil.canonicalPath(path); path=URIUtil.canonicalPath(path);
Resource resource=base.addPath(path); return base.addPath(path);
return resource;
} }
catch(Exception e) catch(Exception e)
{ {

View File

@ -77,7 +77,7 @@ import org.eclipse.jetty.server.Request;
*/ */
public abstract class ScopedHandler extends HandlerWrapper 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 _outerScope;
protected ScopedHandler _nextScope; protected ScopedHandler _nextScope;

View File

@ -88,10 +88,9 @@ public class StatisticsHandler extends HandlerWrapper implements CompleteHandler
long timestamp1=timestamp0; long timestamp1=timestamp0;
try try
{ {
AsyncContinuation asyncContextState=baseRequest.getAsyncContinuation();
synchronized(this) synchronized(this)
{ {
AsyncContinuation asyncContextState=baseRequest.getAsyncContinuation();
if(asyncContextState==null) if(asyncContextState==null)
{ {
_requests++; _requests++;

View File

@ -121,8 +121,8 @@ public class BlockingChannelConnector extends AbstractNIOConnector
/* ------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------- */
private class Connection extends ChannelEndPoint implements Runnable private class Connection extends ChannelEndPoint implements Runnable
{ {
final HttpConnection _connection;
boolean _dispatched=false; boolean _dispatched=false;
HttpConnection _connection;
int _sotimeout; int _sotimeout;
Connection(ByteChannel channel) Connection(ByteChannel channel)
@ -136,7 +136,7 @@ public class BlockingChannelConnector extends AbstractNIOConnector
if (!getThreadPool().dispatch(this)) if (!getThreadPool().dispatch(this))
{ {
Log.warn("dispatch failed for {}",_connection); Log.warn("dispatch failed for {}",_connection);
close(); Connection.this.close();
} }
} }
@ -166,19 +166,19 @@ public class BlockingChannelConnector extends AbstractNIOConnector
catch (EofException e) catch (EofException e)
{ {
Log.debug("EOF", e); Log.debug("EOF", e);
try{close();} try{Connection.this.close();}
catch(IOException e2){Log.ignore(e2);} catch(IOException e2){Log.ignore(e2);}
} }
catch (HttpException e) catch (HttpException e)
{ {
Log.debug("BAD", e); Log.debug("BAD", e);
try{close();} try{Connection.this.close();}
catch(IOException e2){Log.ignore(e2);} catch(IOException e2){Log.ignore(e2);}
} }
catch(Throwable e) catch(Throwable e)
{ {
Log.warn("handle failed",e); Log.warn("handle failed",e);
try{close();} try{Connection.this.close();}
catch(IOException e2){Log.ignore(e2);} catch(IOException e2){Log.ignore(e2);}
} }
finally finally

View File

@ -61,11 +61,11 @@ import org.eclipse.jetty.util.thread.Timeout.Task;
*/ */
public class SelectChannelConnector extends AbstractNIOConnector public class SelectChannelConnector extends AbstractNIOConnector
{ {
protected transient ServerSocketChannel _acceptChannel; protected ServerSocketChannel _acceptChannel;
private long _lowResourcesConnections; private long _lowResourcesConnections;
private long _lowResourcesMaxIdleTime; private long _lowResourcesMaxIdleTime;
private SelectorManager _manager = new SelectorManager() private final SelectorManager _manager = new SelectorManager()
{ {
protected SocketChannel acceptChannel(SelectionKey key) throws IOException protected SocketChannel acceptChannel(SelectionKey key) throws IOException
{ {

View File

@ -33,7 +33,7 @@ public abstract class AbstractSessionIdManager extends AbstractLifeCycle impleme
protected Random _random; protected Random _random;
protected boolean _weakRandom; protected boolean _weakRandom;
protected String _workerName; protected String _workerName;
protected Server _server; protected final Server _server;
public AbstractSessionIdManager(Server server) public AbstractSessionIdManager(Server server)

View File

@ -152,7 +152,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
if (_sessionIdManager==null) if (_sessionIdManager==null)
{ {
Server server=getSessionHandler().getServer(); final Server server=getSessionHandler().getServer();
synchronized (server) synchronized (server)
{ {
_sessionIdManager=server.getSessionIdManager(); _sessionIdManager=server.getSessionIdManager();
@ -544,6 +544,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
*/ */
protected void addSession(Session session, boolean created) protected void addSession(Session session, boolean created)
{ {
//noinspection SynchronizeOnNonFinalField
synchronized (_sessionIdManager) synchronized (_sessionIdManager)
{ {
_sessionIdManager.addSession(session); _sessionIdManager.addSession(session);
@ -627,6 +628,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
public void removeSession(Session session, boolean invalidate) public void removeSession(Session session, boolean invalidate)
{ {
// Remove session from context and global maps // Remove session from context and global maps
//noinspection SynchronizeOnNonFinalField
synchronized (_sessionIdManager) synchronized (_sessionIdManager)
{ {
boolean removed = false; boolean removed = false;
@ -1082,8 +1084,6 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
if (old_value==null) if (old_value==null)
l.attributeAdded(event); l.attributeAdded(event);
else if (value==null)
l.attributeRemoved(event);
else else
l.attributeReplaced(event); l.attributeReplaced(event);
} }

View File

@ -228,7 +228,7 @@ public class HashSessionIdManager extends AbstractLifeCycle implements SessionId
?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^(((long)request.hashCode())<<32)) ?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^(((long)request.hashCode())<<32))
:_random.nextLong(); :_random.nextLong();
r^=created; r^=created;
if (request!=null && request.getRemoteAddr()!=null) if (request.getRemoteAddr()!=null)
r^=request.getRemoteAddr().hashCode(); r^=request.getRemoteAddr().hashCode();
if (r<0) if (r<0)
r=-r; r=-r;

View File

@ -286,7 +286,7 @@ public class HashSessionManager extends AbstractSessionManager
long idleTime=session._maxIdleMs; long idleTime=session._maxIdleMs;
if (idleTime>0&&session._accessed+idleTime<System.currentTimeMillis()) if (idleTime>0&&session._accessed+idleTime<System.currentTimeMillis())
{ {
((Session)session).timeout(); session.timeout();
int nbsess=this._sessions.size(); int nbsess=this._sessions.size();
if (nbsess<this._minSessions) if (nbsess<this._minSessions)
this._minSessions=nbsess; this._minSessions=nbsess;

View File

@ -52,7 +52,7 @@ import org.eclipse.jetty.util.log.Log;
*/ */
public class JDBCSessionIdManager extends AbstractSessionIdManager public class JDBCSessionIdManager extends AbstractSessionIdManager
{ {
protected HashSet<String> _sessionIds = new HashSet(); protected final HashSet<String> _sessionIds = new HashSet();
protected String _driverClassName; protected String _driverClassName;
protected String _connectionUrl; protected String _connectionUrl;
protected DataSource _datasource; protected DataSource _datasource;
@ -353,8 +353,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
Handler[] contexts = _server.getChildHandlersByClass(ContextHandler.class); Handler[] contexts = _server.getChildHandlersByClass(ContextHandler.class);
for (int i=0; contexts!=null && i<contexts.length; i++) for (int i=0; contexts!=null && i<contexts.length; i++)
{ {
SessionManager manager = (SessionManager) SessionManager manager = ((SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class)).getSessionManager();
((SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class)).getSessionManager();
if (manager instanceof JDBCSessionManager) if (manager instanceof JDBCSessionManager)
{ {
@ -597,10 +596,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
PreparedStatement statement = connection.prepareStatement(_queryId); PreparedStatement statement = connection.prepareStatement(_queryId);
statement.setString(1, id); statement.setString(1, id);
ResultSet result = statement.executeQuery(); ResultSet result = statement.executeQuery();
if (result.next()) return result.next();
return true;
else
return false;
} }
finally finally
{ {
@ -651,8 +647,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
Handler[] contexts = _server.getChildHandlersByClass(ContextHandler.class); Handler[] contexts = _server.getChildHandlersByClass(ContextHandler.class);
for (int i=0; contexts!=null && i<contexts.length; i++) for (int i=0; contexts!=null && i<contexts.length; i++)
{ {
SessionManager manager = (SessionManager) SessionManager manager = ((SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class)).getSessionManager();
((SessionHandler)((ContextHandler)contexts[i]).getChildHandlerByClass(SessionHandler.class)).getSessionManager();
if (manager instanceof JDBCSessionManager) if (manager instanceof JDBCSessionManager)
{ {

View File

@ -82,7 +82,7 @@ public class JDBCSessionManager extends AbstractSessionManager
*/ */
public class SessionData public class SessionData
{ {
private String _id; private final String _id;
private String _rowId; private String _rowId;
private long _accessed; private long _accessed;
private long _lastAccessed; private long _lastAccessed;
@ -249,7 +249,7 @@ public class JDBCSessionManager extends AbstractSessionManager
*/ */
public class Session extends AbstractSessionManager.Session public class Session extends AbstractSessionManager.Session
{ {
private SessionData _data; private final SessionData _data;
private boolean _dirty=false; private boolean _dirty=false;
/** /**
@ -622,9 +622,9 @@ public class JDBCSessionManager extends AbstractSessionManager
//then session data will be lost. //then session data will be lost.
try try
{ {
((JDBCSessionManager.Session)session).willPassivate(); session.willPassivate();
storeSession(((JDBCSessionManager.Session)session)._data); storeSession(((JDBCSessionManager.Session)session)._data);
((JDBCSessionManager.Session)session).didActivate(); session.didActivate();
} }
catch (Exception e) catch (Exception e)
{ {

View File

@ -54,7 +54,7 @@ public class ServletSSL
* @param cipherSuite String name of the TLS cipher suite. * @param cipherSuite String name of the TLS cipher suite.
* @return int indicating the effective key entropy bit-length. * @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. // Roughly ordered from most common to least common.
if (cipherSuite == null) if (cipherSuite == null)

View File

@ -634,9 +634,9 @@ public class SslSelectChannelConnector extends SelectChannelConnector
*/ */
private class CachedInfo private class CachedInfo
{ {
private X509Certificate[] _certs; private final X509Certificate[] _certs;
private Integer _keySize; private final Integer _keySize;
private String _idStr; private final String _idStr;
CachedInfo(Integer keySize, X509Certificate[] certs,String idStr) CachedInfo(Integer keySize, X509Certificate[] certs,String idStr)
{ {

View File

@ -595,9 +595,9 @@ public class SslSocketConnector extends SocketConnector
*/ */
private class CachedInfo private class CachedInfo
{ {
private X509Certificate[] _certs; private final X509Certificate[] _certs;
private Integer _keySize; private final Integer _keySize;
private String _idStr; private final String _idStr;
CachedInfo(Integer keySize, X509Certificate[] certs,String id) CachedInfo(Integer keySize, X509Certificate[] certs,String id)

View File

@ -169,7 +169,7 @@ public class AsyncStressTest extends TestCase
private static class SuspendHandler extends HandlerWrapper private static class SuspendHandler extends HandlerWrapper
{ {
private Timer _timer; private final Timer _timer;
public SuspendHandler() public SuspendHandler()
{ {

View File

@ -91,7 +91,7 @@ public class BusySelectChannelServerTest extends HttpServerTestBase
if (x<8) if (x<8)
return 0; return 0;
if (x<16 & buffer.space()>=1) if (x<16 && buffer.space()>=1)
{ {
NIOBuffer one = new IndirectNIOBuffer(1); NIOBuffer one = new IndirectNIOBuffer(1);
int l=super.fill(one); int l=super.fill(one);
@ -100,7 +100,7 @@ public class BusySelectChannelServerTest extends HttpServerTestBase
return l; return l;
} }
if (x<24 & buffer.space()>=2) if (x<24 && buffer.space()>=2)
{ {
NIOBuffer two = new IndirectNIOBuffer(2); NIOBuffer two = new IndirectNIOBuffer(2);
int l=super.fill(two); int l=super.fill(two);
@ -111,7 +111,7 @@ public class BusySelectChannelServerTest extends HttpServerTestBase
return l; return l;
} }
if (x<64 & buffer.space()>=3) if (x<64 && buffer.space()>=3)
{ {
NIOBuffer three = new IndirectNIOBuffer(3); NIOBuffer three = new IndirectNIOBuffer(3);
int l=super.fill(three); int l=super.fill(three);

View File

@ -127,6 +127,8 @@ public class DumpHandler extends AbstractHandler
{ {
String cookie_action=request.getParameter("Button"); String cookie_action=request.getParameter("Button");
try{ try{
String val=request.getParameter("CookieVal");
val=val.replaceAll("[ \n\r=<>]","?");
Cookie cookie= Cookie cookie=
new Cookie(cookie_name.trim(), new Cookie(cookie_name.trim(),
request.getParameter("CookieVal")); request.getParameter("CookieVal"));

View File

@ -261,7 +261,7 @@ public class HttpServerTestBase extends TestCase
int[] points=new int[pointCount]; int[] points=new int[pointCount];
StringBuilder message=new StringBuilder(); StringBuilder message=new StringBuilder();
message.append("iteration #"+(i+1)); message.append("iteration #").append(i + 1);
// Pick fragment points at random // Pick fragment points at random
for (int j=0; j<points.length; ++j) for (int j=0; j<points.length; ++j)
@ -306,7 +306,7 @@ public class HttpServerTestBase extends TestCase
int[] points=new int[] { i }; int[] points=new int[] { i };
StringBuilder message=new StringBuilder(); StringBuilder message=new StringBuilder();
message.append("iteration #"+(i+1)); message.append("iteration #").append(i + 1);
// Sort the list // Sort the list
Arrays.sort(points); Arrays.sort(points);
@ -358,7 +358,7 @@ public class HttpServerTestBase extends TestCase
OutputStream os=client.getOutputStream(); OutputStream os=client.getOutputStream();
StringBuilder message=new StringBuilder(); StringBuilder message=new StringBuilder();
message.append("iteration #"+(i+1)); message.append("iteration #").append(i + 1);
writeFragments(bytes,badPoints[i],message,os); writeFragments(bytes,badPoints[i],message,os);
// Read the response // Read the response
@ -802,7 +802,7 @@ public class HttpServerTestBase extends TestCase
Thread.sleep(PAUSE); Thread.sleep(PAUSE);
// Update the log message // Update the log message
message.append(" point #"+(j+1)+": "+point); message.append(" point #").append(j + 1).append(": ").append(point);
} }
// Write the last fragment // Write the last fragment

View File

@ -392,7 +392,7 @@ public class ResponseTest extends TestCase
while (line!=null && line.length()==0) while (line!=null && line.length()==0)
line = reader.readLine(); line = reader.readLine();
assertTrue(line.startsWith("HTTP/1.1 200 OK")); assertTrue(line!=null && line.startsWith("HTTP/1.1 200 OK"));
} }
finally finally

View File

@ -333,9 +333,9 @@ public class StressTest extends TestCase
finally finally
{ {
int quantums=48; int quantums=48;
int[][] count = new int[_latencies.length][quantums]; final int[][] count = new int[_latencies.length][quantums];
int length[] = new int[_latencies.length]; final int length[] = new int[_latencies.length];
int other[] = new int[_latencies.length]; final int other[] = new int[_latencies.length];
for (int i=0;i<_latencies.length;i++) for (int i=0;i<_latencies.length;i++)
{ {

View File

@ -113,12 +113,12 @@ public class ScopedHandlerTest extends TestCase
{ {
try try
{ {
_history.append(">S"+_name); _history.append(">S").append(_name);
super.nextScope(target,baseRequest,request, response); super.nextScope(target,baseRequest,request, response);
} }
finally finally
{ {
_history.append("<S"+_name); _history.append("<S").append(_name);
} }
} }
@ -126,12 +126,12 @@ public class ScopedHandlerTest extends TestCase
{ {
try try
{ {
_history.append(">W"+_name); _history.append(">W").append(_name);
super.nextHandle(target,baseRequest,request,response); super.nextHandle(target,baseRequest,request,response);
} }
finally finally
{ {
_history.append("<W"+_name); _history.append("<W").append(_name);
} }
} }
@ -150,12 +150,12 @@ public class ScopedHandlerTest extends TestCase
{ {
try try
{ {
_history.append(">H"+_name); _history.append(">H").append(_name);
super.handle(target,baseRequest,request, response); super.handle(target,baseRequest,request, response);
} }
finally finally
{ {
_history.append("<H"+_name); _history.append("<H").append(_name);
} }
} }
} }

View File

@ -203,7 +203,7 @@ public class StatisticsHandlerTest extends TestCase
private static class ActiveHandler extends HandlerWrapper private static class ActiveHandler extends HandlerWrapper
{ {
private Object _lock; private final Object _lock;
public ActiveHandler(Object lock) public ActiveHandler(Object lock)
{ {