Merge branch 'jetty-8' into release-8

This commit is contained in:
Jesse McConnell 2011-10-24 14:39:27 -05:00
commit b074bbdeba
82 changed files with 1094 additions and 414 deletions

2
.gitignore vendored
View File

@ -32,5 +32,5 @@ target/
# vim
.*.sw[a-p]
# kdiff merge
# merge tooling
*.orig

View File

@ -56,6 +56,10 @@ jetty-8.0.2.v20111006 - 06 October 2011
+ JETTY-1434 Add a jsp that exercises jstl.
+ JETTY-1439 space in directory installation path causes classloader problem
jetty-7.5.3.v20111011 - 11 October 2011
+ 348978 migrate jetty-http-spi
+ 358649 StdErrLog system properties for package/class logging LEVEL.
jetty-7.5.2.v20111006 - 06 October 2011
+ 336443 add missing comma in DigestAuthenticator string
+ 342161 ScannerTest fails intermittently on Mac OS X

View File

@ -28,6 +28,11 @@
<artifactId>jetty-servlets</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-rewrite</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-deploy</artifactId>
@ -42,6 +47,11 @@
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-ajp</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-test-helper</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>

View File

@ -73,7 +73,7 @@ public class LikeJettyXml
SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
ssl_connector.setPort(8443);
SslContextFactory cf = ssl_connector.getSslContextFactory();
cf.setKeyStore(jetty_home + "/etc/keystore");
cf.setKeyStorePath(jetty_home + "/etc/keystore");
cf.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
cf.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
cf.setTrustStore(jetty_home + "/etc/keystore");

View File

@ -47,7 +47,7 @@ public class ManyConnectors
System.setProperty("jetty.home",jetty_home);
ssl_connector.setPort(8443);
SslContextFactory cf = ssl_connector.getSslContextFactory();
cf.setKeyStore(jetty_home + "/etc/keystore");
cf.setKeyStorePath(jetty_home + "/etc/keystore");
cf.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
cf.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");

View File

@ -698,14 +698,14 @@ public class HttpClient extends HttpBuffers implements Attributes, Dumpable
@Deprecated
public String getKeyStoreLocation()
{
return _sslContextFactory.getKeyStore();
return _sslContextFactory.getKeyStorePath();
}
/* ------------------------------------------------------------ */
@Deprecated
public void setKeyStoreLocation(String keyStoreLocation)
{
_sslContextFactory.setKeyStore(keyStoreLocation);
_sslContextFactory.setKeyStorePath(keyStoreLocation);
}
@Deprecated

View File

@ -37,6 +37,7 @@ import org.eclipse.jetty.io.Buffers;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.io.View;
import org.eclipse.jetty.io.nio.SslSelectChannelEndPoint;
import org.eclipse.jetty.util.component.AggregateLifeCycle;
@ -279,7 +280,7 @@ public class HttpConnection extends AbstractConnection implements Dumpable
io += filled;
if (_parser.isIdle() && (_endp.isInputShutdown() || !_endp.isOpen()))
throw new EOFException();
throw new EofException();
}
if (io > 0)

View File

@ -593,7 +593,8 @@ public class HttpExchange
if (uri.isOpaque())
throw new IllegalArgumentException("Opaque URI: " + uri);
LOG.debug("URI = {}",uri.toASCIIString());
if (LOG.isDebugEnabled())
LOG.debug("URI = {}",uri.toASCIIString());
String scheme = uri.getScheme();
int port = uri.getPort();

View File

@ -168,7 +168,8 @@ class SelectConnector extends AbstractLifeCycle implements HttpClient.Connector
Timeout.Task connectTimeout = _connectingChannels.remove(channel);
if (connectTimeout != null)
connectTimeout.cancel();
LOG.debug("Channels with connection pending: {}", _connectingChannels.size());
if (LOG.isDebugEnabled())
LOG.debug("Channels with connection pending: {}", _connectingChannels.size());
// key should have destination at this point (will be replaced by endpoint after this call)
HttpDestination dest=(HttpDestination)key.attachment();
@ -228,6 +229,10 @@ class SelectConnector extends AbstractLifeCycle implements HttpClient.Connector
@Override
protected void connectionFailed(SocketChannel channel, Throwable ex, Object attachment)
{
Timeout.Task connectTimeout = _connectingChannels.remove(channel);
if (connectTimeout != null)
connectTimeout.cancel();
if (attachment instanceof HttpDestination)
((HttpDestination)attachment).onConnectionFailed(ex);
else

View File

@ -47,7 +47,7 @@ public class ProxyTunnellingTest
SslSelectChannelConnector connector = new SslSelectChannelConnector();
String keyStorePath = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath();
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keyStorePath);
cf.setKeyStorePath(keyStorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
startServer(connector, handler);

View File

@ -58,7 +58,7 @@ public class SslCertSecuredExchangeTest extends ContentExchangeTest
cf.setValidateCerts(true);
cf.setCrlPath(_crlpath);
cf.setNeedClientAuth(true);
cf.setKeyStore(_keypath);
cf.setKeyStorePath(_keypath);
cf.setKeyStorePassword(_password);
cf.setKeyManagerPassword(_password);
cf.setTrustStore(_trustpath);
@ -159,7 +159,7 @@ public class SslCertSecuredExchangeTest extends ContentExchangeTest
cf.setCrlPath(_crlpath);
cf.setCertAlias("client");
cf.setKeyStore(_clientpath);
cf.setKeyStorePath(_clientpath);
cf.setKeyStorePassword(_password);
cf.setKeyManagerPassword(_password);

View File

@ -37,7 +37,7 @@ public class SslContentExchangeTest
SslSelectChannelConnector connector = new SslSelectChannelConnector();
File keystore = MavenTestingUtils.getTestResourceFile("keystore");
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystore.getAbsolutePath());
cf.setKeyStorePath(keystore.getAbsolutePath());
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setSessionCachingEnabled(true);

View File

@ -63,7 +63,7 @@ extends ContentExchangeTest
SslSelectChannelConnector connector = new SslSelectChannelConnector();
File keystore = MavenTestingUtils.getTestResourceFile("keystore");
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystore.getAbsolutePath());
cf.setKeyStorePath(keystore.getAbsolutePath());
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
server.addConnector(connector);

View File

@ -165,7 +165,7 @@ public class SslSecurityListenerTest
connector.setPort(0);
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystore);
cf.setKeyStorePath(keystore);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");

View File

@ -52,7 +52,7 @@ public abstract class SslValidationTestBase extends ContentExchangeTest
srvFactory.setCrlPath(_crlpath);
srvFactory.setNeedClientAuth(true);
srvFactory.setKeyStore(_keypath);
srvFactory.setKeyStorePath(_keypath);
srvFactory.setKeyStorePassword(_password);
srvFactory.setKeyManagerPassword(_password);
@ -88,7 +88,7 @@ public abstract class SslValidationTestBase extends ContentExchangeTest
cf.setValidateCerts(true);
cf.setCrlPath(_crlpath);
cf.setKeyStore(_clientpath);
cf.setKeyStorePath(_clientpath);
cf.setKeyStorePassword(_password);
cf.setKeyManagerPassword(_password);

View File

@ -42,7 +42,7 @@ public abstract class AbstractSslServerAndClientCreator implements ServerAndClie
connector.setPort(0);
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystore);
cf.setKeyStorePath(keystore);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
connector.setAllowRenegotiate(true);

View File

@ -481,7 +481,7 @@ public class DeploymentManager extends AggregateLifeCycle
while (it.hasNext())
{
Node node = it.next();
LOG.debug("Executing Node: " + node);
LOG.debug("Executing Node {}",node);
_lifecycle.runBindings(node,appentry.app,this);
appentry.setLifeCycleNode(node);
}

View File

@ -257,7 +257,7 @@ public class WebAppDeployer extends AbstractLifeCycle
if (path != null && path.equals(app.getFile().getCanonicalPath()))
{
LOG.debug("Already deployed:"+path);
LOG.debug("Already deployed: {}",path);
continue files;
}
}

View File

