jetty-9 progress on unit tests and LocalConnector

This commit is contained in:
Greg Wilkins 2012-05-14 19:58:09 +02:00
parent fcfb5d704a
commit 68f8e073db
56 changed files with 1209 additions and 1292 deletions

View File

@ -892,7 +892,7 @@ public class HttpGenerator
final HttpFields _httpFields;
final long _contentLength;
public Info(HttpVersion httpVersion, HttpFields httpFields, long contentLength)
private Info(HttpVersion httpVersion, HttpFields httpFields, long contentLength)
{
_httpVersion = httpVersion;
_httpFields = httpFields;
@ -935,6 +935,11 @@ public class HttpGenerator
return _uri;
}
@Override
public String toString()
{
return String.format("RequestInfo{%s %s %s,%d}",_method,_uri,_httpVersion,_contentLength);
}
}
public static class ResponseInfo extends Info
@ -960,13 +965,21 @@ public class HttpGenerator
{
return _status;
}
public String getReason()
{
return _reason;
}
public boolean isHead()
{
return _head;
}
@Override
public String toString()
{
return String.format("ResponseInfo{%s %s %s,%d,%b}",_httpVersion,_status,_reason,_contentLength,_head);
}
}
}

View File

@ -15,7 +15,7 @@ import org.eclipse.jetty.util.log.Logger;
public class AsyncByteArrayEndPoint extends ByteArrayEndPoint implements AsyncEndPoint
{
private static final int TICK=500;
private static final int TICK=Integer.getInteger("org.eclipse.jetty.io.AsyncByteArrayEndPoint.TICK",100);
public static final Logger LOG=Log.getLogger(AsyncByteArrayEndPoint.class);
private static final Timer _timer = new Timer(true);
private boolean _checkForIdle;

View File

@ -122,9 +122,11 @@ public class ChannelEndPoint extends AbstractEndPoint
{
int filled = _channel.read(buffer);
if (filled==-1)
if (filled>0)
notIdle();
else if (filled==-1)
shutdownInput();
return filled;
}
catch(IOException e)
@ -142,11 +144,11 @@ public class ChannelEndPoint extends AbstractEndPoint
@Override
public int flush(ByteBuffer... buffers) throws IOException
{
int len=0;
int flushed=0;
if (buffers.length==1)
len=_channel.write(buffers[0]);
flushed=_channel.write(buffers[0]);
else if (buffers.length>1 && _channel instanceof GatheringByteChannel)
len= (int)((GatheringByteChannel)_channel).write(buffers,0,buffers.length);
flushed= (int)((GatheringByteChannel)_channel).write(buffers,0,buffers.length);
else
{
for (ByteBuffer b : buffers)
@ -155,13 +157,15 @@ public class ChannelEndPoint extends AbstractEndPoint
{
int l=_channel.write(b);
if (l>0)
len+=l;
flushed+=l;
else
break;
}
}
}
return len;
if (flushed>0)
notIdle();
return flushed;
}
public ByteChannel getChannel()

View File

@ -28,7 +28,7 @@ public class NetworkTrafficSelectChannelEndPoint extends SelectChannelEndPoint
private final List<NetworkTrafficListener> listeners;
public NetworkTrafficSelectChannelEndPoint(SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey key, int maxIdleTime, List<NetworkTrafficListener> listeners) throws IOException
public NetworkTrafficSelectChannelEndPoint(SocketChannel channel, SelectorManager.ManagedSelector selectSet, SelectionKey key, int maxIdleTime, List<NetworkTrafficListener> listeners) throws IOException
{
super(channel, selectSet, key, maxIdleTime);
this.listeners = listeners;

View File

@ -20,7 +20,7 @@ import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.io.SelectorManager.SelectSet;
import org.eclipse.jetty.io.SelectorManager.ManagedSelector;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -33,7 +33,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
{
public static final Logger LOG = Log.getLogger(SelectChannelEndPoint.class);
private final SelectorManager.SelectSet _selectSet;
private final SelectorManager.ManagedSelector _selectSet;
private final SelectorManager _manager;
private SelectionKey _key;
@ -44,7 +44,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
/** The desired value for {@link SelectionKey#interestOps()} */
private int _interestOps;
/** true if {@link SelectSet#destroyEndPoint(SelectorManager.SelectableAsyncEndPoint)} has not been called */
/** true if {@link ManagedSelector#destroyEndPoint(SelectorManager.SelectableAsyncEndPoint)} has not been called */
private boolean _open;
private volatile boolean _idlecheck;
@ -72,7 +72,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
};
/* ------------------------------------------------------------ */
public SelectChannelEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key, int maxIdleTime) throws IOException
public SelectChannelEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key, int maxIdleTime) throws IOException
{
super(channel);
_manager = selectSet.getManager();
@ -203,17 +203,6 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
}
}
/* ------------------------------------------------------------ */
@Override
public int fill(ByteBuffer buffer) throws IOException
{
int fill = super.fill(buffer);
if (fill > 0)
notIdle();
return fill;
}
/* ------------------------------------------------------------ */
@Override
public <C> void readable(C context, Callback<C> callback) throws IllegalStateException
@ -228,16 +217,6 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
_writeFlusher.write(context,callback,buffers);
}
/* ------------------------------------------------------------ */
@Override
public int flush(ByteBuffer... buffers) throws IOException
{
int l = super.flush(buffers);
if (l > 0)
notIdle();
return l;
}
/* ------------------------------------------------------------ */
/**
* Updates selection key. This method schedules a call to doUpdateKey to do the keyChange
@ -401,7 +380,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
}
/* ------------------------------------------------------------ */
public SelectSet getSelectSet()
public ManagedSelector getSelectSet()
{
return _selectSet;
}

View File