@ -51,13 +51,14 @@ public class StandardUndeployer implements AppLifeCycle.Binding
for (int i = 0, n = children.length; i < n; i++)
{
Handler child = children[i];
LOG.debug("Child handler: " + child);
LOG.debug("Child handler {}",child);
if (child.equals(context))
{
LOG.debug("Removing handler: " + child);
LOG.debug("Removing handler {}",child);
coll.removeHandler(child);
child.destroy();
LOG.debug(String.format("After removal: %d (originally %d)",coll.getHandlers().length,originalCount));
if (LOG.isDebugEnabled())
LOG.debug("After removal: {} (originally {})",coll.getHandlers().length,originalCount);
}
else if (child instanceof HandlerCollection)
{

View File

@ -99,7 +99,8 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A
@Override
protected void doStart() throws Exception
{
if (LOG.isDebugEnabled()) LOG.debug(this.getClass().getSimpleName() + ".doStart()");
if (LOG.isDebugEnabled())
LOG.debug(this.getClass().getSimpleName() + ".doStart()");
if (_monitoredDir == null)
{
throw new IllegalStateException("No configuration dir specified");
@ -132,7 +133,8 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A
/* ------------------------------------------------------------ */
protected void fileAdded(String filename) throws Exception
{
if (LOG.isDebugEnabled()) LOG.debug("added ",filename);
if (LOG.isDebugEnabled())
LOG.debug("added {}",filename);
App app = ScanningAppProvider.this.createApp(filename);
if (app != null)
{
@ -144,7 +146,8 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A
/* ------------------------------------------------------------ */
protected void fileChanged(String filename) throws Exception
{
if (LOG.isDebugEnabled()) LOG.debug("changed ",filename);
if (LOG.isDebugEnabled())
LOG.debug("changed {}",filename);
App app = _appMap.remove(filename);
if (app != null)
{
@ -161,7 +164,8 @@ public abstract class ScanningAppProvider extends AbstractLifeCycle implements A
/* ------------------------------------------------------------ */
protected void fileRemoved(String filename) throws Exception
{
if (LOG.isDebugEnabled()) LOG.debug("removed ",filename);
if (LOG.isDebugEnabled())
LOG.debug("removed {}",filename);
App app = _appMap.remove(filename);
if (app != null)
_deploymentManager.removeApp(app);

View File

@ -157,7 +157,8 @@ public class HttpGenerator extends AbstractGenerator
if (_last || _state==STATE_END)
{
LOG.debug("Ignoring extra content {}",content);
if (LOG.isDebugEnabled())
LOG.debug("Ignoring extra content {}",content.toDetailString());
content.clear();
return;
}
@ -242,7 +243,8 @@ public class HttpGenerator extends AbstractGenerator
if (_last || _state==STATE_END)
{
LOG.debug("Ignoring extra content {}",Byte.valueOf(b));
if (LOG.isDebugEnabled())
LOG.debug("Ignoring extra content {}",Byte.valueOf(b));
return false;
}

View File

@ -306,7 +306,7 @@ public class HttpParser implements Parser
throw ex;
if (!isComplete() && !isIdle())
throw new EOFException();
throw new EofException();
return -1;
}

View File

@ -178,6 +178,8 @@ public class SslContextFactory extends AbstractLifeCycle
/** SSL context */
private SSLContext _context;
private boolean _trustAll;
/* ------------------------------------------------------------ */
/**
* Construct an instance of SslContextFactory
@ -185,6 +187,17 @@ public class SslContextFactory extends AbstractLifeCycle
*/
public SslContextFactory()
{
_trustAll=true;
}
/* ------------------------------------------------------------ */
/**
* Construct an instance of SslContextFactory
* Default constructor for use in XmlConfiguration files
*/
public SslContextFactory(boolean trustAll)
{
_trustAll=trustAll;
}
/* ------------------------------------------------------------ */
@ -207,29 +220,36 @@ public class SslContextFactory extends AbstractLifeCycle
{
if (_context == null)
{
if (_keyStoreInputStream == null && _keyStorePath == null &&
_trustStoreInputStream == null && _trustStorePath == null )
if (_keyStore==null && _keyStoreInputStream == null && _keyStorePath == null &&
_trustStore==null && _trustStoreInputStream == null && _trustStorePath == null )
{
LOG.debug("No keystore or trust store configured. ACCEPTING UNTRUSTED CERTIFICATES!!!!!");
// Create a trust manager that does not validate certificate chains
TrustManager trustAllCerts = new X509TrustManager()
TrustManager[] trust_managers=null;
if (_trustAll)
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
LOG.info("No keystore or trust store configured. ACCEPTING UNTRUSTED CERTIFICATES!!!!!");
// Create a trust manager that does not validate certificate chains
TrustManager trustAllCerts = new X509TrustManager()
{
return null;
}
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
}
};
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
}
};
trust_managers = new TrustManager[] { trustAllCerts };
}
SecureRandom secureRandom = (_secureRandomAlgorithm == null)?null:SecureRandom.getInstance(_secureRandomAlgorithm);
_context = SSLContext.getInstance(_sslProtocol);
_context.init(null, new TrustManager[]{trustAllCerts}, null);
_context.init(null, trust_managers, secureRandom);
}
else
{
@ -279,8 +299,10 @@ public class SslContextFactory extends AbstractLifeCycle
_context.init(keyManagers,trustManagers,secureRandom);
SSLEngine engine=newSslEngine();
LOG.info("Enabled Protocols {} of {}",Arrays.asList(engine.getEnabledProtocols()),Arrays.asList(engine.getSupportedProtocols()));
LOG.debug("Enabled Ciphers {} of {}",Arrays.asList(engine.getEnabledCipherSuites()),Arrays.asList(engine.getSupportedCipherSuites()));
if (LOG.isDebugEnabled())
LOG.debug("Enabled Ciphers {} of {}",Arrays.asList(engine.getEnabledCipherSuites()),Arrays.asList(engine.getSupportedCipherSuites()));
}
}
}
@ -402,6 +424,13 @@ public class SslContextFactory extends AbstractLifeCycle
/**
* @return The file or URL of the SSL Key store.
*/
public String getKeyStorePath()
{
return _keyStorePath;
}
/* ------------------------------------------------------------ */
@Deprecated
public String getKeyStore()
{
return _keyStorePath;
@ -412,6 +441,19 @@ public class SslContextFactory extends AbstractLifeCycle
* @param keyStorePath
* The file or URL of the SSL Key store.
*/
public void setKeyStorePath(String keyStorePath)
{
checkNotStarted();
_keyStorePath = keyStorePath;
}
/* ------------------------------------------------------------ */
/**
* @param keyStorePath
* @deprecated Use {@link #setKeyStorePath(String)}
*/
@Deprecated
public void setKeyStore(String keyStorePath)
{
checkNotStarted();
@ -479,7 +521,7 @@ public class SslContextFactory extends AbstractLifeCycle
/** Set the keyStoreInputStream.
* @param keyStoreInputStream the InputStream to the KeyStore
*
* @deprecated
* @deprecated Use {@link #setKeyStore(KeyStore)}
*/
@Deprecated
public void setKeyStoreInputStream(InputStream keyStoreInputStream)
@ -864,10 +906,29 @@ public class SslContextFactory extends AbstractLifeCycle
return (_trustManagerFactoryAlgorithm);
}
/* ------------------------------------------------------------ */
/**
* @return True if all certificates should be trusted if there is no KeyStore or TrustStore
*/
public boolean isTrustAll()
{
return _trustAll;
}
/* ------------------------------------------------------------ */
/**
* @param trustAll True if all certificates should be trusted if there is no KeyStore or TrustStore
*/
public void setTrustAll(boolean trustAll)
{
_trustAll = trustAll;
}
/* ------------------------------------------------------------ */
/**
* @param algorithm
* The algorithm name (default "SunX509") used by the {@link TrustManagerFactory}
* Use the string "TrustAll" to install a trust manager that trusts all.
*/
public void setTrustManagerFactoryAlgorithm(String algorithm)
{

View File

@ -0,0 +1,75 @@
package org.eclipse.jetty.http;
import static junit.framework.Assert.assertTrue;
import java.io.FileInputStream;
import java.security.KeyStore;
import org.eclipse.jetty.http.ssl.SslContextFactory;
import org.junit.Test;
public class SslContextFactoryTest
{
@Test
public void testNoTsFileKs() throws Exception
{
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
SslContextFactory cf = new SslContextFactory(keystorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.start();
assertTrue(cf.getSslContext()!=null);
}
@Test
public void testNoTsStreamKs() throws Exception
{
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
SslContextFactory cf = new SslContextFactory();
cf.setKeyStoreInputStream(new FileInputStream(keystorePath));
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.start();
assertTrue(cf.getSslContext()!=null);
}
@Test
public void testNoTsSetKs() throws Exception
{
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystorePath),"storepwd".toCharArray());
SslContextFactory cf = new SslContextFactory();
cf.setKeyStore(ks);
cf.setKeyManagerPassword("keypwd");
cf.start();
assertTrue(cf.getSslContext()!=null);
}
@Test
public void testNoTsNoKs() throws Exception
{
SslContextFactory cf = new SslContextFactory();
cf.start();
assertTrue(cf.getSslContext()!=null);
}
@Test
public void testTrustAll() throws Exception
{
SslContextFactory cf = new SslContextFactory();
cf.start();
assertTrue(cf.getSslContext()!=null);
}
}

Binary file not shown.

View File

@ -16,6 +16,7 @@ package org.eclipse.jetty.io.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.GatheringByteChannel;
@ -129,10 +130,17 @@ public class ChannelEndPoint implements EndPoint
Socket socket= ((SocketChannel)_channel).socket();
if (!socket.isClosed())
{
if (socket.isInputShutdown())
socket.close();
else if (!socket.isOutputShutdown())
socket.shutdownOutput();
try
{
if (socket.isInputShutdown())
socket.close();
else if (!socket.isOutputShutdown())
socket.shutdownOutput();
}
catch(SocketException e)
{
LOG.ignore(e);
}
}
}
}

View File

@ -72,7 +72,8 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
_engine=engine;
_session=engine.getSession();
if (_debug) LOG.debug(_session+" channel="+channel);
if (_debug)
LOG.debug(_session+" channel="+channel);
}
/* ------------------------------------------------------------ */
@ -86,7 +87,8 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
_engine=engine;
_session=engine.getSession();
if (_debug) LOG.debug(_session+" channel="+channel);
if (_debug)
LOG.debug(_session+" channel="+channel);
}
@ -503,7 +505,8 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
int total_filled=0;
boolean remoteClosed = false;
LOG.debug("{} unwrap space={} open={}",_session,_inNIOBuffer.space(),super.isOpen());
if (LOG.isDebugEnabled())
LOG.debug("{} unwrap space={} open={}",_session,_inNIOBuffer.space(),super.isOpen());
// loop filling as much encrypted data as we can into the buffer
while (_inNIOBuffer.space()>0 && super.isOpen())
@ -561,7 +564,7 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
}
catch(SSLException e)
{
LOG.warn(getRemoteAddr() + ":" + getRemotePort() + " ",e);
LOG.debug(getRemoteAddr() + ":" + getRemotePort() + " ",e);
super.close();
throw e;
}
@ -637,7 +640,8 @@ public class SslSelectChannelEndPoint extends SelectChannelEndPoint
out_buffer.position(_outNIOBuffer.putIndex());
out_buffer.limit(out_buffer.capacity());
_result=_engine.wrap(bbuf,out_buffer);
if (_debug) LOG.debug("{} wrap {}",_session,_result);
if (_debug)
LOG.debug("{} wrap {}",_session,_result);
if (!_handshook && _result.getHandshakeStatus()==SSLEngineResult.HandshakeStatus.FINISHED)
_handshook=true;
_outNIOBuffer.setPutIndex(out_buffer.position());

View File

@ -41,7 +41,7 @@ import org.eclipse.jetty.util.thread.ShutdownThread;
*/
public class MBeanContainer extends AbstractLifeCycle implements Container.Listener, Dumpable
{
private final static Logger __log = Log.getLogger(MBeanContainer.class.getName());
private final static Logger LOG = Log.getLogger(MBeanContainer.class.getName());
private final MBeanServer _server;
private final WeakHashMap<Object, ObjectName> _beans = new WeakHashMap<Object, ObjectName>();
@ -93,7 +93,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
}
catch (Exception e)
{
__log.ignore(e);
LOG.ignore(e);
}
}
@ -134,7 +134,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
*/
public synchronized void add(Relationship relationship)
{
__log.debug("add {}",relationship);
LOG.debug("add {}",relationship);
ObjectName parent = _beans.get(relationship.getParent());
if (parent == null)
{
@ -168,7 +168,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
*/
public synchronized void remove(Relationship relationship)
{
__log.debug("remove {}",relationship);
LOG.debug("remove {}",relationship);
ObjectName parent = _beans.get(relationship.getParent());
ObjectName child = _beans.get(relationship.getChild());
@ -194,7 +194,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
*/
public synchronized void removeBean(Object obj)
{
__log.debug("removeBean {}",obj);
LOG.debug("removeBean {}",obj);
ObjectName bean = _beans.remove(obj);
if (bean != null)
@ -202,7 +202,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
List<Container.Relationship> beanRelations= _relations.remove(bean);
if (beanRelations != null)
{
__log.debug("Unregister {}", beanRelations);
LOG.debug("Unregister {}", beanRelations);
List<?> removeList = new ArrayList<Object>(beanRelations);
for (Object r : removeList)
{
@ -214,15 +214,15 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
try
{
_server.unregisterMBean(bean);
__log.debug("Unregistered {}", bean);
LOG.debug("Unregistered {}", bean);
}
catch (javax.management.InstanceNotFoundException e)
{
__log.ignore(e);
LOG.ignore(e);
}
catch (Exception e)
{
__log.warn(e);
LOG.warn(e);
}
}
}
@ -234,7 +234,7 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
*/
public synchronized void addBean(Object obj)
{
__log.debug("addBean {}",obj);
LOG.debug("addBean {}",obj);
try
{
if (obj == null || _beans.containsKey(obj))
@ -298,13 +298,13 @@ public class MBeanContainer extends AbstractLifeCycle implements Container.Liste
}
ObjectInstance oinstance = _server.registerMBean(mbean, oname);
__log.debug("Registered {}", oinstance.getObjectName());
LOG.debug("Registered {}", oinstance.getObjectName());
_beans.put(obj, oinstance.getObjectName());
}
catch (Exception e)
{
__log.warn("bean: " + obj, e);
LOG.warn("bean: " + obj, e);
}
}

View File

@ -280,7 +280,7 @@ public class ProxyRule extends PatternRule
if (debug != 0)
{
_log.debug(debug + " " + request.getMethod() + " " + url + " " + request.getProtocol());
_log.debug("{} {} {} {}", debug ,request.getMethod(), url, request.getProtocol());
}
boolean hasContent = createHeaders(request,debug,exchange);
@ -393,7 +393,7 @@ public class ProxyRule extends PatternRule
if (val != null)
{
if (debug != 0)
_log.debug(debug + " " + hdr + ": " + val);
_log.debug("{} {} {}",debug,hdr,val);
exchange.setRequestHeader(hdr,val);
}

View File

@ -135,9 +135,8 @@ public class HashLoginService extends MappedLoginService implements UserListener
if (_propertyUserStore == null)
{
if(LOG.isDebugEnabled())
{
LOG.debug("doStart: Starting new PropertyUserStore. PropertiesFile: " + _config + " refreshInterval: " + _refreshInterval);
}
_propertyUserStore = new PropertyUserStore();
_propertyUserStore.setRefreshInterval(_refreshInterval);
_propertyUserStore.setConfig(_config);

View File

@ -137,7 +137,7 @@ public class JDBCLoginService extends MappedLoginService
|| _password == null
|| _cacheTime < 0)
{
if (LOG.isDebugEnabled()) LOG.debug("UserRealm " + getName() + " has not been properly configured");
LOG.warn("UserRealm " + getName() + " has not been properly configured");
}
_cacheTime *= 1000;
_lastHashPurge = 0;

View File

@ -100,7 +100,7 @@ public class SpnegoLoginService extends AbstractLifeCycle implements LoginServic
_targetName = properties.getProperty("targetName");
LOG.debug("\n\nTarget Name\n\n" + _targetName);
LOG.debug("Target Name {}", _targetName);
super.doStart();
}

View File

@ -117,7 +117,8 @@ public class DigestAuthenticator extends LoginAuthenticator
boolean stale = false;
if (credentials != null)
{
if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials);
if (LOG.isDebugEnabled())
LOG.debug("Credentials: " + credentials);
QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
final Digest digest = new Digest(request.getMethod());
String last = null;

View File

@ -634,7 +634,7 @@ public abstract class AbstractConnector extends HttpBuffers implements Connector
public void setForwarded(boolean check)
{
if (check)
LOG.debug(this + " is forwarded");
LOG.debug("{} is forwarded",this);
_forwarded = check;
}
@ -1001,7 +1001,8 @@ public abstract class AbstractConnector extends HttpBuffers implements Connector
if (on && _statsStartedAt.get() != -1)
return;
LOG.debug("Statistics on = " + on + " for " + this);
if (LOG.isDebugEnabled())
LOG.debug("Statistics on = " + on + " for " + this);
statsReset();
_statsStartedAt.set(on?System.currentTimeMillis():-1);

View File

@ -7,7 +7,6 @@ import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.nio.ChannelEndPoint;
import org.eclipse.jetty.io.nio.SelectChannelEndPoint;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -133,18 +132,22 @@ public class AsyncHttpConnection extends HttpConnection
if (_generator.isCommitted() && !_generator.isComplete() && _endp.isOpen() && !_endp.isOutputShutdown())
((AsyncEndPoint)_endp).scheduleWrite(); // TODO. This should not be required
if (!some_progress)
if (some_progress)
{
_total_no_progress++;
_total_no_progress=0;
}
else
{
int totalNoProgress=++_total_no_progress;
if (NO_PROGRESS_INFO>0 && _total_no_progress%NO_PROGRESS_INFO==0 && (NO_PROGRESS_CLOSE<=0 || _total_no_progress< NO_PROGRESS_CLOSE))
if (NO_PROGRESS_INFO>0 && totalNoProgress==NO_PROGRESS_INFO && (NO_PROGRESS_CLOSE<=0 || totalNoProgress<NO_PROGRESS_CLOSE))
{
LOG.info("EndPoint making no progress: "+_total_no_progress+" "+_endp);
LOG.info("EndPoint making no progress: {} {}", totalNoProgress, _endp);
}
if (NO_PROGRESS_CLOSE>0 && _total_no_progress==NO_PROGRESS_CLOSE)
if (NO_PROGRESS_CLOSE>0 && totalNoProgress==NO_PROGRESS_CLOSE)
{
LOG.warn("Closing EndPoint making no progress: "+_total_no_progress+" "+_endp);
LOG.warn("Closing EndPoint making no progress: {} {}", totalNoProgress, _endp);
if (_endp instanceof SelectChannelEndPoint)
{
System.err.println(((SelectChannelEndPoint)_endp).getSelectManager().dump());

View File

@ -968,7 +968,8 @@ public abstract class HttpConnection extends AbstractConnection
@Override
public void startResponse(Buffer version, int status, Buffer reason)
{
LOG.debug("Bad request!: "+version+" "+status+" "+reason);
if (LOG.isDebugEnabled())
LOG.debug("Bad request!: "+version+" "+status+" "+reason);
}
}

View File

@ -825,7 +825,8 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server.
@Override
public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
LOG.debug("scope {} @ {}",baseRequest.getContextPath() + "|" + baseRequest.getServletPath() + "|" + baseRequest.getPathInfo(),this);
if (LOG.isDebugEnabled())
LOG.debug("scope {}|{}|{} @ {}",baseRequest.getContextPath(),baseRequest.getServletPath(),baseRequest.getPathInfo(),this);
Context old_context = null;
String old_context_path = null;
@ -897,7 +898,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Server.
}
if (LOG.isDebugEnabled())
LOG.debug("context={} @ {}",baseRequest.getContextPath() + "|" + baseRequest.getServletPath() + "|" + baseRequest.getPathInfo(),this);
LOG.debug("context={}|{}|{} @ {}",baseRequest.getContextPath(),baseRequest.getServletPath(), baseRequest.getPathInfo(),this);
// start manual inline of nextScope(target,baseRequest,request,response);
if (never())

View File

@ -245,9 +245,9 @@ public class SelectChannelConnector extends AbstractNIOConnector
_manager.setMaxIdleTime(getMaxIdleTime());
_manager.setLowResourcesConnections(getLowResourcesConnections());
_manager.setLowResourcesMaxIdleTime(getLowResourcesMaxIdleTime());
_manager.start();
super.doStart();
_manager.start();
}
/* ------------------------------------------------------------ */

View File

@ -30,7 +30,7 @@ import org.eclipse.jetty.util.log.Logger;
@SuppressWarnings("deprecation")
public abstract class AbstractSession implements AbstractSessionManager.SessionIf
{
final static Logger __log = SessionHandler.__log;
final static Logger LOG = SessionHandler.LOG;
private final AbstractSessionManager _manager;
private final String _clusterId; // ID unique within cluster
@ -63,7 +63,8 @@ public abstract class AbstractSession implements AbstractSessionManager.SessionI
_lastAccessed=_created;
_requests=1;
_maxIdleMs=_manager._dftMaxIdleSecs>0?_manager._dftMaxIdleSecs*1000:-1;
__log.debug("new session & id "+_nodeId+" "+_clusterId);
if (LOG.isDebugEnabled())
LOG.debug("new session & id "+_nodeId+" "+_clusterId);
}
/* ------------------------------------------------------------- */
@ -76,7 +77,8 @@ public abstract class AbstractSession implements AbstractSessionManager.SessionI
_accessed=accessed;
_lastAccessed=accessed;
_requests=1;
__log.debug("new session "+_nodeId+" "+_clusterId);
if (LOG.isDebugEnabled())
LOG.debug("new session "+_nodeId+" "+_clusterId);
}
/* ------------------------------------------------------------- */
@ -300,7 +302,7 @@ public abstract class AbstractSession implements AbstractSessionManager.SessionI
{
try
{
__log.debug("invalidate ",_clusterId);
LOG.debug("invalidate {}",_clusterId);
if (isValid())
clearAttributes();
}

View File

@ -15,27 +15,19 @@ package org.eclipse.jetty.server.session;
import static java.lang.Math.round;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.servlet.ServletRequest;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
@ -69,7 +61,7 @@ import org.eclipse.jetty.util.statistic.SampleStatistic;
@SuppressWarnings("deprecation")
public abstract class AbstractSessionManager extends AbstractLifeCycle implements SessionManager
{
final static Logger __log = SessionHandler.__log;
final static Logger __log = SessionHandler.LOG;
public Set<SessionTrackingMode> __defaultSessionTrackingModes =
Collections.unmodifiableSet(
@ -300,6 +292,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
return _sessionIdManager;
}
/* ------------------------------------------------------------ */
/**
* @return seconds
@ -364,6 +357,22 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
return _refreshCookieAge;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the secureCookies.
*/
public boolean getSecureCookies()
{
return _secureCookies;
}
/* ------------------------------------------------------------ */
public String getSessionCookie()
{
return _sessionCookie;
}
/* ------------------------------------------------------------ */
public HttpCookie getSessionCookie(HttpSession session, String contextPath, boolean requestIsSecure)
{
@ -382,7 +391,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
sessionPath,
_cookieConfig.getMaxAge(),
_cookieConfig.isHttpOnly(),
_cookieConfig.isSecure());
requestIsSecure&&_cookieConfig.isSecure());
}
else
{
@ -393,7 +402,7 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
sessionPath,
_cookieConfig.getMaxAge(),
_cookieConfig.isHttpOnly(),
_cookieConfig.isSecure(),
requestIsSecure&&_cookieConfig.isSecure(),
_sessionComment,
1);
}
@ -403,6 +412,11 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
return null;
}
public String getSessionDomain()
{
return _sessionDomain;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the sessionHandler.
@ -422,6 +436,8 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
throw new UnsupportedOperationException();
}
/* ------------------------------------------------------------ */
public int getSessions()
{
@ -440,6 +456,15 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
return _sessionIdPathParameterNamePrefix;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the usingCookies.
*/
public boolean isUsingCookies()
{
return _usingCookies;
}
/* ------------------------------------------------------------ */
public boolean isValid(HttpSession session)
{
@ -531,6 +556,8 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
_sessionIdManager=metaManager;
}
/* ------------------------------------------------------------ */
/**
* @param seconds
@ -547,34 +574,14 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
_refreshCookieAge=ageInSeconds;
}
/* ------------------------------------------------------------ */
/**
* Set if the session manager should use SecureCookies.
* A secure cookie will only be sent by a browser on a secure (https) connection to
* avoid the concern of cookies being intercepted on non secure channels.
* For the cookie to be issued as secure, the {@link ServletRequest#isSecure()} method must return true.
* If SSL offload is used, then the {@link AbstractConnector#customize(org.eclipse.jetty.io.EndPoint, Request)}
* method can be used to force the request to be https, or the {@link AbstractConnector#setForwarded(boolean)}
* can be set to true, so that the X-Forwarded-Proto header is respected.
* <p>
* If secure session cookies are used, then a session may not be shared between http and https requests.
*
* @param secureCookies If true, use secure cookies.
*/
public void setSecureCookies(boolean secureCookies)
{
_secureCookies=secureCookies;
}
public void setSessionCookie(String cookieName)
{
_sessionCookie=cookieName;
}
public void setSessionDomain(String domain)
{
_sessionDomain=domain;
}
/* ------------------------------------------------------------ */
/**
@ -586,14 +593,6 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
_sessionHandler=sessionHandler;
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.server.SessionManager#setSessionPath(java.lang.String)
*/
public void setSessionPath(String path)
{
_sessionPath=path;
}
/* ------------------------------------------------------------ */
public void setSessionIdPathParameterName(String param)
@ -601,6 +600,16 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
_sessionIdPathParameterName =(param==null||"none".equals(param))?null:param;
_sessionIdPathParameterNamePrefix =(param==null||"none".equals(param))?null:(";"+ _sessionIdPathParameterName +"=");
}
/* ------------------------------------------------------------ */
/**
* @param usingCookies
* The usingCookies to set.
*/
public void setUsingCookies(boolean usingCookies)
{
_usingCookies=usingCookies;
}
protected abstract void addSession(AbstractSession session);
@ -742,13 +751,6 @@ public abstract class AbstractSessionManager extends AbstractLifeCycle implement
_usingURLs=_sessionTrackingModes.contains(SessionTrackingMode.URL);
}
/* ------------------------------------------------------------ */
@Override
public boolean isUsingCookies()
{
return _usingCookies;
}
/* ------------------------------------------------------------ */
@Override
public boolean isUsingURLs()