@ -50,37 +50,26 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
{
public static final Logger LOG = Log.getLogger(SelectorManager.class);
private final Executor _executor;
private final SelectSet[] _selectSets;
private int _maxIdleTime;
private final ManagedSelector[] _selectSets;
private long _selectSetIndex;
protected SelectorManager(Executor executor)
protected SelectorManager()
{
this(executor, 1);
this((Runtime.getRuntime().availableProcessors()+1)/2);
}
protected SelectorManager(@Name("executor") Executor executor, @Name("selectSets") int selectSets)
protected SelectorManager(@Name("selectors") int selectors)
{
this._executor = executor;
this._selectSets = new SelectSet[selectSets];
this._selectSets = new ManagedSelector[selectors];
}
/**
* @param maxIdleTime The maximum period in milliseconds that a connection may be idle before it is closed.
*/
public void setMaxIdleTime(long maxIdleTime)
{
_maxIdleTime=(int)maxIdleTime;
}
/**
* @return the max idle time
*/
public long getMaxIdleTime()
{
return _maxIdleTime;
}
protected abstract int getMaxIdleTime();
protected abstract void execute(Runnable task);
/**
* @return the number of select sets in use
@ -90,7 +79,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
return _selectSets.length;
}
private SelectSet chooseSelectSet()
private ManagedSelector chooseSelectSet()
{
// The ++ increment here is not atomic, but it does not matter.
// so long as the value changes sometimes, then connections will
@ -107,7 +96,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
*/
public void connect(SocketChannel channel, Object attachment)
{
SelectSet set = chooseSelectSet();
ManagedSelector set = chooseSelectSet();
set.submit(set.new Connect(channel, attachment));
}
@ -117,22 +106,17 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
*/
public void accept(final SocketChannel channel)
{
final SelectSet set = chooseSelectSet();
final ManagedSelector set = chooseSelectSet();
set.submit(set.new Accept(channel));
}
private void execute(Runnable task)
{
_executor.execute(task);
}
@Override
protected void doStart() throws Exception
{
super.doStart();
for (int i=0;i< _selectSets.length;i++)
{
SelectSet selectSet = newSelectSet(i);
ManagedSelector selectSet = newSelectSet(i);
_selectSets[i] = selectSet;
selectSet.start();
execute(selectSet);
@ -140,15 +124,15 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
}
}
protected SelectSet newSelectSet(int id)
protected ManagedSelector newSelectSet(int id)
{
return new SelectSet(id);
return new ManagedSelector(id);
}
@Override
protected void doStop() throws Exception
{
for (SelectSet set : _selectSets)
for (ManagedSelector set : _selectSets)
set.stop();
super.doStop();
}
@ -185,7 +169,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
* @return the new endpoint {@link SelectChannelEndPoint}
* @throws IOException if the endPoint cannot be created
*/
protected abstract SelectableAsyncEndPoint newEndPoint(SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey sKey) throws IOException;
protected abstract SelectableAsyncEndPoint newEndPoint(SocketChannel channel, SelectorManager.ManagedSelector selectSet, SelectionKey sKey) throws IOException;
protected void connectionFailed(SocketChannel channel, Throwable ex, Object attachment)
{
@ -210,7 +194,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
{
while (isRunning())
{
for (SelectSet selectSet : _selectSets)
for (ManagedSelector selectSet : _selectSets)
selectSet.timeoutCheck();
sleep(1000);
}
@ -229,7 +213,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
}
}
public class SelectSet extends AbstractLifeCycle implements Runnable, Dumpable
public class ManagedSelector extends AbstractLifeCycle implements Runnable, Dumpable
{
private final ConcurrentLinkedQueue<Runnable> _changes = new ConcurrentLinkedQueue<>();
private ConcurrentMap<AsyncEndPoint,Object> _endPoints = new ConcurrentHashMap<>();
@ -238,7 +222,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
private Thread _thread;
private boolean needsWakeup = true;
protected SelectSet(int id)
protected ManagedSelector(int id)
{
_id = id;
}

View File

@ -36,8 +36,20 @@ public class SelectChannelEndPointTest
protected ServerSocketChannel _connector;
protected QueuedThreadPool _threadPool = new QueuedThreadPool();
private int maxIdleTimeout = 600000; // TODO: use smaller value
protected SelectorManager _manager = new SelectorManager(_threadPool)
protected SelectorManager _manager = new SelectorManager()
{
@Override
protected int getMaxIdleTime()
{
return maxIdleTimeout;
}
@Override
protected void execute(Runnable task)
{
_threadPool.execute(task);
}
@Override
protected void endPointClosed(AsyncEndPoint endpoint)
{
@ -61,9 +73,9 @@ public class SelectChannelEndPointTest
}
@Override
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) throws IOException
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException
{
SelectChannelEndPoint endp = new SelectChannelEndPoint(channel,selectSet,key,maxIdleTimeout);
SelectChannelEndPoint endp = new SelectChannelEndPoint(channel,selectSet,key,getMaxIdleTime());
endp.setAsyncConnection(selectSet.getManager().newConnection(channel,endp, key.attachment()));
_lastEndp=endp;
return endp;

View File

@ -20,6 +20,7 @@ import java.util.concurrent.Executor;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.StandardByteBufferPool;
import org.eclipse.jetty.util.Name;
import org.eclipse.jetty.util.component.AggregateLifeCycle;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.log.Log;
@ -42,14 +43,14 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
{
static final Logger LOG = Log.getLogger(AbstractConnector.class);
private String _name;
private final Thread[] _acceptors;
private String _name;
private Server _server;
private Executor _executor;
private String _host;
private int _port = 0;
private int _acceptQueueSize = 0;
private int _acceptors = 1;
private int _acceptorPriorityOffset = 0;
private boolean _reuseAddress = true;
private ByteBufferPool _byteBufferPool=new StandardByteBufferPool(); // TODO should this be server wide? or a thread local one?
@ -59,7 +60,6 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
protected int _maxIdleTime = 200000;
protected int _soLingerTime = -1;
private transient Thread[] _acceptorThreads;
/* ------------------------------------------------------------ */
@ -67,6 +67,17 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
*/
public AbstractConnector()
{
this(Math.max(1,(Runtime.getRuntime().availableProcessors())/4));
}
/* ------------------------------------------------------------ */
/**
*/
public AbstractConnector(@Name("acceptors") int acceptors)
{
if (acceptors > 2 * Runtime.getRuntime().availableProcessors())
LOG.warn("Acceptors should be <=2*availableProcessors: " + this);
_acceptors=new Thread[acceptors];
}
/* ------------------------------------------------------------ */
@ -120,7 +131,8 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
{
return _byteBufferPool;
}
/* ------------------------------------------------------------ */
public void setByteBufferPool(ByteBufferPool byteBufferPool)
{
removeBean(byteBufferPool);
@ -129,17 +141,15 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
}
/* ------------------------------------------------------------ */
/**
*/
public void setHost(String host)
{
_host = host;
if (this instanceof NetConnector)
_host = host;
else
throw new UnsupportedOperationException();
}
/* ------------------------------------------------------------ */
/*
*/
@Override
public String getHost()
{
return _host;
@ -148,16 +158,34 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
/* ------------------------------------------------------------ */
public void setPort(int port)
{
_port = port;
if (this instanceof NetConnector)
_port = port;
else
throw new UnsupportedOperationException();
}
/* ------------------------------------------------------------ */
@Override
public int getPort()
{
return _port;
}
/* ------------------------------------------------------------ */
public void open() throws IOException
{
}
/* ------------------------------------------------------------ */
public void close() throws IOException
{
}
/* ------------------------------------------------------------ */
public int getLocalPort()
{
return -1;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the maxIdleTime.
@ -227,20 +255,9 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
*/
public int getAcceptors()
{
return _acceptors;
return _acceptors.length;
}
/* ------------------------------------------------------------ */
/**
* @param acceptors
* The number of acceptor threads to set.
*/
public void setAcceptors(int acceptors)
{
if (acceptors > 2 * Runtime.getRuntime().availableProcessors())
LOG.warn("Acceptors should be <=2*availableProcessors: " + this);
_acceptors = acceptors;
}
/* ------------------------------------------------------------ */
/**
@ -259,17 +276,20 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
if (_server == null)
throw new IllegalStateException("No server");
if (_name==null)
_name = (getHost() == null?"0.0.0.0":getHost()) + ":" + getPort();
// open listener port
open();
_name=_name+"/"+getLocalPort();
super.doStart();
// Start selector thread
synchronized (this)
{
_acceptorThreads = new Thread[getAcceptors()];
for (int i = 0; i < _acceptorThreads.length; i++)
for (int i = 0; i < _acceptors.length; i++)
findExecutor().execute(new Acceptor(i));
}
@ -291,34 +311,23 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
super.doStop();
Thread[] acceptors;
synchronized (this)
for (Thread thread : _acceptors)
{
acceptors = _acceptorThreads;
_acceptorThreads = null;
}
if (acceptors != null)
{
for (Thread thread : acceptors)
{
if (thread != null)
thread.interrupt();
}
if (thread != null)
thread.interrupt();
}
int i=_name.lastIndexOf("/");
if (i>0)
_name=_name.substring(0,i);
}
/* ------------------------------------------------------------ */
public void join() throws InterruptedException
{
Thread[] threads;
synchronized(this)
{
threads=_acceptorThreads;
}
if (threads != null)
for (Thread thread : threads)
if (thread != null)
thread.join();
for (Thread thread : _acceptors)
if (thread != null)
thread.join();
}
/* ------------------------------------------------------------ */
@ -341,12 +350,6 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
/* ------------------------------------------------------------ */
protected abstract void accept(int acceptorID) throws IOException, InterruptedException;
/* ------------------------------------------------------------ */
public void stopAccept(int acceptorID) throws Exception
{
}
/* ------------------------------------------------------------ */
@Override
public String toString()
@ -377,11 +380,11 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
String name;
synchronized (AbstractConnector.this)
{
if (_acceptorThreads == null)
if (!isRunning())
return;
_acceptorThreads[_acceptor] = current;
name = _acceptorThreads[_acceptor].getName();
_acceptors[_acceptor] = current;
name = _acceptors[_acceptor].getName();
current.setName(name + " Acceptor" + _acceptor + " " + AbstractConnector.this);
}
int old_priority = current.getPriority();
@ -412,8 +415,7 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
synchronized (AbstractConnector.this)
{
if (_acceptorThreads != null)
_acceptorThreads[_acceptor] = null;
_acceptors[_acceptor] = null;
}
}
}
@ -423,8 +425,6 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
@Override
public String getName()
{
if (_name == null)
_name = (getHost() == null?"0.0.0.0":getHost()) + ":" + (getLocalPort() <= 0?getPort():getLocalPort());
return _name;
}

View File

@ -1,446 +0,0 @@
package org.eclipse.jetty.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import javax.servlet.ServletRequest;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.io.ByteBufferPool;
public abstract class AbstractHttpConnector extends AbstractConnector implements HttpConnector
{
private String _integralScheme = HttpScheme.HTTPS.asString();
private int _integralPort = 0;
private String _confidentialScheme = HttpScheme.HTTPS.asString();
private int _confidentialPort = 0;
private boolean _forwarded;
private String _hostHeader;
private String _forwardedHostHeader = HttpHeader.X_FORWARDED_HOST.toString();
private String _forwardedServerHeader = HttpHeader.X_FORWARDED_SERVER.toString();
private String _forwardedForHeader = HttpHeader.X_FORWARDED_FOR.toString();
private String _forwardedProtoHeader = HttpHeader.X_FORWARDED_PROTO.toString();
private String _forwardedCipherSuiteHeader;
private String _forwardedSslSessionIdHeader;
private int _requestHeaderSize=6*1024;;
private int _requestBufferSize=16*1024;
private int _responseHeaderSize=6*1024;
private int _responseBufferSize=16*1024;
@Override
public int getRequestHeaderSize()
{
return _requestHeaderSize;
}
public void setRequestHeaderSize(int requestHeaderSize)
{
_requestHeaderSize = requestHeaderSize;
}
@Override
public int getRequestBufferSize()
{
return _requestBufferSize;
}
public void setRequestBufferSize(int requestBufferSize)
{
_requestBufferSize = requestBufferSize;
}
@Override
public int getResponseHeaderSize()
{
return _responseHeaderSize;
}
public void setResponseHeaderSize(int responseHeaderSize)
{
_responseHeaderSize = responseHeaderSize;
}
@Override
public int getResponseBufferSize()
{
return _responseBufferSize;
}
public void setResponseBufferSize(int responseBufferSize)
{
_responseBufferSize = responseBufferSize;
}
/* ------------------------------------------------------------ */
@Override
public void customize(Request request) throws IOException
{
if (isForwarded())
checkForwardedHeaders(request);
}
/* ------------------------------------------------------------ */
protected void checkForwardedHeaders(Request request) throws IOException
{
HttpFields httpFields = request.getHttpChannel().getRequestFields();
// Do SSL first
if (getForwardedCipherSuiteHeader()!=null)
{
String cipher_suite=httpFields.getStringField(getForwardedCipherSuiteHeader());
if (cipher_suite!=null)
request.setAttribute("javax.servlet.request.cipher_suite",cipher_suite);
}
if (getForwardedSslSessionIdHeader()!=null)
{
String ssl_session_id=httpFields.getStringField(getForwardedSslSessionIdHeader());
if(ssl_session_id!=null)
{
request.setAttribute("javax.servlet.request.ssl_session_id", ssl_session_id);
request.setScheme(HttpScheme.HTTPS.asString());
}
}
// Retrieving headers from the request
String forwardedHost = getLeftMostFieldValue(httpFields,getForwardedHostHeader());
String forwardedServer = getLeftMostFieldValue(httpFields,getForwardedServerHeader());
String forwardedFor = getLeftMostFieldValue(httpFields,getForwardedForHeader());
String forwardedProto = getLeftMostFieldValue(httpFields,getForwardedProtoHeader());
if (_hostHeader != null)
{
// Update host header
httpFields.put(HttpHeader.HOST.toString(),_hostHeader);
request.setServerName(null);
request.setServerPort(-1);
request.getServerName();
}
else if (forwardedHost != null)
{
// Update host header
httpFields.put(HttpHeader.HOST.toString(),forwardedHost);
request.setServerName(null);
request.setServerPort(-1);
request.getServerName();
}
else if (forwardedServer != null)
{
// Use provided server name
request.setServerName(forwardedServer);
}
if (forwardedFor != null)
{
request.setRemoteAddr(new InetSocketAddress(forwardedFor,request.getRemotePort()));
}
if (forwardedProto != null)
{
request.setScheme(forwardedProto);
}
}
/* ------------------------------------------------------------ */
protected String getLeftMostFieldValue(HttpFields fields, String header)
{
if (header == null)
return null;
String headerValue = fields.getStringField(header);
if (headerValue == null)
return null;
int commaIndex = headerValue.indexOf(',');
if (commaIndex == -1)
{
// Single value
return headerValue;
}
// The left-most value is the farthest downstream client
return headerValue.substring(0,commaIndex);
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialPort()
*/
@Override
public int getConfidentialPort()
{
return _confidentialPort;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialScheme()
*/
@Override
public String getConfidentialScheme()
{
return _confidentialScheme;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server .Request)
*/
@Override
public boolean isIntegral(Request request)
{
return false;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialPort()
*/
@Override
public int getIntegralPort()
{
return _integralPort;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getIntegralScheme()
*/
@Override
public String getIntegralScheme()
{
return _integralScheme;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server.Request)
*/
@Override
public boolean isConfidential(Request request)
{
return _forwarded && request.getScheme().equalsIgnoreCase(HttpScheme.HTTPS.toString());
}
/* ------------------------------------------------------------ */
/**
* @param confidentialPort
* The confidentialPort to set.
*/
public void setConfidentialPort(int confidentialPort)
{
_confidentialPort = confidentialPort;
}
/* ------------------------------------------------------------ */
/**
* @param confidentialScheme
* The confidentialScheme to set.
*/
public void setConfidentialScheme(String confidentialScheme)
{
_confidentialScheme = confidentialScheme;
}
/* ------------------------------------------------------------ */
/**
* @param integralPort
* The integralPort to set.
*/
public void setIntegralPort(int integralPort)
{
_integralPort = integralPort;
}
/* ------------------------------------------------------------ */
/**
* @param integralScheme
* The integralScheme to set.
*/
public void setIntegralScheme(String integralScheme)
{
_integralScheme = integralScheme;
}
/* ------------------------------------------------------------ */
/**
* Is reverse proxy handling on?
*
* @return true if this connector is checking the x-forwarded-for/host/server headers
*/
public boolean isForwarded()
{
return _forwarded;
}
/* ------------------------------------------------------------ */
/**
* Set reverse proxy handling. If set to true, then the X-Forwarded headers (or the headers set in their place) are looked for to set the request protocol,
* host, server and client ip.
*
* @param check
* true if this connector is checking the x-forwarded-for/host/server headers
* @set {@link #setForwardedForHeader(String)}
* @set {@link #setForwardedHostHeader(String)}
* @set {@link #setForwardedProtoHeader(String)}
* @set {@link #setForwardedServerHeader(String)}
*/
public void setForwarded(boolean check)
{
if (check)
LOG.debug("{} is forwarded",this);
_forwarded = check;
}
/* ------------------------------------------------------------ */
public String getHostHeader()
{
return _hostHeader;
}
/* ------------------------------------------------------------ */
/**
* Set a forced valued for the host header to control what is returned by {@link ServletRequest#getServerName()} and {@link ServletRequest#getServerPort()}.
* This value is only used if {@link #isForwarded()} is true.
*
* @param hostHeader
* The value of the host header to force.
*/
public void setHostHeader(String hostHeader)
{
_hostHeader = hostHeader;
}
/* ------------------------------------------------------------ */
/*
*
* @see #setForwarded(boolean)
*/
public String getForwardedHostHeader()
{
return _forwardedHostHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedHostHeader
* The header name for forwarded hosts (default x-forwarded-host)
* @see #setForwarded(boolean)
*/
public void setForwardedHostHeader(String forwardedHostHeader)
{
_forwardedHostHeader = forwardedHostHeader;
}
/* ------------------------------------------------------------ */
/**
* @return the header name for forwarded server.
* @see #setForwarded(boolean)
*/
public String getForwardedServerHeader()
{
return _forwardedServerHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedServerHeader
* The header name for forwarded server (default x-forwarded-server)
* @see #setForwarded(boolean)
*/
public void setForwardedServerHeader(String forwardedServerHeader)
{
_forwardedServerHeader = forwardedServerHeader;
}
/* ------------------------------------------------------------ */
/**
* @see #setForwarded(boolean)
*/
public String getForwardedForHeader()
{
return _forwardedForHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedRemoteAddressHeader
* The header name for forwarded for (default x-forwarded-for)
* @see #setForwarded(boolean)
*/
public void setForwardedForHeader(String forwardedRemoteAddressHeader)
{
_forwardedForHeader = forwardedRemoteAddressHeader;
}
/* ------------------------------------------------------------ */
/**
* Get the forwardedProtoHeader.
*
* @return the forwardedProtoHeader (default X-Forwarded-For)
* @see #setForwarded(boolean)
*/
public String getForwardedProtoHeader()
{
return _forwardedProtoHeader;
}
/* ------------------------------------------------------------ */
/**
* Set the forwardedProtoHeader.
*
* @param forwardedProtoHeader
* the forwardedProtoHeader to set (default X-Forwarded-For)
* @see #setForwarded(boolean)
*/
public void setForwardedProtoHeader(String forwardedProtoHeader)
{
_forwardedProtoHeader = forwardedProtoHeader;
}
/* ------------------------------------------------------------ */
/**
* @return The header name holding a forwarded cipher suite (default null)
*/
public String getForwardedCipherSuiteHeader()
{
return _forwardedCipherSuiteHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedCipherSuite
* The header name holding a forwarded cipher suite (default null)
*/
public void setForwardedCipherSuiteHeader(String forwardedCipherSuite)
{
_forwardedCipherSuiteHeader = forwardedCipherSuite;
}
/* ------------------------------------------------------------ */
/**
* @return The header name holding a forwarded SSL Session ID (default null)
*/
public String getForwardedSslSessionIdHeader()
{
return _forwardedSslSessionIdHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedSslSessionId
* The header name holding a forwarded SSL Session ID (default null)
*/
public void setForwardedSslSessionIdHeader(String forwardedSslSessionId)
{
_forwardedSslSessionIdHeader = forwardedSslSessionId;
}
}

View File

@ -18,7 +18,6 @@ import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.management.timer.TimerMBean;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
@ -35,7 +34,6 @@ import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.Timeout;
/* ------------------------------------------------------------ */
/** Implementation of Continuation and AsyncContext interfaces

View File

@ -0,0 +1,278 @@
// ========================================================================
// Copyright (c) 2003-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Executor;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.SelectChannelEndPoint;
import org.eclipse.jetty.io.SelectorManager;
import org.eclipse.jetty.io.SelectorManager.ManagedSelector;
import org.eclipse.jetty.server.Connector.NetConnector;
/* ------------------------------------------------------------------------------- */
/**
* Selecting NIO connector.
* <p>
* This connector uses efficient NIO buffers with a non blocking threading model. Direct NIO buffers
* are used and threads are only allocated to connections with requests. Synchronization is used to
* simulate blocking for the servlet API, and any unflushed content at the end of request handling
* is written asynchronously.
* </p>
* <p>
* This connector is best used when there are a many connections that have idle periods.
* </p>
* <p>
* When used with {@link org.eclipse.jetty.continuation.Continuation}, threadless waits are supported.
* If a filter or servlet returns after calling {@link Continuation#suspend()} or when a
* runtime exception is thrown from a call to {@link Continuation#undispatch()}, Jetty will
* will not send a response to the client. Instead the thread is released and the Continuation is
* placed on the timer queue. If the Continuation timeout expires, or it's
* resume method is called, then the request is again allocated a thread and the request is retried.
* The limitation of this approach is that request content is not available on the retried request,
* thus if possible it should be read after the continuation or saved as a request attribute or as the
* associated object of the Continuation instance.
* </p>
*
* @org.apache.xbean.XBean element="nioConnector" description="Creates an NIO based socket connector"
*/
public class ChannelHttpConnector extends HttpConnector implements NetConnector
{
private final SelectorManager _manager;
protected ServerSocketChannel _acceptChannel;
private int _localPort=-1;
/* ------------------------------------------------------------------------------- */
/**
* Constructor.
*
*/
public ChannelHttpConnector()
{
this(Math.max(1,(Runtime.getRuntime().availableProcessors())/4),
Math.max(1,(Runtime.getRuntime().availableProcessors())/4));
}
/* ------------------------------------------------------------ */
public ChannelHttpConnector(int acceptors, int selectors)
{
super(acceptors);
_manager=new ConnectorSelectorManager(selectors);
addBean(_manager,true);
}
/* ------------------------------------------------------------ */
@Override
public void accept(int acceptorID) throws IOException
{
ServerSocketChannel server;
synchronized(this)
{
server = _acceptChannel;
}
if (server!=null && server.isOpen() && _manager.isStarted())
{
SocketChannel channel = server.accept();
channel.configureBlocking(false);
Socket socket = channel.socket();
configure(socket);
_manager.accept(channel);
}
}
/* ------------------------------------------------------------ */
@Override
public void close()
{
synchronized(this)
{
if (_acceptChannel != null)
{
removeBean(_acceptChannel);
try
{
if (_acceptChannel.isOpen())
_acceptChannel.close();
}
catch(IOException e)
{
LOG.warn(e);
}
}
_acceptChannel = null;
_localPort=-2;
}
}
/* ------------------------------------------------------------------------------- */
@Override
public void customize(Request request) throws IOException
{
request.setTimeStamp(System.currentTimeMillis());
super.customize(request);
}
/* ------------------------------------------------------------ */
public SelectorManager getSelectorManager()
{
return _manager;
}
/* ------------------------------------------------------------ */
@Override
public synchronized Object getTransport()
{
return _acceptChannel;
}
/* ------------------------------------------------------------------------------- */
@Override
public int getLocalPort()
{
synchronized(this)
{
return _localPort;
}
}
/* ------------------------------------------------------------ */
@Override
public void open() throws IOException
{
synchronized(this)
{
if (_acceptChannel == null)
{
// Create a new server socket
_acceptChannel = ServerSocketChannel.open();
// Set to blocking mode
_acceptChannel.configureBlocking(true);
// Bind the server socket to the local host and port
_acceptChannel.socket().setReuseAddress(getReuseAddress());
InetSocketAddress addr = getHost()==null?new InetSocketAddress(getPort()):new InetSocketAddress(getHost(),getPort());
_acceptChannel.socket().bind(addr,getAcceptQueueSize());
_localPort=_acceptChannel.socket().getLocalPort();
if (_localPort<=0)
throw new IOException("Server channel not bound");
addBean(_acceptChannel);
}
}
}
/* ------------------------------------------------------------ */
@Override
public void setMaxIdleTime(int maxIdleTime)
{
super.setMaxIdleTime(maxIdleTime);
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.server.AbstractConnector#doStart()
*/
@Override
protected void doStart() throws Exception
{
super.doStart();
}
/* ------------------------------------------------------------ */
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException
{
SelectChannelEndPoint endp= new SelectChannelEndPoint(channel,selectSet,key, ChannelHttpConnector.this._maxIdleTime);
endp.setAsyncConnection(selectSet.getManager().newConnection(channel,endp, key.attachment()));
return endp;
}
/* ------------------------------------------------------------------------------- */
protected void endPointClosed(AsyncEndPoint endpoint)
{
endpoint.onClose();
connectionClosed(endpoint.getAsyncConnection());
}
/* ------------------------------------------------------------------------------- */
protected AsyncConnection newConnection(SocketChannel channel,final AsyncEndPoint endpoint)
{
return new HttpConnection(ChannelHttpConnector.this,endpoint,getServer());
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private final class ConnectorSelectorManager extends SelectorManager
{
private ConnectorSelectorManager(int selectSets)
{
super(selectSets);
}
@Override
protected void execute(Runnable task)
{
findExecutor().execute(task);
}
@Override
protected int getMaxIdleTime()
{
return ChannelHttpConnector.this.getMaxIdleTime();
}
@Override
protected void endPointClosed(AsyncEndPoint endpoint)
{
ChannelHttpConnector.this.endPointClosed(endpoint);
}
@Override
protected void endPointOpened(AsyncEndPoint endpoint)
{
// TODO handle max connections and low resources
connectionOpened(endpoint.getAsyncConnection());
}
@Override
protected void endPointUpgraded(AsyncEndPoint endpoint, AsyncConnection oldConnection)
{
connectionUpgraded(oldConnection,endpoint.getAsyncConnection());
}
@Override
public AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint, Object attachment)
{
return ChannelHttpConnector.this.newConnection(channel,endpoint);
}
@Override
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey sKey) throws IOException
{
return ChannelHttpConnector.this.newEndPoint(channel,selectSet,sKey);
}
}
}

View File

@ -17,7 +17,6 @@ import java.io.IOException;
import java.util.concurrent.Executor;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.component.LifeCycle;
/** HTTP Connector.
@ -39,63 +38,66 @@ public interface Connector extends LifeCycle
*/
String getName();
/* ------------------------------------------------------------ */
/**
* Opens the connector
* @throws IOException
*/
void open() throws IOException;
/* ------------------------------------------------------------ */
void close() throws IOException;
/* ------------------------------------------------------------ */
Server getServer();
/* ------------------------------------------------------------ */
Executor findExecutor();
/* ------------------------------------------------------------ */
Executor getExecutor();
/* ------------------------------------------------------------ */
ByteBufferPool getByteBufferPool();
/* ------------------------------------------------------------ */
/**
* @return The hostname representing the interface to which
* this connector will bind, or null for all interfaces.
*/
String getHost();
/* ------------------------------------------------------------ */
/**
* @return The configured port for the connector or 0 if any available
* port may be used.
*/
int getPort();
/* ------------------------------------------------------------ */
/**
* @return The actual port the connector is listening on or
* -1 if it has not been opened, or -2 if it has been closed.
*/
int getLocalPort();
/* ------------------------------------------------------------ */
/**
* @return Max Idle time for connections in milliseconds
*/
int getMaxIdleTime();
/* ------------------------------------------------------------ */
/**
* @return the underlying socket, channel, buffer etc. for the connector.
*/
Object getTransport();
/* ------------------------------------------------------------ */
Statistics getStatistics();
interface NetConnector extends Connector
{
/* ------------------------------------------------------------ */
/**
* Opens the connector
* @throws IOException
*/
void open() throws IOException;
/* ------------------------------------------------------------ */
void close();
/* ------------------------------------------------------------ */
/**
* @return The hostname representing the interface to which
* this connector will bind, or null for all interfaces.
*/
String getHost();
/* ------------------------------------------------------------ */
/**
* @return The configured port for the connector or 0 if any available
* port may be used.
*/
int getPort();
/* ------------------------------------------------------------ */
/**
* @return The actual port the connector is listening on or
* -1 if it has not been opened, or -2 if it has been closed.
*/
int getLocalPort();
}
interface Statistics extends LifeCycle
{

View File

@ -39,7 +39,6 @@ import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.io.UncheckedPrintWriter;
@ -50,7 +49,6 @@ import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.thread.Timeout.Task;
/**
*
@ -391,7 +389,8 @@ public abstract class HttpChannel
LOG.warn(String.valueOf(_uri),e);
error=true;
_request.setHandled(true);
sendError(info==null?400:500, null, null, true);
if (!_response.isCommitted())
sendError(info==null?400:500, null, null, true);
}
finally
{

View File

@ -21,13 +21,11 @@ import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.jetty.http.HttpException;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.http.HttpGenerator.Action;
import org.eclipse.jetty.http.HttpGenerator.ResponseInfo;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.io.AbstractAsyncConnection;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.AsyncEndPoint;
@ -37,13 +35,11 @@ import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.Timeout.Task;
/**
*/
public class HttpConnection extends AbstractAsyncConnection
{
private static final Logger LOG = Log.getLogger(HttpConnection.class);
private static final ThreadLocal<HttpConnection> __currentConnection = new ThreadLocal<HttpConnection>();
@ -57,7 +53,6 @@ public class HttpConnection extends AbstractAsyncConnection
private final ByteBufferPool _bufferPool;
private ResponseInfo _info;
FutureCallback<Void> _writeFuture;
ByteBuffer _requestBuffer=null;
ByteBuffer _responseHeader=null;
ByteBuffer _chunk=null;
@ -82,7 +77,8 @@ public class HttpConnection extends AbstractAsyncConnection
*/
public HttpConnection(HttpConnector connector, AsyncEndPoint endpoint, Server server)
{
super(endpoint,connector.getServer().getThreadPool());
super(endpoint,connector.findExecutor());
_connector = connector;
_bufferPool=_connector.getByteBufferPool();
if (_bufferPool==null)
@ -205,7 +201,7 @@ public class HttpConnection extends AbstractAsyncConnection
:_bufferPool.acquire(_connector.getRequestHeaderSize(),false);
int filled=getEndPoint().fill(_requestBuffer);
System.err.println("filled="+filled+" to "+BufferUtil.toDetailString(_requestBuffer)+" from "+getEndPoint());
LOG.debug("{} filled {}",this,filled);
// If we parse to an event, call the connection
if (BufferUtil.hasContent(_requestBuffer) && _parser.parseNext(_requestBuffer))
@ -289,7 +285,7 @@ public class HttpConnection extends AbstractAsyncConnection
if (_generator.isComplete())
throw new EofException();
do
loop: while (true)
{
if (LOG.isDebugEnabled())
LOG.debug("{}: send({},{},{})@{}",
@ -329,18 +325,17 @@ public class HttpConnection extends AbstractAsyncConnection
break;
case FLUSH_CONTENT:
_writeFuture=write(_responseHeader,_chunk,content);
return;
write(_responseHeader,_chunk,content);
break loop;
case SHUTDOWN_OUT:
getEndPoint().shutdownOutput();
break;
break loop;
case OK:
break;
break loop;
}
}
while(BufferUtil.hasContent(content));
}
catch(InterruptedException e)
{
@ -360,14 +355,11 @@ public class HttpConnection extends AbstractAsyncConnection
/* ------------------------------------------------------------ */
private int generate(ByteBuffer content, Action action) throws IOException
{
boolean hasContent=BufferUtil.hasContent(content);
long preparedBefore=0;
long preparedAfter;
long prepared_before=0;
long prepared_after;
_lock.lock();
try
{
preparedBefore=_generator.getContentPrepared();
if (_generator.isComplete())
{
if (Action.COMPLETE==action)
@ -375,12 +367,9 @@ public class HttpConnection extends AbstractAsyncConnection
throw new EofException();
}
do
prepared_before=_generator.getContentPrepared();
loop: while (true)
{
// block if the last write is not complete
if (_writeFuture!=null && !_writeFuture.isDone())
_writeFuture.get();
if (LOG.isDebugEnabled())
LOG.debug("{}: generate({},{},{},{},{})@{}",
this,
@ -407,23 +396,20 @@ public class HttpConnection extends AbstractAsyncConnection
if (_info==null)
_info=_channel.getEventHandler().commit();
_responseHeader=_bufferPool.acquire(_connector.getResponseHeaderSize(),false);
break;
continue;
case NEED_BUFFER:
_responseBuffer=_bufferPool.acquire(_connector.getResponseBufferSize(),false);
break;
continue;
case NEED_CHUNK:
_responseHeader=null;
_chunk=_bufferPool.acquire(HttpGenerator.CHUNK_SIZE,false);
break;
continue;
case FLUSH:
if (hasContent)
write(_responseHeader,_chunk,_responseBuffer).get();
else
_writeFuture=write(_responseHeader,_chunk,_responseBuffer);
break;
write(_responseHeader,_chunk,_responseBuffer).get();
continue;
case FLUSH_CONTENT:
write(_responseHeader,_chunk,content).get();
@ -431,13 +417,13 @@ public class HttpConnection extends AbstractAsyncConnection
case SHUTDOWN_OUT:
getEndPoint().shutdownOutput();
break;
break loop;
case OK:
break;
if (!BufferUtil.hasContent(content))
break loop;
}
}
while(BufferUtil.hasContent(content));
}
catch(InterruptedException e)
{
@ -452,14 +438,15 @@ public class HttpConnection extends AbstractAsyncConnection
}
finally
{
preparedAfter=_generator.getContentPrepared();
prepared_after=_generator.getContentPrepared();
_lock.unlock();
}
return (int)(preparedAfter-preparedBefore);
return (int)(prepared_after-prepared_before);
}
private FutureCallback<Void> write(ByteBuffer b0,ByteBuffer b1,ByteBuffer b2)
{
// TODO use a recycled FutureCallback ????
FutureCallback<Void> fcb=new FutureCallback<>();
if (BufferUtil.hasContent(b0))
{

View File

@ -1,66 +1,446 @@
package org.eclipse.jetty.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.eclipse.jetty.io.EndPoint;
import javax.servlet.ServletRequest;
public interface HttpConnector extends Connector
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpScheme;
public abstract class HttpConnector extends AbstractConnector
{
int getRequestHeaderSize();
int getRequestBufferSize();
int getResponseHeaderSize();
int getResponseBufferSize();
/* ------------------------------------------------------------ */
/**
* @return The port to use when redirecting a request if a data constraint of integral is
* required. See {@link org.eclipse.jetty.util.security.Constraint#getDataConstraint()}
*/
int getIntegralPort();
private String _integralScheme = HttpScheme.HTTPS.asString();
private int _integralPort = 0;
private String _confidentialScheme = HttpScheme.HTTPS.asString();
private int _confidentialPort = 0;
private boolean _forwarded;
private String _hostHeader;
/* ------------------------------------------------------------ */
/**
* @return The schema to use when redirecting a request if a data constraint of integral is
* required. See {@link org.eclipse.jetty.util.security.Constraint#getDataConstraint()}
*/
String getIntegralScheme();
private String _forwardedHostHeader = HttpHeader.X_FORWARDED_HOST.toString();
private String _forwardedServerHeader = HttpHeader.X_FORWARDED_SERVER.toString();
private String _forwardedForHeader = HttpHeader.X_FORWARDED_FOR.toString();
private String _forwardedProtoHeader = HttpHeader.X_FORWARDED_PROTO.toString();
private String _forwardedCipherSuiteHeader;
private String _forwardedSslSessionIdHeader;
/* ------------------------------------------------------------ */
/**
* @param request A request
* @return true if the request is integral. This normally means the https schema has been used.
*/
boolean isIntegral(Request request);
/* ------------------------------------------------------------ */
/**
* @return The port to use when redirecting a request if a data constraint of confidential is
* required. See {@link org.eclipse.jetty.util.security.Constraint#getDataConstraint()}
*/
int getConfidentialPort();
/* ------------------------------------------------------------ */
/**
* @return The schema to use when redirecting a request if a data constraint of confidential is
* required. See {@link org.eclipse.jetty.util.security.Constraint#getDataConstraint()}
*/
String getConfidentialScheme();
/* ------------------------------------------------------------ */
/**
* @param request A request
* @return true if the request is confidential. This normally means the https schema has been used.
*/
boolean isConfidential(Request request);
/* ------------------------------------------------------------ */
/** Customize a request for an endpoint.
* Called on every request to allow customization of the request for
* the particular endpoint (eg security properties from a SSL connection).
* @param request
* @throws IOException
*/
void customize(Request request) throws IOException;
private int _requestHeaderSize=6*1024;;
private int _requestBufferSize=16*1024;
private int _responseHeaderSize=6*1024;
private int _responseBufferSize=16*1024;
public HttpConnector()
{
super();
}
public HttpConnector(int acceptors)
{
super(acceptors);
}
public int getRequestHeaderSize()
{
return _requestHeaderSize;
}
public void setRequestHeaderSize(int requestHeaderSize)
{
_requestHeaderSize = requestHeaderSize;
}
public int getRequestBufferSize()
{
return _requestBufferSize;
}
public void setRequestBufferSize(int requestBufferSize)
{
_requestBufferSize = requestBufferSize;
}
public int getResponseHeaderSize()
{
return _responseHeaderSize;
}
public void setResponseHeaderSize(int responseHeaderSize)
{
_responseHeaderSize = responseHeaderSize;
}
public int getResponseBufferSize()
{
return _responseBufferSize;
}
public void setResponseBufferSize(int responseBufferSize)
{
_responseBufferSize = responseBufferSize;
}
/* ------------------------------------------------------------ */
public void customize(Request request) throws IOException
{
if (isForwarded())
checkForwardedHeaders(request);
}
/* ------------------------------------------------------------ */
protected void checkForwardedHeaders(Request request) throws IOException
{
HttpFields httpFields = request.getHttpChannel().getRequestFields();
// Do SSL first
if (getForwardedCipherSuiteHeader()!=null)
{
String cipher_suite=httpFields.getStringField(getForwardedCipherSuiteHeader());
if (cipher_suite!=null)
request.setAttribute("javax.servlet.request.cipher_suite",cipher_suite);
}
if (getForwardedSslSessionIdHeader()!=null)
{
String ssl_session_id=httpFields.getStringField(getForwardedSslSessionIdHeader());
if(ssl_session_id!=null)
{
request.setAttribute("javax.servlet.request.ssl_session_id", ssl_session_id);
request.setScheme(HttpScheme.HTTPS.asString());
}
}
// Retrieving headers from the request
String forwardedHost = getLeftMostFieldValue(httpFields,getForwardedHostHeader());
String forwardedServer = getLeftMostFieldValue(httpFields,getForwardedServerHeader());
String forwardedFor = getLeftMostFieldValue(httpFields,getForwardedForHeader());
String forwardedProto = getLeftMostFieldValue(httpFields,getForwardedProtoHeader());
if (_hostHeader != null)
{
// Update host header
httpFields.put(HttpHeader.HOST.toString(),_hostHeader);
request.setServerName(null);
request.setServerPort(-1);
request.getServerName();
}
else if (forwardedHost != null)
{
// Update host header
httpFields.put(HttpHeader.HOST.toString(),forwardedHost);
request.setServerName(null);
request.setServerPort(-1);
request.getServerName();
}
else if (forwardedServer != null)
{
// Use provided server name
request.setServerName(forwardedServer);
}
if (forwardedFor != null)
{
request.setRemoteAddr(new InetSocketAddress(forwardedFor,request.getRemotePort()));
}
if (forwardedProto != null)
{
request.setScheme(forwardedProto);
}
}
/* ------------------------------------------------------------ */
protected String getLeftMostFieldValue(HttpFields fields, String header)
{
if (header == null)
return null;
String headerValue = fields.getStringField(header);
if (headerValue == null)
return null;
int commaIndex = headerValue.indexOf(',');
if (commaIndex == -1)
{
// Single value
return headerValue;
}
// The left-most value is the farthest downstream client
return headerValue.substring(0,commaIndex);
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialPort()
*/
public int getConfidentialPort()
{
return _confidentialPort;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialScheme()
*/
public String getConfidentialScheme()
{
return _confidentialScheme;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server .Request)
*/
public boolean isIntegral(Request request)
{
return false;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialPort()
*/
public int getIntegralPort()
{
return _integralPort;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getIntegralScheme()
*/
public String getIntegralScheme()
{
return _integralScheme;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server.Request)
*/
public boolean isConfidential(Request request)
{
return _forwarded && request.getScheme().equalsIgnoreCase(HttpScheme.HTTPS.toString());
}
/* ------------------------------------------------------------ */
/**
* @param confidentialPort
* The confidentialPort to set.
*/
public void setConfidentialPort(int confidentialPort)
{
_confidentialPort = confidentialPort;
}
/* ------------------------------------------------------------ */
/**
* @param confidentialScheme
* The confidentialScheme to set.
*/
public void setConfidentialScheme(String confidentialScheme)
{
_confidentialScheme = confidentialScheme;
}
/* ------------------------------------------------------------ */
/**
* @param integralPort
* The integralPort to set.
*/
public void setIntegralPort(int integralPort)
{
_integralPort = integralPort;
}
/* ------------------------------------------------------------ */
/**
* @param integralScheme
* The integralScheme to set.
*/
public void setIntegralScheme(String integralScheme)
{
_integralScheme = integralScheme;
}
/* ------------------------------------------------------------ */
/**
* Is reverse proxy handling on?
*
* @return true if this connector is checking the x-forwarded-for/host/server headers
*/
public boolean isForwarded()
{
return _forwarded;
}
/* ------------------------------------------------------------ */
/**
* Set reverse proxy handling. If set to true, then the X-Forwarded headers (or the headers set in their place) are looked for to set the request protocol,
* host, server and client ip.
*
* @param check
* true if this connector is checking the x-forwarded-for/host/server headers
* @set {@link #setForwardedForHeader(String)}
* @set {@link #setForwardedHostHeader(String)}
* @set {@link #setForwardedProtoHeader(String)}
* @set {@link #setForwardedServerHeader(String)}
*/
public void setForwarded(boolean check)
{
if (check)
LOG.debug("{} is forwarded",this);
_forwarded = check;
}
/* ------------------------------------------------------------ */
public String getHostHeader()
{
return _hostHeader;
}
/* ------------------------------------------------------------ */
/**
* Set a forced valued for the host header to control what is returned by {@link ServletRequest#getServerName()} and {@link ServletRequest#getServerPort()}.
* This value is only used if {@link #isForwarded()} is true.
*
* @param hostHeader
* The value of the host header to force.
*/
public void setHostHeader(String hostHeader)
{
_hostHeader = hostHeader;
}
/* ------------------------------------------------------------ */
/*
*
* @see #setForwarded(boolean)
*/
public String getForwardedHostHeader()
{
return _forwardedHostHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedHostHeader
* The header name for forwarded hosts (default x-forwarded-host)
* @see #setForwarded(boolean)
*/
public void setForwardedHostHeader(String forwardedHostHeader)
{
_forwardedHostHeader = forwardedHostHeader;
}
/* ------------------------------------------------------------ */
/**
* @return the header name for forwarded server.
* @see #setForwarded(boolean)
*/
public String getForwardedServerHeader()
{
return _forwardedServerHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedServerHeader
* The header name for forwarded server (default x-forwarded-server)
* @see #setForwarded(boolean)
*/
public void setForwardedServerHeader(String forwardedServerHeader)
{
_forwardedServerHeader = forwardedServerHeader;
}
/* ------------------------------------------------------------ */
/**
* @see #setForwarded(boolean)
*/
public String getForwardedForHeader()
{
return _forwardedForHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedRemoteAddressHeader
* The header name for forwarded for (default x-forwarded-for)
* @see #setForwarded(boolean)
*/
public void setForwardedForHeader(String forwardedRemoteAddressHeader)
{
_forwardedForHeader = forwardedRemoteAddressHeader;
}
/* ------------------------------------------------------------ */
/**
* Get the forwardedProtoHeader.
*
* @return the forwardedProtoHeader (default X-Forwarded-For)
* @see #setForwarded(boolean)
*/
public String getForwardedProtoHeader()
{
return _forwardedProtoHeader;
}
/* ------------------------------------------------------------ */
/**
* Set the forwardedProtoHeader.
*
* @param forwardedProtoHeader
* the forwardedProtoHeader to set (default X-Forwarded-For)
* @see #setForwarded(boolean)
*/
public void setForwardedProtoHeader(String forwardedProtoHeader)
{
_forwardedProtoHeader = forwardedProtoHeader;
}
/* ------------------------------------------------------------ */
/**
* @return The header name holding a forwarded cipher suite (default null)
*/
public String getForwardedCipherSuiteHeader()
{
return _forwardedCipherSuiteHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedCipherSuite
* The header name holding a forwarded cipher suite (default null)
*/
public void setForwardedCipherSuiteHeader(String forwardedCipherSuite)
{
_forwardedCipherSuiteHeader = forwardedCipherSuite;
}
/* ------------------------------------------------------------ */
/**
* @return The header name holding a forwarded SSL Session ID (default null)
*/
public String getForwardedSslSessionIdHeader()
{
return _forwardedSslSessionIdHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedSslSessionId
* The header name holding a forwarded SSL Session ID (default null)
*/
public void setForwardedSslSessionIdHeader(String forwardedSslSessionId)
{
_forwardedSslSessionIdHeader = forwardedSslSessionId;
}
}

View File

@ -19,6 +19,7 @@ import java.nio.ByteBuffer;
import javax.servlet.ServletOutputStream;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.ByteArrayOutputStream2;
/** Output.
@ -103,7 +104,7 @@ public class HttpOutput extends ServletOutputStream
public void write(byte[] b, int off, int len) throws IOException
{
if (_closed)
throw new IOException("Closed");
throw new EofException();
_written+=_channel.write(ByteBuffer.wrap(b,off,len));
_channel.getResponse().checkAllContentWritten(_written);

View File

@ -1,176 +0,0 @@
// ========================================================================
// Copyright (c) 2006-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.ByteArrayEndPoint;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
public class LocalConnector extends AbstractHttpConnector
{
private static final Logger LOG = Log.getLogger(LocalConnector.class);
private final BlockingQueue<Request> _requests = new LinkedBlockingQueue<Request>();
public LocalConnector()
{
setMaxIdleTime(30000);
}
@Override
public Object getTransport()
{
return this;
}
public String getResponses(String requests) throws Exception
{
return getResponses(requests, false);
}
public String getResponses(String requests, boolean keepOpen) throws Exception
{
ByteBuffer result = getResponses(BufferUtil.toBuffer(requests,StringUtil.__UTF8_CHARSET), keepOpen);
return result==null?null:BufferUtil.toString(result,StringUtil.__UTF8_CHARSET);
}
public ByteBuffer getResponses(ByteBuffer requestsBuffer, boolean keepOpen) throws Exception
{
CountDownLatch latch = new CountDownLatch(1);
Request request = new Request(requestsBuffer, keepOpen, latch);
_requests.add(request);
latch.await(getMaxIdleTime(),TimeUnit.MILLISECONDS);
return request.getResponsesBuffer();
}
@Override
protected void accept(int acceptorID) throws IOException, InterruptedException
{
Request request = _requests.take();
findExecutor().execute(request);
}
public void open() throws IOException
{
}
public void close() throws IOException
{
}
public int getLocalPort()
{
return -1;
}
public void executeRequest(String rawRequest) throws IOException
{
Request request = new Request(BufferUtil.toBuffer(rawRequest,StringUtil.__UTF8_CHARSET),true,null);
_requests.add(request);
}
private class Request implements Runnable
{
private final ByteBuffer _requestsBuffer;
private final boolean _keepOpen;
private final CountDownLatch _latch;
private volatile ByteBuffer _responsesBuffer;
private Request(ByteBuffer requestsBuffer, boolean keepOpen, CountDownLatch latch)
{
_requestsBuffer = requestsBuffer;
_keepOpen = keepOpen;
_latch = latch;
}
public void run()
{
/*
try
{
ByteArrayEndPoint endPoint = new ByteArrayEndPoint(_requestsBuffer.asArray(), 1024)
{
@Override
public void setConnection(AsyncConnection connection)
{
if (getConnection()!=null && connection!=getConnection())
connectionUpgraded(getConnection(),connection);
super.setConnection(connection);
}
};
endPoint.setGrowOutput(true);
AbstractHttpConnection connection = new BlockingHttpConnection(LocalConnector.this, endPoint, getServer());
endPoint.setConnection(connection);
connectionOpened(connection);
boolean leaveOpen = _keepOpen;
try
{
while (endPoint.getIn().length() > 0 && endPoint.isOpen())
{
while (true)
{
final AsyncConnection con = endPoint.getConnection();
final AsyncConnection next = con.handle();
if (next!=con)
{
endPoint.setConnection(next);
continue;
}
break;
}
}
}
catch (IOException x)
{
LOG.debug(x);
leaveOpen = false;
}
catch (Exception x)
{
LOG.warn(x);
leaveOpen = false;
}
finally
{
if (!leaveOpen)
connectionClosed(connection);
_responsesBuffer = endPoint.getOutput();
}
}
finally
{
if (_latch != null)
_latch.countDown();
}
*/
}
public ByteBuffer getResponsesBuffer()
{
return _responsesBuffer;
}
}
}

View File

@ -0,0 +1,157 @@
// ========================================================================
// Copyright (c) 2006-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Phaser;
import org.eclipse.jetty.io.AsyncByteArrayEndPoint;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
public class LocalHttpConnector extends HttpConnector
{
private static final Logger LOG = Log.getLogger(LocalHttpConnector.class);
private final BlockingQueue<LocalEndPoint> _connects = new LinkedBlockingQueue<LocalEndPoint>();
private LocalExecutor _executor;
public LocalHttpConnector()
{
setMaxIdleTime(30000);
}
@Override
public Object getTransport()
{
return this;
}
public String getResponses(String requests) throws Exception
{
ByteBuffer result = getResponses(BufferUtil.toBuffer(requests,StringUtil.__UTF8_CHARSET));
return result==null?null:BufferUtil.toString(result,StringUtil.__UTF8_CHARSET);
}
public ByteBuffer getResponses(ByteBuffer requestsBuffer) throws Exception
{
int phase=_executor._phaser.getPhase();
LocalEndPoint request = new LocalEndPoint();
request.setInput(requestsBuffer);
_connects.add(request);
_executor._phaser.awaitAdvance(phase);
return request.takeOutput();
}
public void executeRequest(String rawRequest)
{
LocalEndPoint endp = new LocalEndPoint();
endp.setInput(BufferUtil.toBuffer(rawRequest,StringUtil.__UTF8_CHARSET));
_connects.add(endp);
}
@Override
protected void accept(int acceptorID) throws IOException, InterruptedException
{
LOG.debug("accepting {}",acceptorID);
LocalEndPoint endp = _connects.take();
_executor._phaser.register();
HttpConnection connection=new HttpConnection(this,endp,getServer());
endp.setAsyncConnection(connection);
LOG.debug("accepted {} {}",endp,connection);
connection.onOpen();
_executor._phaser.arriveAndDeregister();
}
@Override
protected void doStart() throws Exception
{
super.doStart();
_executor=new LocalExecutor(findExecutor());
}
@Override
protected void doStop() throws Exception
{
super.doStop();
_executor=null;
}
@Override
public Executor findExecutor()
{
return _executor==null?super.findExecutor():_executor;
}
class LocalExecutor implements Executor
{
Phaser _phaser=new Phaser()
{
@Override
protected boolean onAdvance(int phase, int registeredParties)
{
return super.onAdvance(phase,registeredParties);
}
};
final Executor _executor;
LocalExecutor(Executor e)
{
_executor=e;
}
@Override
public void execute(final Runnable task)
{
_phaser.register();
_executor.execute(new Runnable()
{
@Override
public void run()
{
try
{
task.run();
}
finally
{
_phaser.arriveAndDeregister();
}
}
});
}
}
private class LocalEndPoint extends AsyncByteArrayEndPoint
{
LocalEndPoint()
{
setGrowOutput(true);
}
LocalEndPoint(CountDownLatch onCloseLatch)
{
this();
}
}
}

View File

@ -29,6 +29,7 @@ import javax.servlet.http.HttpSession;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.http.HttpGenerator.ResponseInfo;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpScheme;
@ -36,7 +37,6 @@ import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http.HttpGenerator.ResponseInfo;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.ByteArrayISO8859Writer;
@ -372,9 +372,6 @@ public class Response implements HttpServletResponse
writer.write(message);
writer.write("</pre>");
writer.write("</p>\n<hr /><i><small>Powered by Jetty://</small></i>");
for (int i= 0; i < 20; i++)
writer.write("\n ");
writer.write("\n</body>\n</html>\n");
writer.flush();
@ -898,7 +895,7 @@ public class Response implements HttpServletResponse
{
_contentType=contentType;
_mimeType=MimeTypes.CACHE.get(contentType);
String charset=_mimeType==null?MimeTypes.getCharsetFromContentType(contentType):_mimeType.getCharset().toString();
String charset=(_mimeType!=null && _mimeType.getCharset()!=null)?_mimeType.getCharset().toString():null;
if (charset!=null)
_characterEncoding=charset;

View File

@ -24,8 +24,8 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.server.Connector.NetConnector;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.AttributesMap;
import org.eclipse.jetty.util.LazyList;
@ -88,26 +88,26 @@ public class Server extends HandlerWrapper implements Attributes
/* ------------------------------------------------------------ */
/** Convenience constructor
* Creates server and a {@link SelectChannelConnector} at the passed port.
* Creates server and a {@link ChannelHttpConnector} at the passed port.
*/
public Server(int port)
{
setServer(this);
SelectChannelConnector connector=new SelectChannelConnector();
ChannelHttpConnector connector=new ChannelHttpConnector();
connector.setPort(port);
setConnectors(new Connector[]{connector});
}
/* ------------------------------------------------------------ */
/** Convenience constructor
* Creates server and a {@link SelectChannelConnector} at the passed address.
* Creates server and a {@link ChannelHttpConnector} at the passed address.
*/
public Server(InetSocketAddress addr)
{
setServer(this);
SelectChannelConnector connector=new SelectChannelConnector();
ChannelHttpConnector connector=new ChannelHttpConnector();
connector.setHost(addr.getHostName());
connector.setPort(addr.getPort());
setConnectors(new Connector[]{connector});
@ -305,7 +305,8 @@ public class Server extends HandlerWrapper implements Attributes
for (int i=_connectors.length;i-->0;)
{
LOG.info("Graceful shutdown {}",_connectors[i]);
try{_connectors[i].close();}catch(Throwable e){mex.add(e);}
if (_connectors[i] instanceof NetConnector)
((NetConnector)_connectors[i]).close();
}
}

View File

@ -3,31 +3,20 @@ package org.eclipse.jetty.server.handler;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.SelectChannelEndPoint;
import org.eclipse.jetty.io.SelectorManager;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.HostMap;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

View File

@ -19,7 +19,6 @@ import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Arrays;

View File

@ -104,7 +104,7 @@ public class DefaultHandler extends AbstractHandler
}
if (!method.equals(HttpMethod.GET) || !request.getRequestURI().equals("/"))
if (!_showContexts || !method.equals(HttpMethod.GET) || !request.getRequestURI().equals("/"))
{
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
@ -118,53 +118,46 @@ public class DefaultHandler extends AbstractHandler
writer.write("<HTML>\n<HEAD>\n<TITLE>Error 404 - Not Found");
writer.write("</TITLE>\n<BODY>\n<H2>Error 404 - Not Found.</H2>\n");
writer.write("No context on this server matched or handled this request.<BR>");
if (_showContexts)
writer.write("Contexts known to this server are: <ul>");
Server server = getServer();
Handler[] handlers = server==null?null:server.getChildHandlersByClass(ContextHandler.class);
for (int i=0;handlers!=null && i<handlers.length;i++)
{
writer.write("Contexts known to this server are: <ul>");
Server server = getServer();
Handler[] handlers = server==null?null:server.getChildHandlersByClass(ContextHandler.class);
for (int i=0;handlers!=null && i<handlers.length;i++)
ContextHandler context = (ContextHandler)handlers[i];
if (context.isRunning())
{
ContextHandler context = (ContextHandler)handlers[i];
if (context.isRunning())
{
writer.write("<li><a href=\"");
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("http://"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write(context.getContextPath());
if (context.getContextPath().length()>1 && context.getContextPath().endsWith("/"))
writer.write("/");
writer.write("\">");
writer.write(context.getContextPath());
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write("&nbsp;--->&nbsp;");
writer.write(context.toString());
writer.write("</a></li>\n");
}
else
{
writer.write("<li>");
writer.write(context.getContextPath());
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write("&nbsp;--->&nbsp;");
writer.write(context.toString());
if (context.isFailed())
writer.write(" [failed]");
if (context.isStopped())
writer.write(" [stopped]");
writer.write("</li>\n");
}
writer.write("<li><a href=\"");
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("http://"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write(context.getContextPath());
if (context.getContextPath().length()>1 && context.getContextPath().endsWith("/"))
writer.write("/");
writer.write("\">");
writer.write(context.getContextPath());
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write("&nbsp;--->&nbsp;");
writer.write(context.toString());
writer.write("</a></li>\n");
}
else
{
writer.write("<li>");
writer.write(context.getContextPath());
if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
writer.write("&nbsp;--->&nbsp;");
writer.write(context.toString());
if (context.isFailed())
writer.write(" [failed]");
if (context.isStopped())
writer.write(" [stopped]");
writer.write("</li>\n");
}
}
for (int i=0;i<10;i++)
writer.write("\n<!-- Padding for IE -->");
writer.write("\n</BODY>\n</HTML>\n");
writer.flush();
response.setContentLength(writer.size());

View File

@ -104,9 +104,7 @@ public class ErrorHandler extends AbstractHandler
writeErrorPageMessage(request,writer,code,message,uri);
if (showStacks)
writeErrorPageStacks(request,writer);
writer.write("<hr /><i><small>Powered by Jetty://</small></i>");
for (int i= 0; i < 20; i++)
writer.write("<br/> \n");
writer.write("<hr><i><small>Powered by Jetty://</small></i><hr/>\n");
}
/* ------------------------------------------------------------ */

View File

@ -16,7 +16,6 @@ package org.eclipse.jetty.server.handler;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.nio.ByteBuffer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
@ -29,12 +28,9 @@ import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.io.WriterOutputStream;
import org.eclipse.jetty.server.Dispatcher;
import org.eclipse.jetty.server.HttpOutput;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

View File

@ -17,6 +17,7 @@ import java.io.IOException;
import java.nio.channels.Channel;
import java.nio.channels.ServerSocketChannel;
import org.eclipse.jetty.server.ChannelHttpConnector;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -36,7 +37,7 @@ import org.eclipse.jetty.util.log.Logger;
*
* @author athena
*/
public class InheritedChannelConnector extends SelectChannelConnector
public class InheritedChannelConnector extends ChannelHttpConnector
{
private static final Logger LOG = Log.getLogger(InheritedChannelConnector.class);

View File

@ -25,13 +25,14 @@ import org.eclipse.jetty.io.NetworkTrafficListener;
import org.eclipse.jetty.io.NetworkTrafficSelectChannelEndPoint;
import org.eclipse.jetty.io.SelectChannelEndPoint;
import org.eclipse.jetty.io.SelectorManager;
import org.eclipse.jetty.server.ChannelHttpConnector;
/**
* <p>A specialized version of {@link SelectChannelConnector} that supports {@link NetworkTrafficListener}s.</p>
* <p>A specialized version of {@link ChannelHttpConnector} that supports {@link NetworkTrafficListener}s.</p>
* <p>{@link NetworkTrafficListener}s can be added and removed dynamically before and after this connector has
* been started without causing {@link ConcurrentModificationException}s.</p>
*/
public class NetworkTrafficSelectChannelConnector extends SelectChannelConnector
public class NetworkTrafficSelectChannelConnector extends ChannelHttpConnector
{
private final List<NetworkTrafficListener> listeners = new CopyOnWriteArrayList<NetworkTrafficListener>();
@ -52,7 +53,7 @@ public class NetworkTrafficSelectChannelConnector extends SelectChannelConnector
}
@Override
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey key) throws IOException
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectorManager.ManagedSelector selectSet, SelectionKey key) throws IOException
{
NetworkTrafficSelectChannelEndPoint endPoint = new NetworkTrafficSelectChannelEndPoint(channel, selectSet, key, _maxIdleTime, listeners);
endPoint.setAsyncConnection(selectSet.getManager().newConnection(channel,endPoint, key.attachment()));

View File

@ -1,257 +1,8 @@
// ========================================================================
// Copyright (c) 2003-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Executor;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.SelectChannelEndPoint;
import org.eclipse.jetty.io.SelectorManager;
import org.eclipse.jetty.io.SelectorManager.SelectSet;
import org.eclipse.jetty.server.AbstractHttpConnector;
import org.eclipse.jetty.server.HttpConnection;
import org.eclipse.jetty.server.Request;
/* ------------------------------------------------------------------------------- */
/**
* Selecting NIO connector.
* <p>
* This connector uses efficient NIO buffers with a non blocking threading model. Direct NIO buffers
* are used and threads are only allocated to connections with requests. Synchronization is used to
* simulate blocking for the servlet API, and any unflushed content at the end of request handling
* is written asynchronously.
* </p>
* <p>
* This connector is best used when there are a many connections that have idle periods.
* </p>
* <p>
* When used with {@link org.eclipse.jetty.continuation.Continuation}, threadless waits are supported.
* If a filter or servlet returns after calling {@link Continuation#suspend()} or when a
* runtime exception is thrown from a call to {@link Continuation#undispatch()}, Jetty will
* will not send a response to the client. Instead the thread is released and the Continuation is
* placed on the timer queue. If the Continuation timeout expires, or it's
* resume method is called, then the request is again allocated a thread and the request is retried.
* The limitation of this approach is that request content is not available on the retried request,
* thus if possible it should be read after the continuation or saved as a request attribute or as the
* associated object of the Continuation instance.
* </p>
*
* @org.apache.xbean.XBean element="nioConnector" description="Creates an NIO based socket connector"
* @deprecated Use {@link org.eclipse.jetty.server.ChannelHttpConnector}
*/
public class SelectChannelConnector extends AbstractHttpConnector
public class SelectChannelConnector extends org.eclipse.jetty.server.ChannelHttpConnector
{
private SelectorManager _manager;
protected ServerSocketChannel _acceptChannel;
private int _localPort=-1;
/* ------------------------------------------------------------------------------- */
/**
* Constructor.
*
*/
public SelectChannelConnector()
{
_manager.setMaxIdleTime(getMaxIdleTime());
addBean(_manager,true);
setAcceptors(Math.max(1,(Runtime.getRuntime().availableProcessors()+3)/4));
}
/* ------------------------------------------------------------ */
@Override
public void accept(int acceptorID) throws IOException
{
ServerSocketChannel server;
synchronized(this)
{
server = _acceptChannel;
}
if (server!=null && server.isOpen() && _manager.isStarted())
{
SocketChannel channel = server.accept();
channel.configureBlocking(false);
Socket socket = channel.socket();
configure(socket);
_manager.accept(channel);
}
}
/* ------------------------------------------------------------ */
@Override
public void close() throws IOException
{
synchronized(this)
{
if (_acceptChannel != null)
{
removeBean(_acceptChannel);
if (_acceptChannel.isOpen())
_acceptChannel.close();
}
_acceptChannel = null;
_localPort=-2;
}
}
/* ------------------------------------------------------------------------------- */
@Override
public void customize(Request request) throws IOException
{
request.setTimeStamp(System.currentTimeMillis());
super.customize(request);
}
/* ------------------------------------------------------------ */
public SelectorManager getSelectorManager()
{
return _manager;
}
/* ------------------------------------------------------------ */
@Override
public synchronized Object getTransport()
{
return _acceptChannel;
}
/* ------------------------------------------------------------------------------- */
@Override
public int getLocalPort()
{
synchronized(this)
{
return _localPort;
}
}
/* ------------------------------------------------------------ */
@Override
public void open() throws IOException
{
synchronized(this)
{
if (_acceptChannel == null)
{
// Create a new server socket
_acceptChannel = ServerSocketChannel.open();
// Set to blocking mode
_acceptChannel.configureBlocking(true);
// Bind the server socket to the local host and port
_acceptChannel.socket().setReuseAddress(getReuseAddress());
InetSocketAddress addr = getHost()==null?new InetSocketAddress(getPort()):new InetSocketAddress(getHost(),getPort());
_acceptChannel.socket().bind(addr,getAcceptQueueSize());
_localPort=_acceptChannel.socket().getLocalPort();
if (_localPort<=0)
throw new IOException("Server channel not bound");
addBean(_acceptChannel);
}
}
}
/* ------------------------------------------------------------ */
@Override
public void setMaxIdleTime(int maxIdleTime)
{
_manager.setMaxIdleTime(maxIdleTime);
super.setMaxIdleTime(maxIdleTime);
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.server.AbstractConnector#doStart()
*/
@Override
protected void doStart() throws Exception
{
super.doStart();
_manager = new ConnectorSelectorManager(findExecutor(), getAcceptors());
_manager.setMaxIdleTime(getMaxIdleTime());
_manager.start();
}
/* ------------------------------------------------------------ */
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) throws IOException
{
SelectChannelEndPoint endp= new SelectChannelEndPoint(channel,selectSet,key, SelectChannelConnector.this._maxIdleTime);
endp.setAsyncConnection(selectSet.getManager().newConnection(channel,endp, key.attachment()));
return endp;
}
/* ------------------------------------------------------------------------------- */
protected void endPointClosed(AsyncEndPoint endpoint)
{
endpoint.onClose();
connectionClosed(endpoint.getAsyncConnection());
}
/* ------------------------------------------------------------------------------- */
protected AsyncConnection newConnection(SocketChannel channel,final AsyncEndPoint endpoint)
{
return new HttpConnection(SelectChannelConnector.this,endpoint,getServer());
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private final class ConnectorSelectorManager extends SelectorManager
{
private ConnectorSelectorManager(Executor executor, int selectSets)
{
super(executor, selectSets);
}
@Override
protected void endPointClosed(AsyncEndPoint endpoint)
{
SelectChannelConnector.this.endPointClosed(endpoint);
}
@Override
protected void endPointOpened(AsyncEndPoint endpoint)
{
// TODO handle max connections and low resources
connectionOpened(endpoint.getAsyncConnection());
}
@Override
protected void endPointUpgraded(AsyncEndPoint endpoint, AsyncConnection oldConnection)
{
connectionUpgraded(oldConnection,endpoint.getAsyncConnection());
}
@Override
public AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint, Object attachment)
{
return SelectChannelConnector.this.newConnection(channel,endpoint);
}
@Override
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey sKey) throws IOException
{
return SelectChannelConnector.this.newEndPoint(channel,selectSet,sKey);
}
}
}

View File

@ -3,6 +3,7 @@ package org.eclipse.jetty.server.ssl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;

View File

@ -15,6 +15,7 @@ package org.eclipse.jetty.server.ssl;
import java.io.IOException;
import java.nio.channels.SocketChannel;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
@ -24,8 +25,8 @@ import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.io.ssl.SslConnection;
import org.eclipse.jetty.server.ChannelHttpConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.component.AggregateLifeCycle;
import org.eclipse.jetty.util.ssl.SslContextFactory;
@ -35,7 +36,7 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
*
* @org.apache.xbean.XBean element="sslConnector" description="Creates an NIO ssl connector"
*/
public class SslSelectChannelConnector extends SelectChannelConnector implements SslConnector
public class SslSelectChannelConnector extends ChannelHttpConnector implements SslConnector
{
private final SslContextFactory _sslContextFactory;
@ -584,7 +585,7 @@ public class SslSelectChannelConnector extends SelectChannelConnector implements
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.server.nio.SelectChannelConnector#doStart()
* @see org.eclipse.jetty.server.ChannelHttpConnector#doStart()
*/
@Override
protected void doStart() throws Exception
@ -608,7 +609,7 @@ public class SslSelectChannelConnector extends SelectChannelConnector implements
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.server.nio.SelectChannelConnector#doStop()
* @see org.eclipse.jetty.server.ChannelHttpConnector#doStop()
*/
@Override
protected void doStop() throws Exception

View File

@ -28,9 +28,9 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.junit.AfterClass;
@ -57,7 +57,7 @@ public class AbstractConnectorTest
_connect = new CyclicBarrier(2);
_server = new Server();
_connector = new SelectChannelConnector()
_connector = new ChannelHttpConnector()
{
public void connectionClosed(AsyncConnection connection)
{

View File

@ -32,7 +32,6 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.junit.AfterClass;
@ -52,7 +51,7 @@ public class AsyncRequestReadTest
public static void startServer() throws Exception
{
server = new Server();
connector = new SelectChannelConnector();
connector = new ChannelHttpConnector();
connector.setMaxIdleTime(10000);
server.addConnector(connector);
server.setHandler(new EmptyHandler());

View File

@ -32,7 +32,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.toolchain.test.Stress;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.Log;
@ -48,7 +47,7 @@ public class AsyncStressTest
protected Server _server = new Server();
protected SuspendHandler _handler = new SuspendHandler();
protected SelectChannelConnector _connector;
protected ChannelHttpConnector _connector;
protected InetAddress _addr;
protected int _port;
protected Random _random = new Random();
@ -68,7 +67,7 @@ public class AsyncStressTest
{
_threads.setMaxThreads(50);
_server.setThreadPool(_threads);
_connector = new SelectChannelConnector();
_connector = new ChannelHttpConnector();
_connector.setMaxIdleTime(120000);
_server.setConnectors(new Connector[]{ _connector });
_server.setHandler(_handler);

View File

@ -1,19 +1,20 @@
package org.eclipse.jetty.server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.log.Log;
public class SelectChannelServer
public class ChannelHttpServer
{
public static void main(String[] s) throws Exception
{
System.setProperty("org.eclipse.jetty.LEVEL","DEBUG");
Log.getRootLogger().setDebugEnabled(true);
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
ChannelHttpConnector connector = new ChannelHttpConnector();
connector.setPort(8080);
server.addConnector(connector);
server.setHandler(new DumpHandler());
server.start();
server.dumpStdErr();
server.join();
}
}

View File

@ -93,7 +93,7 @@ public class CheckReverseProxyHeadersTest
private void testRequest(String headers, RequestValidator requestValidator) throws Exception
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
LocalHttpConnector connector = new LocalHttpConnector();
// Activate reverse proxy headers checking
connector.setForwarded(true);

View File

@ -13,6 +13,10 @@
package org.eclipse.jetty.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.matchers.JUnitMatchers.containsString;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -20,6 +24,7 @@ import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -32,10 +37,6 @@ import org.eclipse.jetty.util.IO;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.matchers.JUnitMatchers.containsString;
public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
{
protected static final int MAX_IDLE_TIME=250;

View File

@ -205,27 +205,28 @@ public class DumpHandler extends AbstractHandler
writer.write(e.toString());
}
writer.write("</pre>");
writer.write("</html>");
writer.write("</pre>\n");
writer.write("</html>\n");
writer.flush();
// commit now
writer.flush();
response.setContentLength(buf.size()+1000);
response.addHeader("Before-Flush",response.isCommitted()?"Committed???":"Not Committed");
buf.writeTo(out);
out.flush();
response.addHeader("After-Flush","These headers should not be seen in the response!!!");
response.addHeader("After-Flush",response.isCommitted()?"Committed":"Not Committed?");
// write remaining content after commit
try
{
buf.writeTo(out);
buf.reset();
writer.flush();
for (int pad=998-buf.size();pad-->0;)
for (int pad=998;pad-->0;)
writer.write(" ");
writer.write("\015\012");
writer.write("\r\n");
writer.flush();
buf.writeTo(out);
response.setHeader("IgnoreMe","ignored");
}
catch(Exception e)
{

View File

@ -46,13 +46,13 @@ public class HttpConnectionTest
private static final Logger LOG = Log.getLogger(HttpConnectionTest.class);
private Server server;
private LocalConnector connector;
private LocalHttpConnector connector;
@Before
public void init() throws Exception
{
server = new Server();
connector = new LocalConnector();
connector = new LocalHttpConnector();
server.addConnector(connector);
connector.setRequestHeaderSize(1024);
connector.setResponseHeaderSize(1024);

View File

@ -8,6 +8,7 @@ import java.nio.ByteBuffer;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.ByteArrayEndPoint;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;

View File

@ -48,7 +48,7 @@ public class LocalAsyncContextTest
protected Connector initConnector()
{
return new LocalConnector();
return new LocalHttpConnector();
}
@After
@ -189,7 +189,7 @@ public class LocalAsyncContextTest
protected String getResponse(String request) throws Exception
{
return ((LocalConnector)_connector).getResponses(request);
return ((LocalHttpConnector)_connector).getResponses(request);
}

View File

@ -0,0 +1,19 @@
package org.eclipse.jetty.server;
public class LocalServer
{
public static void main(String[] s) throws Exception
{
Server server = new Server();
LocalHttpConnector connector = new LocalHttpConnector();
server.addConnector(connector);
server.setHandler(new DumpHandler());
server.start();
server.dumpStdErr();
System.err.println(connector.getResponses("GET / HTTP/1.0\r\n\r\n"));
server.stop();
}
}

View File

@ -39,13 +39,13 @@ import org.junit.Test;
public class RFC2616Test
{
private Server server;
private LocalConnector connector;
private LocalHttpConnector connector;
@Before
public void init() throws Exception
{
server = new Server();
connector = new LocalConnector();
connector = new LocalHttpConnector();
server.addConnector(connector);
ContextHandler vcontext=new ContextHandler();
@ -764,7 +764,7 @@ public class RFC2616Test
}
}
private void checkContentRange(LocalConnector listener, String tname, String path, String reqRanges, int expectedStatus, String expectedRange, String expectedData)
private void checkContentRange(LocalHttpConnector listener, String tname, String path, String reqRanges, int expectedStatus, String expectedRange, String expectedData)
{
try
{

View File

@ -53,14 +53,14 @@ import org.junit.Test;
public class RequestTest
{
private Server _server;
private LocalConnector _connector;
private LocalHttpConnector _connector;
private RequestHandler _handler;
@Before
public void init() throws Exception
{
_server = new Server();
_connector = new LocalConnector();
_connector = new LocalHttpConnector();
_connector.setRequestHeaderSize(512);
_connector.setRequestBufferSize(1024);
_connector.setResponseHeaderSize(512);

View File

@ -37,6 +37,7 @@ import javax.servlet.http.HttpSessionContext;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.io.AsyncConnection;
import org.eclipse.jetty.io.ByteArrayEndPoint;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.handler.AbstractHandler;
@ -55,13 +56,13 @@ import org.junit.Test;
public class ResponseTest
{
private Server server;
private LocalConnector connector;
private LocalHttpConnector connector;
@Before
public void init() throws Exception
{
server = new Server();
connector = new LocalConnector();
connector = new LocalHttpConnector();
server.addConnector(connector);
server.setHandler(new DumpHandler());
server.start();

View File

@ -7,7 +7,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.IO;
import org.junit.Test;
@ -18,7 +17,7 @@ public class SelectChannelAsyncContextTest extends LocalAsyncContextTest
@Override
protected Connector initConnector()
{
return new SelectChannelConnector(){
return new ChannelHttpConnector(){
@Override
public void customize(EndPoint endpoint, Request request) throws IOException
@ -33,7 +32,7 @@ public class SelectChannelAsyncContextTest extends LocalAsyncContextTest
@Override
protected String getResponse(String request) throws Exception
{
SelectChannelConnector connector = (SelectChannelConnector)_connector;
ChannelHttpConnector connector = (ChannelHttpConnector)_connector;
Socket socket = new Socket((String)null,connector.getLocalPort());
socket.getOutputStream().write(request.getBytes("UTF-8"));
return IO.toString(socket.getInputStream());

View File

@ -13,7 +13,6 @@
package org.eclipse.jetty.server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.junit.Before;
@ -26,6 +25,6 @@ public class SelectChannelConnectorCloseTest extends ConnectorCloseTestBase
public void init() throws Exception
{
System.setProperty("org.eclipse.jetty.util.log.DEBUG","true");
startServer(new SelectChannelConnector());
startServer(new ChannelHttpConnector());
}
}

View File

@ -12,7 +12,6 @@
// ========================================================================
package org.eclipse.jetty.server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.junit.BeforeClass;
/**
@ -23,7 +22,7 @@ public class SelectChannelServerTest extends HttpServerTestBase
@BeforeClass
public static void init() throws Exception
{
startServer(new SelectChannelConnector());
startServer(new ChannelHttpConnector());
}
@Override

View File

@ -20,7 +20,6 @@ import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.IO;
import org.junit.BeforeClass;
@ -32,7 +31,7 @@ public class SelectChannelTimeoutTest extends ConnectorTimeoutTest
@BeforeClass
public static void init() throws Exception
{
SelectChannelConnector connector = new SelectChannelConnector();
ChannelHttpConnector connector = new ChannelHttpConnector();
connector.setMaxIdleTime(MAX_IDLE_TIME); // 250 msec max idle
startServer(connector);
}
@ -94,7 +93,7 @@ public class SelectChannelTimeoutTest extends ConnectorTimeoutTest
private String getResponse(String request) throws UnsupportedEncodingException, IOException, InterruptedException
{
SelectChannelConnector connector = (SelectChannelConnector)_connector;
ChannelHttpConnector connector = (ChannelHttpConnector)_connector;
Socket socket = new Socket((String)null,connector.getLocalPort());
socket.setSoTimeout(10 * MAX_IDLE_TIME);
socket.getOutputStream().write(request.getBytes("UTF-8"));

View File

@ -29,7 +29,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.toolchain.test.OS;
import org.eclipse.jetty.toolchain.test.Stress;
import org.eclipse.jetty.util.BlockingArrayQueue;
@ -48,7 +47,7 @@ public class StressTest
private static QueuedThreadPool _threads;
private static Server _server;
private static SelectChannelConnector _connector;
private static ChannelHttpConnector _connector;
private static final AtomicInteger _handled=new AtomicInteger(0);
private static final ConcurrentLinkedQueue[] _latencies= {
new ConcurrentLinkedQueue<Long>(),
@ -90,7 +89,7 @@ public class StressTest
_server = new Server();
_server.setThreadPool(_threads);
_connector = new SelectChannelConnector();
_connector = new ChannelHttpConnector();
_connector.setAcceptors(1);
_connector.setAcceptQueueSize(5000);
_connector.setMaxIdleTime(30000);
@ -223,7 +222,7 @@ public class StressTest
{
System.err.println("STALLED!!!");
System.err.println(_server.getThreadPool().toString());
((SelectChannelConnector)(_server.getConnectors()[0])).dump();
((ChannelHttpConnector)(_server.getConnectors()[0])).dump();
Thread.sleep(5000);
System.exit(1);
}

View File

@ -13,10 +13,10 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jetty.server.ChannelHttpConnector;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.junit.AfterClass;
/**
@ -41,7 +41,7 @@ public abstract class AbstractConnectHandlerTest
protected static void startProxy() throws Exception
{
proxy = new Server();
proxyConnector = new SelectChannelConnector();
proxyConnector = new ChannelHttpConnector();
proxy.addConnector(proxyConnector);
proxy.setHandler(new ConnectHandler());
proxy.start();

View File

@ -20,8 +20,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.ChannelHttpConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.toolchain.test.OS;
import org.junit.BeforeClass;
import org.junit.Test;
@ -34,7 +34,7 @@ public class ConnectHandlerTest extends AbstractConnectHandlerTest
@BeforeClass
public static void init() throws Exception
{
startServer(new SelectChannelConnector(), new ServerHandler());
startServer(new ChannelHttpConnector(), new ServerHandler());
startProxy();
}

View File

@ -24,7 +24,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.LocalHttpConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.junit.Test;
@ -35,7 +35,7 @@ public class ContextHandlerCollectionTest
public void testVirtualHostNormalization() throws Exception
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
LocalHttpConnector connector = new LocalHttpConnector();
server.setConnectors(new Connector[]
{ connector });
@ -93,7 +93,7 @@ public class ContextHandlerCollectionTest
public void testVirtualHostWildcard() throws Exception
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
LocalHttpConnector connector = new LocalHttpConnector();
server.setConnectors(new Connector[] { connector });
ContextHandler context = new ContextHandler("/");
@ -133,7 +133,7 @@ public class ContextHandlerCollectionTest
private void checkWildcardHost(boolean succeed, Server server, String[] contextHosts, String[] requestHosts) throws Exception
{
LocalConnector connector = (LocalConnector)server.getConnectors()[0];
LocalHttpConnector connector = (LocalHttpConnector)server.getConnectors()[0];
ContextHandlerCollection handlerCollection = (ContextHandlerCollection)server.getHandler();
ContextHandler context = (ContextHandler)handlerCollection.getHandlers()[0];
IsHandledHandler handler = (IsHandledHandler)context.getHandler();

View File

@ -32,7 +32,7 @@ import javax.servlet.http.HttpServletResponse;
import junit.framework.Assert;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.LocalHttpConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.Resource;
@ -59,7 +59,7 @@ public class ContextHandlerTest
public void testVirtualHostNormalization() throws Exception
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
LocalHttpConnector connector = new LocalHttpConnector();
server.setConnectors(new Connector[]
{ connector });
@ -118,7 +118,7 @@ public class ContextHandlerTest
public void testContextGetContext() throws Exception
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
LocalHttpConnector connector = new LocalHttpConnector();
server.setConnectors(new Connector[] { connector });
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
@ -150,7 +150,7 @@ public class ContextHandlerTest
public void testContextVirtualGetContext() throws Exception
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
LocalHttpConnector connector = new LocalHttpConnector();
server.setConnectors(new Connector[] { connector });
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
@ -197,7 +197,7 @@ public class ContextHandlerTest
public void testVirtualHostWildcard() throws Exception
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
LocalHttpConnector connector = new LocalHttpConnector();
server.setConnectors(new Connector[] { connector });
ContextHandler context = new ContextHandler("/");
@ -338,7 +338,7 @@ public class ContextHandlerTest
{
Server server = new Server();
server.setUncheckedPrintWriter(true);
LocalConnector connector = new LocalConnector();
LocalHttpConnector connector = new LocalHttpConnector();
server.setConnectors(new Connector[] { connector });
ContextHandler context = new ContextHandler("/");
WriterHandler handler = new WriterHandler();
@ -364,7 +364,7 @@ public class ContextHandlerTest
private void checkWildcardHost(boolean succeed, Server server, String[] contextHosts, String[] requestHosts) throws Exception
{
LocalConnector connector = (LocalConnector)server.getConnectors()[0];
LocalHttpConnector connector = (LocalHttpConnector)server.getConnectors()[0];
ContextHandler context = (ContextHandler)server.getHandler();
context.setVirtualHosts(contextHosts);

View File

@ -31,7 +31,7 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationListener;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.LocalHttpConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.junit.After;
@ -41,7 +41,7 @@ import org.junit.Test;
public class StatisticsHandlerTest
{
private Server _server;
private LocalConnector _connector;
private LocalHttpConnector _connector;
private LatchHandler _latchHandler;
private StatisticsHandler _statsHandler;
@ -50,7 +50,7 @@ public class StatisticsHandlerTest
{
_server = new Server();
_connector = new LocalConnector();
_connector = new LocalHttpConnector();
_server.addConnector(_connector);
_connector.setStatsOn(true);

View File

@ -272,7 +272,7 @@ public class SPDYClient
}
@Override
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) throws IOException
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException
{
SessionPromise attachment = (SessionPromise)key.attachment();

View File

@ -39,7 +39,7 @@ import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.StandardByteBufferPool;
import org.eclipse.jetty.io.ssl.SslConnection;
import org.eclipse.jetty.npn.NextProtoNego;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ChannelHttpConnector;
import org.eclipse.jetty.spdy.api.SPDY;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.api.server.ServerSessionFrameListener;
@ -48,7 +48,7 @@ import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.ThreadPool;
public class SPDYServerConnector extends SelectChannelConnector
public class SPDYServerConnector extends ChannelHttpConnector
{
private static final Logger logger = Log.getLogger(SPDYServerConnector.class);