View File

@ -47,7 +47,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class HashSessionManager extends AbstractSessionManager
{
final static Logger __log = SessionHandler.__log;
final static Logger __log = SessionHandler.LOG;
protected final ConcurrentMap<String,HashedSession> _sessions=new ConcurrentHashMap<String,HashedSession>();
private static int __id;

View File

@ -162,11 +162,8 @@ public class HashedSession extends AbstractSession
// Access now to prevent race with idling period
access(System.currentTimeMillis());
if (LOG.isDebugEnabled())
{
LOG.debug("Deidling " + super.getId());
}
FileInputStream fis = null;

View File

@ -53,7 +53,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class JDBCSessionIdManager extends AbstractSessionIdManager
{
final static Logger LOG = SessionHandler.__log;
final static Logger LOG = SessionHandler.LOG;
protected final HashSet<String> _sessionIds = new HashSet<String>();
protected Server _server;
@ -108,7 +108,7 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
throws SQLException
{
_dbName = dbMeta.getDatabaseProductName().toLowerCase();
LOG.debug ("Using database "+_dbName);
LOG.debug ("Using database {}",_dbName);
_isLower = dbMeta.storesLowerCaseIdentifiers();
_isUpper = dbMeta.storesUpperCaseIdentifiers();
}
@ -199,6 +199,16 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
}
public void setDatasource (DataSource ds)
{
_datasource = ds;
}
public DataSource getDataSource ()
{
return _datasource;
}
public String getDriverClassName()
{
return _driverClassName;
@ -245,7 +255,8 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
if ((System.currentTimeMillis()%2) == 0)
_scavengeIntervalMs += tenPercent;
if (LOG.isDebugEnabled()) LOG.debug("Scavenging every "+_scavengeIntervalMs+" ms");
if (LOG.isDebugEnabled())
LOG.debug("Scavenging every "+_scavengeIntervalMs+" ms");
if (_timer!=null && (period!=old_period || _task==null))
{
synchronized (this)
@ -424,7 +435,8 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
initializeDatabase();
prepareTables();
super.doStart();
if (LOG.isDebugEnabled()) LOG.debug("Scavenging interval = "+getScavengeInterval()+" sec");
if (LOG.isDebugEnabled())
LOG.debug("Scavenging interval = "+getScavengeInterval()+" sec");
_timer=new Timer("JDBCSessionScavenger", true);
setScavengeInterval(getScavengeInterval());
}
@ -471,6 +483,9 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
private void initializeDatabase ()
throws Exception
{
if (_datasource != null)
return; //already set up
if (_jndiName!=null)
{
InitialContext ic = new InitialContext();
@ -671,7 +686,8 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
List<String> expiredSessionIds = new ArrayList<String>();
try
{
if (LOG.isDebugEnabled()) LOG.debug("Scavenge sweep started at "+System.currentTimeMillis());
if (LOG.isDebugEnabled())
LOG.debug("Scavenge sweep started at "+System.currentTimeMillis());
if (_lastScavengeTime > 0)
{
connection = getConnection();
@ -680,7 +696,8 @@ public class JDBCSessionIdManager extends AbstractSessionIdManager
PreparedStatement statement = connection.prepareStatement(_selectExpiredSessions);
long lowerBound = (_lastScavengeTime - _scavengeIntervalMs);
long upperBound = _lastScavengeTime;
if (LOG.isDebugEnabled()) LOG.debug (" Searching for sessions expired between "+lowerBound + " and "+upperBound);
if (LOG.isDebugEnabled())
LOG.debug (" Searching for sessions expired between "+lowerBound + " and "+upperBound);
statement.setLong(1, lowerBound);
statement.setLong(2, upperBound);

View File

@ -377,7 +377,8 @@ public class JDBCSessionManager extends AbstractSessionManager
@Override
protected void timeout() throws IllegalStateException
{
if (LOG.isDebugEnabled()) LOG.debug("Timing out session id="+getClusterId());
if (LOG.isDebugEnabled())
LOG.debug("Timing out session id="+getClusterId());
super.timeout();
}
}
@ -790,7 +791,8 @@ public class JDBCSessionManager extends AbstractSessionManager
while (itor.hasNext())
{
String sessionId = (String)itor.next();
if (LOG.isDebugEnabled()) LOG.debug("Expiring session id "+sessionId);
if (LOG.isDebugEnabled())
LOG.debug("Expiring session id "+sessionId);
Session session = (Session)_sessions.get(sessionId);
if (session != null)
@ -800,7 +802,8 @@ public class JDBCSessionManager extends AbstractSessionManager
}
else
{
if (LOG.isDebugEnabled()) LOG.debug("Unrecognized session id="+sessionId);
if (LOG.isDebugEnabled())
LOG.debug("Unrecognized session id="+sessionId);
}
}
}

View File

@ -38,7 +38,7 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class SessionHandler extends ScopedHandler
{
final static Logger __log = Log.getLogger("org.eclipse.jetty.server.session");
final static Logger LOG = Log.getLogger("org.eclipse.jetty.server.session");
public final static EnumSet<SessionTrackingMode> DEFAULT_TRACKING = EnumSet.of(SessionTrackingMode.COOKIE,SessionTrackingMode.URL);
@ -181,10 +181,10 @@ public class SessionHandler extends ScopedHandler
}
}
if(__log.isDebugEnabled())
if(LOG.isDebugEnabled())
{
__log.debug("sessionManager="+_sessionManager);
__log.debug("session="+session);
LOG.debug("sessionManager="+_sessionManager);
LOG.debug("session="+session);
}
// start manual inline of nextScope(target,baseRequest,request,response);
@ -271,7 +271,8 @@ public class SessionHandler extends ScopedHandler
{
requested_session_id=cookies[i].getValue();
requested_session_id_from_cookie = true;
if(__log.isDebugEnabled())__log.debug("Got Session ID "+requested_session_id+" from cookie");
if(LOG.isDebugEnabled())
LOG.debug("Got Session ID {} from cookie",requested_session_id);
session=sessionManager.getHttpSession(requested_session_id);
if (session!=null && sessionManager.isValid(session))
@ -304,8 +305,8 @@ public class SessionHandler extends ScopedHandler
requested_session_id = uri.substring(s,i);
requested_session_id_from_cookie = false;
session=sessionManager.getHttpSession(requested_session_id);
if(__log.isDebugEnabled())
__log.debug("Got Session ID "+requested_session_id+" from URL");
if(LOG.isDebugEnabled())
LOG.debug("Got Session ID {} from URL",requested_session_id);
}
}
}

View File

@ -262,7 +262,7 @@ public class SslSelectChannelConnector extends SelectChannelConnector implements
@Deprecated
public void setKeystore(String keystore)
{
_sslContextFactory.setKeyStore(keystore);
_sslContextFactory.setKeyStorePath(keystore);
}
/* ------------------------------------------------------------ */
@ -273,7 +273,7 @@ public class SslSelectChannelConnector extends SelectChannelConnector implements
@Deprecated
public String getKeystore()
{
return _sslContextFactory.getKeyStore();
return _sslContextFactory.getKeyStorePath();
}
/* ------------------------------------------------------------ */

View File

@ -176,7 +176,7 @@ public class SslSocketConnector extends SocketConnector implements SslConnector
@Deprecated
public String getKeystore()
{
return _sslContextFactory.getKeyStore();
return _sslContextFactory.getKeyStorePath();
}
/* ------------------------------------------------------------ */
@ -427,7 +427,7 @@ public class SslSocketConnector extends SocketConnector implements SslConnector
@Deprecated
public void setKeystore(String keystore)
{
_sslContextFactory.setKeyStore(keystore);
_sslContextFactory.setKeyStorePath(keystore);
}
/* ------------------------------------------------------------ */

View File

@ -92,12 +92,12 @@ public class RequestTest
{
//catch the error and check the param map is not null
map = request.getParameterMap();
System.err.println(map);
assertFalse(map == null);
assertTrue(map.isEmpty());
Enumeration names = request.getParameterNames();
assertFalse(names.hasMoreElements());
}
return true;
@ -111,7 +111,32 @@ public class RequestTest
"Content-Type: text/html;charset=utf8\n"+
"\n";
String response = _connector.getResponses(request);
String responses=_connector.getResponses(request);
assertTrue(responses.startsWith("HTTP/1.1 200"));
}
@Test
public void testBadUtf8ParamExtraction() throws Exception
{
_handler._checker = new RequestTester()
{
public boolean check(HttpServletRequest request,HttpServletResponse response)
{
String value=request.getParameter("param");
return value.startsWith("aaa") && value.endsWith("bb");
}
};
//Send a request with query string with illegal hex code to cause
//an exception parsing the params
String request="GET /?param=aaa%E7bbb HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: text/html;charset=utf8\n"+
"\n";
String responses=_connector.getResponses(request);
assertTrue(responses.startsWith("HTTP/1.1 200"));
}

View File

@ -43,7 +43,7 @@ public class ConnectHandlerSSLTest extends AbstractConnectHandlerTest
String keyStorePath = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath();
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keyStorePath);
cf.setKeyStorePath(keyStorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");

View File

@ -112,7 +112,7 @@ public class SSLEngineTest
connector.setPort(0);
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystore);
cf.setKeyStorePath(keystore);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
connector.setRequestBufferSize(512);

View File

@ -45,7 +45,7 @@ public class SSLSelectChannelConnectorLoadTest
String keystorePath = System.getProperty("basedir", ".") + "/src/test/resources/keystore";
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystorePath);
cf.setKeyStorePath(keystorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setTrustStore(keystorePath);

View File

@ -95,7 +95,7 @@ public class SslRenegotiateTest
String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath();
connector.setPort(0);
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystore);
cf.setKeyStorePath(keystore);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setAllowRenegotiate(reneg);

View File

@ -48,7 +48,7 @@ public class SslSelectChannelServerTest extends HttpServerTestBase
SslSelectChannelConnector connector = new SslSelectChannelConnector();
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystorePath);
cf.setKeyStorePath(keystorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setTrustStore(keystorePath);

View File

@ -42,7 +42,7 @@ public class SslSelectChannelTimeoutTest extends ConnectorTimeoutTest
connector.setMaxIdleTime(MAX_IDLE_TIME); //250 msec max idle
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystorePath);
cf.setKeyStorePath(keystorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setTrustStore(keystorePath);

View File

@ -51,7 +51,7 @@ public class SslSocketServerTest extends HttpServerTestBase
SslSocketConnector connector = new SslSocketConnector();
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystorePath);
cf.setKeyStorePath(keystorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setTrustStore(keystorePath);

View File

@ -44,7 +44,7 @@ public class SslSocketTimeoutTest extends ConnectorTimeoutTest
connector.setMaxIdleTime(MAX_IDLE_TIME); //250 msec max idle
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystorePath);
cf.setKeyStorePath(keystorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setTrustStore(keystorePath);

View File

@ -84,7 +84,7 @@ public class SslTruncationAttackTest
String keystorePath = System.getProperty("basedir", ".") + "/src/test/resources/keystore";
SslContextFactory sslContextFactory = connector.getSslContextFactory();
sslContextFactory.setKeyStore(keystorePath);
sslContextFactory.setKeyStorePath(keystorePath);
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
sslContextFactory.setTrustStore(keystorePath);

View File

@ -58,7 +58,7 @@ public class SslUploadTest
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
SslContextFactory cf = connector.getSslContextFactory();
cf.setKeyStore(keystorePath);
cf.setKeyStorePath(keystorePath);
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
cf.setTrustStore(keystorePath);

View File

@ -280,7 +280,8 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
if (h.getServletInstance()==this)
_defaultHolder=h;
if (LOG.isDebugEnabled()) LOG.debug("resource base = "+_resourceBase);
if (LOG.isDebugEnabled())
LOG.debug("resource base = "+_resourceBase);
}
/**

View File

@ -90,7 +90,8 @@ public class Holder<T> extends AbstractLifeCycle implements Dumpable
try
{
_class=Loader.loadClass(Holder.class, _className);
if(LOG.isDebugEnabled())LOG.debug("Holding {}",_class);
if(LOG.isDebugEnabled())
LOG.debug("Holding {}",_class);
}
catch (Exception e)
{

View File

@ -140,7 +140,8 @@ public class Invoker extends HttpServlet
{
// Found a named servlet (from a user's web.xml file) so
// now we add a mapping for it
LOG.debug("Adding servlet mapping for named servlet:"+servlet+":"+URIUtil.addPaths(servlet_path,servlet)+"/*");
if (LOG.isDebugEnabled())
LOG.debug("Adding servlet mapping for named servlet:"+servlet+":"+URIUtil.addPaths(servlet_path,servlet)+"/*");
ServletMapping mapping = new ServletMapping();
mapping.setServletName(servlet);
mapping.setPathSpec(URIUtil.addPaths(servlet_path,servlet)+"/*");
@ -174,7 +175,8 @@ public class Invoker extends HttpServlet
else
{
// Make a holder
LOG.debug("Making new servlet="+servlet+" with path="+path+"/*");
if (LOG.isDebugEnabled())
LOG.debug("Making new servlet="+servlet+" with path="+path+"/*");
holder=_servletHandler.addServletWithMapping(servlet, path+"/*");
if (_parameters!=null)
@ -211,7 +213,7 @@ public class Invoker extends HttpServlet
}
}
if (_verbose)
if (_verbose && LOG.isDebugEnabled())
LOG.debug("Dynamic load '"+servlet+"' at "+path);
}
}

View File

@ -395,7 +395,7 @@ public class ServletHandler extends ScopedHandler
}
if (LOG.isDebugEnabled())
LOG.debug("servlet {} -> {}",baseRequest.getContextPath()+"|"+baseRequest.getServletPath()+"|"+baseRequest.getPathInfo(),servlet_holder);
LOG.debug("servlet {}|{}|{} -> {}",baseRequest.getContextPath(),baseRequest.getServletPath(),baseRequest.getPathInfo(),servlet_holder);
try
{
@ -463,7 +463,7 @@ public class ServletHandler extends ScopedHandler
}
}
LOG.debug("chain=",chain);
LOG.debug("chain={}",chain);
try
{
@ -1239,7 +1239,8 @@ public class ServletHandler extends ScopedHandler
HttpServletResponse response)
throws IOException
{
if(LOG.isDebugEnabled())LOG.debug("Not Found "+request.getRequestURI());
if(LOG.isDebugEnabled())
LOG.debug("Not Found "+request.getRequestURI());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
@ -1399,13 +1400,15 @@ public class ServletHandler extends ScopedHandler
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
if (LOG.isDebugEnabled()) LOG.debug("doFilter " + _filter);
if (LOG.isDebugEnabled())
LOG.debug("doFilter " + _filter);
// pass to next filter
if (_filter < LazyList.size(_chain))
{
FilterHolder holder= (FilterHolder)LazyList.get(_chain, _filter++);
if (LOG.isDebugEnabled()) LOG.debug("call filter " + holder);
if (LOG.isDebugEnabled())
LOG.debug("call filter " + holder);
Filter filter= holder.getFilter();
if (holder.isAsyncSupported() || !_baseRequest.isAsyncSupported())
@ -1431,7 +1434,8 @@ public class ServletHandler extends ScopedHandler
// Call servlet
if (_servletHolder != null)
{
if (LOG.isDebugEnabled()) LOG.debug("call servlet " + _servletHolder);
if (LOG.isDebugEnabled())
LOG.debug("call servlet " + _servletHolder);
_servletHolder.handle(_baseRequest,request, response);
}
else // Not found

View File

@ -32,7 +32,7 @@ import org.eclipse.jetty.util.log.Logger;
/**
* <p>Implementation of the
* <a href="http://dev.w3.org/2006/waf/access-control/">cross-origin resource sharing</a>.</p>
* <a href="http://www.w3.org/TR/cors/">cross-origin resource sharing</a>.</p>
* <p>A typical example is to use this filter to allow cross-domain
* <a href="http://cometd.org">cometd</a> communication using the standard
* long polling transport instead of the JSONP transport (that is less
@ -78,34 +78,35 @@ public class CrossOriginFilter implements Filter
// Request headers
private static final String ORIGIN_HEADER = "Origin";
private static final String ACCESS_CONTROL_REQUEST_METHOD_HEADER = "Access-Control-Request-Method";
private static final String ACCESS_CONTROL_REQUEST_HEADERS_HEADER = "Access-Control-Request-Headers";
public static final String ACCESS_CONTROL_REQUEST_METHOD_HEADER = "Access-Control-Request-Method";
public static final String ACCESS_CONTROL_REQUEST_HEADERS_HEADER = "Access-Control-Request-Headers";
// Response headers
private static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin";
private static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods";
private static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers";
private static final String ACCESS_CONTROL_MAX_AGE_HEADER = "Access-Control-Max-Age";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER = "Access-Control-Allow-Credentials";
public static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin";
public static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods";
public static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers";
public static final String ACCESS_CONTROL_MAX_AGE_HEADER = "Access-Control-Max-Age";
public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER = "Access-Control-Allow-Credentials";
// Implementation constants
private static final String ALLOWED_ORIGINS_PARAM = "allowedOrigins";
private static final String ALLOWED_METHODS_PARAM = "allowedMethods";
private static final String ALLOWED_HEADERS_PARAM = "allowedHeaders";
private static final String PREFLIGHT_MAX_AGE_PARAM = "preflightMaxAge";
private static final String ALLOWED_CREDENTIALS_PARAM = "allowCredentials";
public static final String ALLOWED_ORIGINS_PARAM = "allowedOrigins";
public static final String ALLOWED_METHODS_PARAM = "allowedMethods";
public static final String ALLOWED_HEADERS_PARAM = "allowedHeaders";
public static final String PREFLIGHT_MAX_AGE_PARAM = "preflightMaxAge";
public static final String ALLOW_CREDENTIALS_PARAM = "allowCredentials";
private static final String ANY_ORIGIN = "*";
private static final List<String> SIMPLE_HTTP_METHODS = Arrays.asList("GET", "POST", "HEAD");
private boolean anyOriginAllowed = false;
private boolean anyOriginAllowed;
private List<String> allowedOrigins = new ArrayList<String>();
private List<String> allowedMethods = new ArrayList<String>();
private List<String> allowedHeaders = new ArrayList<String>();
private int preflightMaxAge = 0;
private boolean allowCredentials = true;
private boolean allowCredentials;
public void init(FilterConfig config) throws ServletException
{
String allowedOriginsConfig = config.getInitParameter(ALLOWED_ORIGINS_PARAM);
if (allowedOriginsConfig == null) allowedOriginsConfig = "*";
if (allowedOriginsConfig == null)
allowedOriginsConfig = "*";
String[] allowedOrigins = allowedOriginsConfig.split(",");
for (String allowedOrigin : allowedOrigins)
{
@ -126,15 +127,18 @@ public class CrossOriginFilter implements Filter
}
String allowedMethodsConfig = config.getInitParameter(ALLOWED_METHODS_PARAM);
if (allowedMethodsConfig == null) allowedMethodsConfig = "GET,POST";
if (allowedMethodsConfig == null)
allowedMethodsConfig = "GET,POST,HEAD";
allowedMethods.addAll(Arrays.asList(allowedMethodsConfig.split(",")));
String allowedHeadersConfig = config.getInitParameter(ALLOWED_HEADERS_PARAM);
if (allowedHeadersConfig == null) allowedHeadersConfig = "X-Requested-With,Content-Type,Accept,Origin";
if (allowedHeadersConfig == null)
allowedHeadersConfig = "X-Requested-With,Content-Type,Accept,Origin";
allowedHeaders.addAll(Arrays.asList(allowedHeadersConfig.split(",")));
String preflightMaxAgeConfig = config.getInitParameter(PREFLIGHT_MAX_AGE_PARAM);
if (preflightMaxAgeConfig == null) preflightMaxAgeConfig = "1800"; // Default is 30 minutes
if (preflightMaxAgeConfig == null)
preflightMaxAgeConfig = "1800"; // Default is 30 minutes
try
{
preflightMaxAge = Integer.parseInt(preflightMaxAgeConfig);
@ -144,16 +148,20 @@ public class CrossOriginFilter implements Filter
LOG.info("Cross-origin filter, could not parse '{}' parameter as integer: {}", PREFLIGHT_MAX_AGE_PARAM, preflightMaxAgeConfig);
}
String allowedCredentialsConfig = config.getInitParameter(ALLOWED_CREDENTIALS_PARAM);
if (allowedCredentialsConfig == null) allowedCredentialsConfig = "false";
String allowedCredentialsConfig = config.getInitParameter(ALLOW_CREDENTIALS_PARAM);
if (allowedCredentialsConfig == null)
allowedCredentialsConfig = "true";
allowCredentials = Boolean.parseBoolean(allowedCredentialsConfig);
LOG.debug("Cross-origin filter configuration: " +
ALLOWED_ORIGINS_PARAM + " = " + allowedOriginsConfig + ", " +
ALLOWED_METHODS_PARAM + " = " + allowedMethodsConfig + ", " +
ALLOWED_HEADERS_PARAM + " = " + allowedHeadersConfig + ", " +
PREFLIGHT_MAX_AGE_PARAM + " = " + preflightMaxAgeConfig + ", " +
ALLOWED_CREDENTIALS_PARAM + " = " + allowedCredentialsConfig);
if (LOG.isDebugEnabled())
{
LOG.debug("Cross-origin filter configuration: " +
ALLOWED_ORIGINS_PARAM + " = " + allowedOriginsConfig + ", " +
ALLOWED_METHODS_PARAM + " = " + allowedMethodsConfig + ", " +
ALLOWED_HEADERS_PARAM + " = " + allowedHeadersConfig + ", " +
PREFLIGHT_MAX_AGE_PARAM + " = " + preflightMaxAgeConfig + ", " +
ALLOW_CREDENTIALS_PARAM + " = " + allowedCredentialsConfig);
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
@ -174,11 +182,16 @@ public class CrossOriginFilter implements Filter
LOG.debug("Cross-origin request to {} is a simple cross-origin request", request.getRequestURI());
handleSimpleResponse(request, response, origin);
}
else
else if (isPreflightRequest(request))
{
LOG.debug("Cross-origin request to {} is a preflight cross-origin request", request.getRequestURI());
handlePreflightResponse(request, response, origin);
}
else
{
LOG.debug("Cross-origin request to {} is a non-simple cross-origin request", request.getRequestURI());
handleSimpleResponse(request, response, origin);
}
}
else
{
@ -201,14 +214,33 @@ public class CrossOriginFilter implements Filter
return true;
}
private boolean originMatches(String origin)
private boolean originMatches(String originList)
{
if (anyOriginAllowed) return true;
for (String allowedOrigin : allowedOrigins)
if (anyOriginAllowed)
return true;
if (originList.trim().length() == 0)
return false;
String[] origins = originList.split(" ");
for (String origin : origins)
{
if (allowedOrigin.equals(origin)) return true;
if (origin.trim().length() == 0)
continue;
boolean allowed = false;
for (String allowedOrigin : allowedOrigins)
{
if (allowedOrigin.equals(origin))
{
allowed = true;
break;
}
}
if (!allowed)
return false;
}
return false;
return true;
}
private boolean isSimpleRequest(HttpServletRequest request)
@ -216,8 +248,8 @@ public class CrossOriginFilter implements Filter
String method = request.getMethod();
if (SIMPLE_HTTP_METHODS.contains(method))
{
// TODO: implement better section 6.1
// Section 6.1 says that for a request to be simple, custom request headers must be simple.
// TODO: implement better detection of simple headers
// The specification says that for a request to be simple, custom request headers must be simple.
// Here for simplicity I just check if there is a Access-Control-Request-Method header,
// which is required for preflight requests
return request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER) == null;
@ -225,30 +257,37 @@ public class CrossOriginFilter implements Filter
return false;
}
private boolean isPreflightRequest(HttpServletRequest request)
{
String method = request.getMethod();
if (!"OPTIONS".equalsIgnoreCase(method))
return false;
if (request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER) == null)
return false;
return true;
}
private void handleSimpleResponse(HttpServletRequest request, HttpServletResponse response, String origin)
{
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, origin);
if (allowCredentials) response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
if (allowCredentials)
response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
}
private void handlePreflightResponse(HttpServletRequest request, HttpServletResponse response, String origin)
{
// Implementation of section 5.2
// 5.2.3 and 5.2.5
boolean methodAllowed = isMethodAllowed(request);
if (!methodAllowed) return;
// 5.2.4 and 5.2.6
if (!methodAllowed)
return;
boolean headersAllowed = areHeadersAllowed(request);
if (!headersAllowed) return;
// 5.2.7
if (!headersAllowed)
return;
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, origin);
if (allowCredentials) response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
// 5.2.8
if (preflightMaxAge > 0) response.setHeader(ACCESS_CONTROL_MAX_AGE_HEADER, String.valueOf(preflightMaxAge));
// 5.2.9
if (allowCredentials)
response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
if (preflightMaxAge > 0)
response.setHeader(ACCESS_CONTROL_MAX_AGE_HEADER, String.valueOf(preflightMaxAge));
response.setHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER, commify(allowedMethods));
// 5.2.10
response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_HEADER, commify(allowedHeaders));
}
@ -258,9 +297,7 @@ public class CrossOriginFilter implements Filter
LOG.debug("{} is {}", ACCESS_CONTROL_REQUEST_METHOD_HEADER, accessControlRequestMethod);
boolean result = false;
if (accessControlRequestMethod != null)
{
result = allowedMethods.contains(accessControlRequestMethod);
}
LOG.debug("Method {} is" + (result ? "" : " not") + " among allowed methods {}", accessControlRequestMethod, allowedMethods);
return result;
}

View File

@ -0,0 +1,346 @@
package org.eclipse.jetty.servlets;
import java.io.IOException;
import java.util.EnumSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.testing.ServletTester;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CrossOriginFilterTest
{
private ServletTester tester;
@Before
public void init() throws Exception
{
tester = new ServletTester();
tester.start();
}
@After
public void destroy() throws Exception
{
if (tester != null)
tester.stop();
}
@Test
public void testRequestWithNoOriginArrivesToApplication() throws Exception
{
tester.getContext().addFilter(CrossOriginFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
final CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithNonMatchingOrigin() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
String origin = "http://localhost";
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, origin);
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String otherOrigin = origin.replace("localhost", "127.0.0.1");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: " + otherOrigin + "\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithMatchingOrigin() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
String origin = "http://localhost";
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, origin);
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: " + origin + "\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithMatchingMultipleOrigins() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
String origin = "http://localhost";
String otherOrigin = origin.replace("localhost", "127.0.0.1");
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, origin + "," + otherOrigin);
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
// Use 2 spaces as separator to test that the implementation does not fail
"Origin: " + otherOrigin + " " + " " + origin + "\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testSimpleRequestWithoutCredentials() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "false");
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testNonSimpleRequestWithoutPreflight() throws Exception
{
// We cannot know if an actual request has performed the preflight before:
// we'll trust browsers to do it right, so responses to actual requests
// will contain the CORS response headers.
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"PUT / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testOptionsRequestButNotPreflight() throws Exception
{
// We cannot know if an actual request has performed the preflight before:
// we'll trust browsers to do it right, so responses to actual requests
// will contain the CORS response headers.
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"OPTIONS / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
@Test
public void testPUTRequestWithPreflight() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "PUT");
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
// Preflight request
String request = "" +
"OPTIONS / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER + ": PUT\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_MAX_AGE_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_METHODS_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_HEADERS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
// Preflight request was ok, now make the actual request
request = "" +
"PUT / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
}
@Test
public void testDELETERequestWithPreflightAndAllowedCustomHeaders() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,HEAD,POST,PUT,DELETE");
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,X-Custom");
tester.getContext().addFilter(filterHolder, "/*",EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
// Preflight request
String request = "" +
"OPTIONS / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER + ": DELETE\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_HEADERS_HEADER + ": origin,x-custom,x-requested-with\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_MAX_AGE_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_METHODS_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_HEADERS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
// Preflight request was ok, now make the actual request
request = "" +
"DELETE / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"X-Custom: value\r\n" +
"X-Requested-With: local\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertTrue(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
}
@Test
public void testDELETERequestWithPreflightAndNotAllowedCustomHeaders() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,HEAD,POST,PUT,DELETE");
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
// Preflight request
String request = "" +
"OPTIONS / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER + ": DELETE\r\n" +
CrossOriginFilter.ACCESS_CONTROL_REQUEST_HEADERS_HEADER + ": origin,x-custom,x-requested-with\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
// The preflight request failed because header X-Custom is not allowed, actual request not issued
}
@Test
public void testCrossOriginFilterDisabledForWebSocketUpgrade() throws Exception
{
FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
tester.getContext().addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
CountDownLatch latch = new CountDownLatch(1);
tester.getContext().addServlet(new ServletHolder(new ResourceServlet(latch)), "/*");
String request = "" +
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Connection: Upgrade\r\n" +
"Upgrade: WebSocket\r\n" +
"Origin: http://localhost\r\n" +
"\r\n";
String response = tester.getResponses(request);
Assert.assertTrue(response.contains("HTTP/1.1 200"));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER));
Assert.assertFalse(response.contains(CrossOriginFilter.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER));
Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
}
public static class ResourceServlet extends HttpServlet
{
private final CountDownLatch latch;
public ResourceServlet(CountDownLatch latch)
{
this.latch = latch;
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
latch.countDown();
}
}
}

View File

@ -20,6 +20,9 @@ import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.jetty.util.Utf8Appendable.NotUtf8Exception;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/* ------------------------------------------------------------ */
/** Handles coding of MIME "x-www-form-urlencoded".
@ -42,7 +45,7 @@ import java.util.Map;
*/
public class UrlEncoded extends MultiMap
{
// private static final Logger LOG = Log.getLogger(UrlEncoded.class);
private static final Logger LOG = Log.getLogger(UrlEncoded.class);
public static final String ENCODING = System.getProperty("org.eclipse.jetty.util.UrlEncoding.charset",StringUtil.__UTF8);
@ -273,44 +276,53 @@ public class UrlEncoded extends MultiMap
for (int i=offset;i<end;i++)
{
byte b=raw[i];
switch ((char)(0xff&b))
try
{
case '&':
value = buffer.length()==0?"":buffer.toString();
buffer.reset();
if (key != null)
{
map.add(key,value);
}
else if (value!=null&&value.length()>0)
{
map.add(value,"");
}
key = null;
value=null;
break;
switch ((char)(0xff&b))
{
case '&':
value = buffer.length()==0?"":buffer.toString();
buffer.reset();
if (key != null)
{
map.add(key,value);
}
else if (value!=null&&value.length()>0)
{
map.add(value,"");
}
key = null;
value=null;
break;
case '=':
if (key!=null)
{
case '=':
if (key!=null)
{
buffer.append(b);
break;
}
key = buffer.toString();
buffer.reset();
break;
case '+':
buffer.append((byte)' ');
break;
case '%':
if (i+2<end)
buffer.append((byte)((TypeUtil.convertHexDigit(raw[++i])<<4) + TypeUtil.convertHexDigit(raw[++i])));
break;
default:
buffer.append(b);
break;
}
key = buffer.toString();
buffer.reset();
break;
case '+':
buffer.append((byte)' ');
break;
case '%':
if (i+2<end)
buffer.append((byte)((TypeUtil.convertHexDigit(raw[++i])<<4) + TypeUtil.convertHexDigit(raw[++i])));
break;
default:
buffer.append(b);
break;
}
}
catch(NotUtf8Exception e)
{
LOG.warn(e.toString());
LOG.debug(e);
}
}

View File

@ -159,6 +159,7 @@ public abstract class Utf8Appendable
}
else if (_state == UTF8_REJECT)
{
_codep=0;
_state = UTF8_ACCEPT;
_appendable.append(REPLACEMENT);
throw new NotUtf8Exception();

View File

@ -188,7 +188,7 @@ public abstract class AbstractLifeCycle implements LifeCycle
private void setStopped()
{
_state = __STOPPED;
LOG.debug(STOPPED+" {}",this);
LOG.debug("{} {}",STOPPED,this);
for (Listener listener : _listeners)
listener.lifeCycleStopped(this);
}

View File

@ -144,7 +144,7 @@ public class AggregateLifeCycle extends AbstractLifeCycle implements Destroyable
t=(T)o;
}
}
if (count>1)
if (count>1 && LOG.isDebugEnabled())
LOG.debug("getBean({}) 1 of {}",clazz.getName(),count);
return t;

View File

@ -56,40 +56,39 @@ public class Log
});
}
private static Logger __log;
private static Logger LOG;
private static boolean __initialized;
public static boolean initialized()
{
if (__log != null)
if (LOG != null)
return true;
synchronized (Log.class)
{
if (__initialized)
return __log != null;
return LOG != null;
__initialized = true;
}
try
{
Class<?> log_class = Loader.loadClass(Log.class, __logClass);
if (__log == null || !__log.getClass().equals(log_class))
if (LOG == null || !LOG.getClass().equals(log_class))
{
__log = (Logger)log_class.newInstance();
__log.debug("Logging to {} via {}", __log, log_class.getName());
LOG = (Logger)log_class.newInstance();
LOG.debug("Logging to {} via {}", LOG, log_class.getName());
}
}
catch(NoClassDefFoundError e)
{
initStandardLogging(e);
}
catch(Exception e)
catch(Throwable e)
{
if (e instanceof ThreadDeath)
throw (ThreadDeath)e;
initStandardLogging(e);
}
return __log != null;
return LOG != null;
}
private static void initStandardLogging(Throwable e)
@ -97,17 +96,17 @@ public class Log
Class<?> log_class;
if(e != null && __ignored)
e.printStackTrace();
if (__log == null)
if (LOG == null)
{
log_class = StdErrLog.class;
__log = new StdErrLog();
__log.debug("Logging to {} via {}", __log, log_class.getName());
LOG = new StdErrLog();
LOG.debug("Logging to {} via {}", LOG, log_class.getName());
}
}
public static void setLog(Logger log)
{
Log.__log = log;
Log.LOG = log;
}
/**
@ -117,7 +116,7 @@ public class Log
public static Logger getLog()
{
initialized();
return __log;
return LOG;
}
/**
@ -126,7 +125,7 @@ public class Log
*/
public static Logger getRootLogger() {
initialized();
return __log;
return LOG;
}
static boolean isIgnored()
@ -180,7 +179,7 @@ public class Log
{
if (!isDebugEnabled())
return;
__log.debug(EXCEPTION, th);
LOG.debug(EXCEPTION, th);
}
/**
@ -191,7 +190,7 @@ public class Log
{
if (!initialized())
return;
__log.debug(msg);
LOG.debug(msg);
}
/**
@ -202,7 +201,7 @@ public class Log
{
if (!initialized())
return;
__log.debug(msg, arg);
LOG.debug(msg, arg);
}
/**
@ -213,7 +212,7 @@ public class Log
{
if (!initialized())
return;
__log.debug(msg, arg0, arg1);
LOG.debug(msg, arg0, arg1);
}
/**
@ -229,7 +228,7 @@ public class Log
{
if (!initialized())
return;
__log.ignore(thrown);
LOG.ignore(thrown);
}
/**
@ -240,7 +239,7 @@ public class Log
{
if (!initialized())
return;
__log.info(msg);
LOG.info(msg);
}
/**
@ -251,7 +250,7 @@ public class Log
{
if (!initialized())
return;
__log.info(msg, arg);
LOG.info(msg, arg);
}
/**
@ -262,7 +261,7 @@ public class Log
{
if (!initialized())
return;
__log.info(msg, arg0, arg1);
LOG.info(msg, arg0, arg1);
}
/**
@ -273,7 +272,7 @@ public class Log
{
if (!initialized())
return false;
return __log.isDebugEnabled();
return LOG.isDebugEnabled();
}
/**
@ -284,7 +283,7 @@ public class Log
{
if (!initialized())
return;
__log.warn(msg);
LOG.warn(msg);
}
/**
@ -295,7 +294,7 @@ public class Log
{
if (!initialized())
return;
__log.warn(msg, arg);
LOG.warn(msg, arg);
}
/**
@ -306,7 +305,7 @@ public class Log
{
if (!initialized())
return;
__log.warn(msg, arg0, arg1);
LOG.warn(msg, arg0, arg1);
}
/**
@ -317,7 +316,7 @@ public class Log
{
if (!initialized())
return;
__log.warn(msg, th);
LOG.warn(msg, th);
}
/**
@ -328,7 +327,7 @@ public class Log
{
if (!initialized())
return;
__log.warn(EXCEPTION, th);
LOG.warn(EXCEPTION, th);
}
/**
@ -353,6 +352,6 @@ public class Log
if (!initialized())
return null;
return name == null ? __log : __log.getLogger(name);
return name == null ? LOG : LOG.getLogger(name);
}
}

View File

@ -141,27 +141,44 @@ public class StdErrLog implements Logger
}
else
{
if ("ALL".equalsIgnoreCase(levelStr.trim()))
int level = getLevelId(levelStr);
if (level != (-1))
{
return LEVEL_ALL;
}
else if ("DEBUG".equalsIgnoreCase(levelStr.trim()))
{
return LEVEL_DEBUG;
}
else if ("INFO".equalsIgnoreCase(levelStr.trim()))
{
return LEVEL_INFO;
}
else if ("WARN".equalsIgnoreCase(levelStr.trim()))
{
return LEVEL_WARN;
return level;
}
}
}
// Default Logging Level
return LEVEL_INFO;
return getLevelId(props.getProperty("log.LEVEL", "INFO"));
}
protected static int getLevelId(String levelName)
{
if (levelName == null)
{
return -1;
}
String levelStr = levelName.trim();
if ("ALL".equalsIgnoreCase(levelStr))
{
return LEVEL_ALL;
}
else if ("DEBUG".equalsIgnoreCase(levelStr))
{
return LEVEL_DEBUG;
}
else if ("INFO".equalsIgnoreCase(levelStr))
{
return LEVEL_INFO;
}
else if ("WARN".equalsIgnoreCase(levelStr))
{
return LEVEL_WARN;
}
System.err.println("Unknown StdErrLog level [" + levelStr + "], expecting only [ALL, DEBUG, INFO, WARN] as values.");
return -1;
}
/**
@ -541,7 +558,7 @@ public class StdErrLog implements Logger
StdErrLog sel = new StdErrLog(fullname);
// Preserve configuration for new loggers configuration
sel.setPrintLongNames(_printLongNames);
sel.setLevel(_level);
// Let Level come from configured Properties instead - sel.setLevel(_level);
sel.setSource(_source);
logger = __loggers.putIfAbsent(fullname,sel);
if (logger == null)

View File

@ -130,7 +130,8 @@ public class JarResource extends URLResource
if (!exists())
return;
if(LOG.isDebugEnabled())LOG.debug("Extract "+this+" to "+directory);
if(LOG.isDebugEnabled())
LOG.debug("Extract "+this+" to "+directory);
String urlString = this.getURL().toExternalForm().trim();
int endOfJarUrl = urlString.indexOf("!/");
@ -143,7 +144,8 @@ public class JarResource extends URLResource
String subEntryName = (endOfJarUrl+2 < urlString.length() ? urlString.substring(endOfJarUrl + 2) : null);
boolean subEntryIsDir = (subEntryName != null && subEntryName.endsWith("/")?true:false);
if (LOG.isDebugEnabled()) LOG.debug("Extracting entry = "+subEntryName+" from jar "+jarFileURL);
if (LOG.isDebugEnabled())
LOG.debug("Extracting entry = "+subEntryName+" from jar "+jarFileURL);
InputStream is = jarFileURL.openConnection().getInputStream();
JarInputStream jin = new JarInputStream(is);
@ -194,7 +196,8 @@ public class JarResource extends URLResource
if (!shouldExtract)
{
if (LOG.isDebugEnabled()) LOG.debug("Skipping entry: "+entryName);
if (LOG.isDebugEnabled())
LOG.debug("Skipping entry: "+entryName);
continue;
}
@ -202,7 +205,8 @@ public class JarResource extends URLResource
dotCheck = URIUtil.canonicalPath(dotCheck);
if (dotCheck == null)
{
if (LOG.isDebugEnabled()) LOG.debug("Invalid entry: "+entryName);
if (LOG.isDebugEnabled())
LOG.debug("Invalid entry: "+entryName);
continue;
}

View File

@ -41,62 +41,78 @@ public class ExecutorThreadPool extends AbstractLifeCycle implements ThreadPool,
/* ------------------------------------------------------------ */
public ExecutorThreadPool(ExecutorService executor)
{
_executor=executor;
_executor = executor;
}
/* ------------------------------------------------------------ */
/** constructor.
/**
* Wraps an {@link ThreadPoolExecutor}.
* Core size is 32, max pool size is 256, pool thread timeout after 60 seconds and
* Max pool size is 256, pool thread timeout after 60 seconds and
* an unbounded {@link LinkedBlockingQueue} is used for the job queue;
*/
public ExecutorThreadPool()
{
this(new ThreadPoolExecutor(32,256,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>()));
// Using an unbounded queue makes the maxThreads parameter useless
// Refer to ThreadPoolExecutor javadocs for details
this(new ThreadPoolExecutor(256, 256, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()));
}
/* ------------------------------------------------------------ */
/** constructor.
/**
* Wraps an {@link ThreadPoolExecutor}.
* Core size is 32, max pool size is 256, pool thread timeout after 60 seconds
* @param queueSize if -1, an unbounded {@link LinkedBlockingQueue} is used, if 0 then a
* {@link SynchronousQueue} is used, other a {@link ArrayBlockingQueue} of the given size is used.
* Max pool size is 256, pool thread timeout after 60 seconds, and core pool size is 32 when queueSize >= 0.
* @param queueSize can be -1 for using an unbounded {@link LinkedBlockingQueue}, 0 for using a
* {@link SynchronousQueue}, greater than 0 for using a {@link ArrayBlockingQueue} of the given size.
*/
public ExecutorThreadPool(int queueSize)
{
this(new ThreadPoolExecutor(32,256,60,TimeUnit.SECONDS,
queueSize<0?new LinkedBlockingQueue<Runnable>()
: (queueSize==0?new SynchronousQueue<Runnable>()
:new ArrayBlockingQueue<Runnable>(queueSize))));
this(queueSize < 0 ? new ThreadPoolExecutor(256, 256, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()) :
queueSize == 0 ? new ThreadPoolExecutor(32, 256, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()) :
new ThreadPoolExecutor(32, 256, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize)));
}
/* ------------------------------------------------------------ */
/** constructor.
/**
* Wraps an {@link ThreadPoolExecutor} using
* an unbounded {@link LinkedBlockingQueue} is used for the jobs queue;
* @param corePoolSize must be equal to maximumPoolSize
* @param maximumPoolSize the maximum number of threads to allow in the pool
* @param keepAliveTime the max time a thread can remain idle, in milliseconds
*/
public ExecutorThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime)
{
this(new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));
this(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS);
}
/* ------------------------------------------------------------ */
/** constructor.
/**
* Wraps an {@link ThreadPoolExecutor} using
* an unbounded {@link LinkedBlockingQueue} is used for the jobs queue;
* an unbounded {@link LinkedBlockingQueue} is used for the jobs queue.
* @param corePoolSize must be equal to maximumPoolSize
* @param maximumPoolSize the maximum number of threads to allow in the pool
* @param keepAliveTime the max time a thread can remain idle
* @param unit the unit for the keepAliveTime
*/
public ExecutorThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit)
{
this(new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,new LinkedBlockingQueue<Runnable>()));
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>());
}
/* ------------------------------------------------------------ */
/**
* Wraps an {@link ThreadPoolExecutor}
* @param corePoolSize the number of threads to keep in the pool, even if they are idle
* @param maximumPoolSize the maximum number of threads to allow in the pool
* @param keepAliveTime the max time a thread can remain idle
* @param unit the unit for the keepAliveTime
* @param workQueue the queue to use for holding tasks before they are executed
*/
public ExecutorThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
{
this(new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue));
this(new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue));
}
/* ------------------------------------------------------------ */
public boolean dispatch(Runnable job)
{
@ -118,7 +134,7 @@ public class ExecutorThreadPool extends AbstractLifeCycle implements ThreadPool,
if (_executor instanceof ThreadPoolExecutor)
{
final ThreadPoolExecutor tpe = (ThreadPoolExecutor)_executor;
return tpe.getPoolSize() -tpe.getActiveCount();
return tpe.getPoolSize() - tpe.getActiveCount();
}
return -1;
}
@ -140,7 +156,9 @@ public class ExecutorThreadPool extends AbstractLifeCycle implements ThreadPool,
if (_executor instanceof ThreadPoolExecutor)
{
final ThreadPoolExecutor tpe = (ThreadPoolExecutor)_executor;
return tpe.getTaskCount()>=(tpe.getMaximumPoolSize());
// getActiveCount() locks the thread pool, so execute it last
return tpe.getPoolSize() == tpe.getMaximumPoolSize() &&
tpe.getQueue().size() >= tpe.getPoolSize() - tpe.getActiveCount();
}
return false;
}
@ -148,14 +166,7 @@ public class ExecutorThreadPool extends AbstractLifeCycle implements ThreadPool,
/* ------------------------------------------------------------ */
public void join() throws InterruptedException
{
_executor.awaitTermination(Long.MAX_VALUE,TimeUnit.MILLISECONDS);
}
/* ------------------------------------------------------------ */
@Override
protected void doStart() throws Exception
{
super.doStart();
_executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
/* ------------------------------------------------------------ */
@ -165,5 +176,4 @@ public class ExecutorThreadPool extends AbstractLifeCycle implements ThreadPool,
super.doStop();
_executor.shutdownNow();
}
}

View File

@ -122,7 +122,7 @@ public class ShutdownThread extends Thread
try
{
lifeCycle.stop();
LOG.debug("Stopped " + lifeCycle);
LOG.debug("Stopped {}",lifeCycle);
}
catch (Exception ex)
{

View File

@ -78,6 +78,19 @@ public class StdErrLogTest
Assert.assertEquals("Default Logging Level",StdErrLog.LEVEL_INFO,StdErrLog.getLoggingLevel(props,StdErrLogTest.class.getName()));
}
@Test
public void testGetLoggingLevel_Root()
{
Properties props = new Properties();
props.setProperty("log.LEVEL","DEBUG");
// Default Levels
Assert.assertEquals("Default Logging Level",StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,null));
Assert.assertEquals("Default Logging Level",StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,""));
Assert.assertEquals("Default Logging Level",StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty"));
Assert.assertEquals("Default Logging Level",StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,StdErrLogTest.class.getName()));
}
@Test
public void testGetLoggingLevel_FQCN()
{
@ -117,20 +130,21 @@ public class StdErrLogTest
public void testGetLoggingLevel_MixedLevels()
{
Properties props = new Properties();
props.setProperty("org.eclipse.jetty.util.LEVEL","DEBUG");
props.setProperty("log.LEVEL","DEBUG");
props.setProperty("org.eclipse.jetty.util.LEVEL","WARN");
props.setProperty("org.eclipse.jetty.util.ConcurrentHashMap.LEVEL","ALL");
// Default Levels
Assert.assertEquals(StdErrLog.LEVEL_INFO,StdErrLog.getLoggingLevel(props,null));
Assert.assertEquals(StdErrLog.LEVEL_INFO,StdErrLog.getLoggingLevel(props,""));
Assert.assertEquals(StdErrLog.LEVEL_INFO,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty"));
Assert.assertEquals(StdErrLog.LEVEL_INFO,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.server.ServerObject"));
Assert.assertEquals(StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,null));
Assert.assertEquals(StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,""));
Assert.assertEquals(StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty"));
Assert.assertEquals(StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.server.ServerObject"));
// Configured Level
Assert.assertEquals(StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,StdErrLogTest.class.getName()));
Assert.assertEquals(StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.util.MagicUtil"));
Assert.assertEquals(StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.util"));
Assert.assertEquals(StdErrLog.LEVEL_DEBUG,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.util.resource.FileResource"));
Assert.assertEquals(StdErrLog.LEVEL_WARN,StdErrLog.getLoggingLevel(props,StdErrLogTest.class.getName()));
Assert.assertEquals(StdErrLog.LEVEL_WARN,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.util.MagicUtil"));
Assert.assertEquals(StdErrLog.LEVEL_WARN,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.util"));
Assert.assertEquals(StdErrLog.LEVEL_WARN,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.util.resource.FileResource"));
Assert.assertEquals(StdErrLog.LEVEL_ALL,StdErrLog.getLoggingLevel(props,"org.eclipse.jetty.util.ConcurrentHashMap"));
}

View File

@ -55,12 +55,11 @@ public class JettyWebXmlConfiguration extends AbstractConfiguration
//cannot configure if the _context is already started
if (context.isStarted())
{
if (LOG.isDebugEnabled()){LOG.debug("Cannot configure webapp after it is started");}
LOG.debug("Cannot configure webapp after it is started");
return;
}
if(LOG.isDebugEnabled())
LOG.debug("Configuring web-jetty.xml");
LOG.debug("Configuring web-jetty.xml");
Resource web_inf = context.getWebInf();
// handle any WEB-INF descriptors
@ -80,9 +79,8 @@ public class JettyWebXmlConfiguration extends AbstractConfiguration
try
{
context.setServerClasses(null);
if(LOG.isDebugEnabled()) {
if(LOG.isDebugEnabled())
LOG.debug("Configure: "+jetty);
}
XmlConfiguration jetty_config = (XmlConfiguration)context.getAttribute(XML_CONFIGURATION);

View File

@ -153,7 +153,8 @@ public class StandardDescriptorProcessor extends IterativeDescriptorProcessor
break;
}
}
if (LOG.isDebugEnabled()) LOG.debug("ContextParam: " + name + "=" + value);
if (LOG.isDebugEnabled())
LOG.debug("ContextParam: " + name + "=" + value);
}

View File

@ -437,7 +437,8 @@ public class TagLibConfiguration extends AbstractConfiguration
public void visitListener (WebAppContext context, Descriptor descriptor, XmlParser.Node node)
{
String className=node.getString("listener-class",false,true);
if (LOG.isDebugEnabled()) LOG.debug("listener="+className);
if (LOG.isDebugEnabled())
LOG.debug("listener="+className);
try
{

View File

@ -400,11 +400,11 @@ public class WebAppContext extends ServletContextHandler implements WebAppClassL
if (LOG.isDebugEnabled())
{
ClassLoader loader = getClassLoader();
LOG.debug("Thread Context class loader is: " + loader);
LOG.debug("Thread Context classloader {}",loader);
loader=loader.getParent();
while(loader!=null)
{
LOG.debug("Parent class loader is: " + loader);
LOG.debug("Parent class loader: {} ",loader);
loader=loader.getParent();
}
}

View File

@ -198,7 +198,8 @@ public class WebDescriptor extends Descriptor
_metaDataComplete = Boolean.valueOf(s).booleanValue()?MetaDataComplete.True:MetaDataComplete.False;
}
LOG.debug(_xml.toString()+": Calculated metadatacomplete = " + _metaDataComplete + " with version=" + version);
if (LOG.isDebugEnabled())
LOG.debug(_xml.toString()+": Calculated metadatacomplete = " + _metaDataComplete + " with version=" + version);
}
public void processOrdering ()

View File

@ -125,7 +125,8 @@ public class WebInfConfiguration extends AbstractConfiguration
//cannot configure if the context is already started
if (context.isStarted())
{
if (LOG.isDebugEnabled()){LOG.debug("Cannot configure webapp "+context+" after it is started");}
if (LOG.isDebugEnabled())
LOG.debug("Cannot configure webapp "+context+" after it is started");
return;
}

View File

@ -81,7 +81,7 @@ public class WebXmlConfiguration extends AbstractConfiguration
// cannot configure if the context is already started
if (context.isStarted())
{
if (LOG.isDebugEnabled()) LOG.debug("Cannot configure webapp after it is started");
LOG.debug("Cannot configure webapp after it is started");
return;
}
@ -104,7 +104,8 @@ public class WebXmlConfiguration extends AbstractConfiguration
// do web.xml file
Resource web = web_inf.addPath("web.xml");
if (web.exists()) return web;
LOG.debug("No WEB-INF/web.xml in " + context.getWar() + ". Serving files and default/dynamic servlets only");
if (LOG.isDebugEnabled())
LOG.debug("No WEB-INF/web.xml in " + context.getWar() + ". Serving files and default/dynamic servlets only");
}
return null;
}

View File

@ -187,7 +187,7 @@
<plugin>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-version-maven-plugin</artifactId>
<version>1.0.6</version>
<version>1.0.7</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>