jetty-9 jetty-server passing tests

This commit is contained in:
Greg Wilkins 2012-06-04 17:27:46 +02:00
parent b2a55556b0
commit 96cbd53c47
26 changed files with 507 additions and 930 deletions

View File

@ -54,7 +54,7 @@ public class WebdavListener extends HttpEventListenerWrapper
_exchange=ex;
// We'll only enable webdav if this is a PUT request
if ( HttpMethod.PUT.equalsIgnoreCase( _exchange.getMethod() ) )
if ( HttpMethod.PUT.asString().equalsIgnoreCase( _exchange.getMethod() ) )
{
_webdavEnabled = true;
}

View File

@ -1163,32 +1163,32 @@ public class HttpFields implements Iterable<HttpFields.Field>
}
/* ------------------------------------------------------------ */
public void putTo(ByteBuffer buffer)
public void putTo(ByteBuffer bufferInFillMode)
{
HttpHeader header = HttpHeader.CACHE.get(_name);
if (header!=null)
{
buffer.put(header.getBytesColonSpace());
bufferInFillMode.put(header.getBytesColonSpace());
if (HttpHeaderValue.hasKnownValues(header))
{
HttpHeaderValue value=HttpHeaderValue.CACHE.get(_value);
if (value!=null)
buffer.put(value.toBuffer());
bufferInFillMode.put(value.toBuffer());
else
buffer.put(toSanitisedBytes(_value));
bufferInFillMode.put(toSanitisedBytes(_value));
}
else
buffer.put(toSanitisedBytes(_value));
bufferInFillMode.put(toSanitisedBytes(_value));
}
else
{
buffer.put(toSanitisedBytes(_name));
buffer.put(__colon_space);
buffer.put(toSanitisedBytes(_value));
bufferInFillMode.put(toSanitisedBytes(_name));
bufferInFillMode.put(__colon_space);
bufferInFillMode.put(toSanitisedBytes(_value));
}
BufferUtil.putCRLF(buffer);
BufferUtil.putCRLF(bufferInFillMode);
}
/* ------------------------------------------------------------ */

View File

@ -13,6 +13,7 @@
package org.eclipse.jetty.http;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import org.eclipse.jetty.http.HttpTokens.EndOfContent;
@ -32,7 +33,8 @@ public class HttpGenerator
public static final ResponseInfo CONTINUE_100_INFO = new ResponseInfo(HttpVersion.HTTP_1_1,null,-1,100,null,false);
public static final ResponseInfo PROGRESS_102_INFO = new ResponseInfo(HttpVersion.HTTP_1_1,null,-1,102,null,false);
public final static ResponseInfo RESPONSE_500_INFO =
new ResponseInfo(HttpVersion.HTTP_1_1,new HttpFields(){{put(HttpHeader.CONNECTION,HttpHeaderValue.CLOSE);}},0,HttpStatus.INTERNAL_SERVER_ERROR_500,null,false);
// states
public enum Action { FLUSH, COMPLETE, PREPARE };
@ -432,6 +434,33 @@ public class HttpGenerator
throw new IllegalStateException();
}
}
catch(Exception e)
{
if (header!=null && info instanceof ResponseInfo)
{
if (e instanceof BufferOverflowException)
{
LOG.warn("Response header too large");
LOG.debug(e);
}
else
LOG.warn(e);
_state=State.COMPLETING;
// We were probably trying to generate a header, so let's make it a 500 instead
header.clear();
_persistent=false;
generateResponseLine(RESPONSE_500_INFO,header);
generateHeaders(RESPONSE_500_INFO,header,null,true);
if (buffer!=null)
BufferUtil.clear(buffer);
if (chunk!=null)
BufferUtil.clear(chunk);
if (content!=null)
BufferUtil.clear(content);
return Result.FLUSH;
}
throw e;
}
finally
{
if (pos>=0)

View File

@ -27,7 +27,7 @@ import org.eclipse.jetty.util.log.Logger;
public class HttpParser
{
private static final Logger LOG = Log.getLogger(HttpParser.class);
public static final Logger LOG = Log.getLogger(HttpParser.class);
// States
public enum State
@ -170,6 +170,12 @@ public class HttpParser
return isState(State.CLOSED);
}
/* ------------------------------------------------------------ */
public boolean isIdle()
{
return isState(State.START)||isState(State.END)||isState(State.CLOSED);
}
/* ------------------------------------------------------------ */
public boolean isComplete()
{
@ -375,6 +381,7 @@ public class HttpParser
return_from_parse|=_requestHandler.startRequest(_method,_methodString,_uri,null);
_persistent=false;
_state=State.END;
BufferUtil.clear(buffer);
return_from_parse|=_handler.headerComplete(false,_persistent);
return_from_parse|=_handler.messageComplete(_contentPosition);
}
@ -426,6 +433,7 @@ public class HttpParser
return_from_parse|=_requestHandler.startRequest(_method,_methodString, _uri, null);
_persistent=false;
_state=State.END;
BufferUtil.clear(buffer);
return_from_parse|=_handler.headerComplete(false,_persistent);
return_from_parse|=_handler.messageComplete(_contentPosition);
}
@ -606,7 +614,8 @@ public class HttpParser
// now handle the ch
if (ch == HttpTokens.CARRIAGE_RETURN || ch == HttpTokens.LINE_FEED)
{
_eol=ch;
consumeCRLF(ch,buffer);
_contentPosition=0;
// End of headers!
@ -680,7 +689,7 @@ public class HttpParser
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
_eol=ch;
consumeCRLF(ch,buffer);
_headerString=takeLengthString();
_header=HttpHeader.CACHE.get(_headerString);
_state=State.HEADER;
@ -723,7 +732,7 @@ public class HttpParser
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
_eol=ch;
consumeCRLF(ch,buffer);
_headerString=takeString();
_length=-1;
_header=HttpHeader.CACHE.get(_headerString);
@ -755,7 +764,7 @@ public class HttpParser
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
_eol=ch;
consumeCRLF(ch,buffer);
if (_length > 0)
{
if (_valueString!=null)
@ -794,7 +803,7 @@ public class HttpParser
{
case HttpTokens.CARRIAGE_RETURN:
case HttpTokens.LINE_FEED:
_eol=ch;
consumeCRLF(ch,buffer);
if (_length > 0)
{
if (_valueString!=null)
@ -837,6 +846,17 @@ public class HttpParser
return return_from_parse;
}
/* ------------------------------------------------------------------------------- */
private void consumeCRLF(byte ch, ByteBuffer buffer)
{
_eol=ch;
if (_eol==HttpTokens.CARRIAGE_RETURN && buffer.hasRemaining() && buffer.get(buffer.position())==HttpTokens.LINE_FEED)
{
buffer.get();
_eol=0;
}
}
/* ------------------------------------------------------------------------------- */
/**
* Parse until next Event.

View File

@ -242,7 +242,7 @@ public class ByteArrayEndPoint extends AbstractEndPoint
public int fill(ByteBuffer buffer) throws IOException
{
if (_closed)
throw new IOException("CLOSED");
throw new EofException("CLOSED");
if (_in==null)
shutdownInput();
if (_ishut)

View File

@ -48,7 +48,7 @@ import org.omg.stub.java.rmi._Remote_Stub;
* Connection, that implements TLS encryption using an {@link SSLEngine}.
* <p>
* The connector uses an {@link EndPoint} (like {@link SelectChannelEndPoint}) as
* it's source/sink of encrypted data. It then provides {@link #getAppEndPoint()} to
* it's source/sink of encrypted data. It then provides {@link #getSslEndPoint()} to
* expose a source/sink of unencrypted data to another connection (eg HttpConnection).
*/
public class SslConnection extends AbstractAsyncConnection
@ -81,7 +81,7 @@ public class SslConnection extends AbstractAsyncConnection
return _sslEngine;
}
public AsyncEndPoint getAppEndPoint()
public AsyncEndPoint getSslEndPoint()
{
return _appEndPoint;
}
@ -120,6 +120,13 @@ public class SslConnection extends AbstractAsyncConnection
}
}
/* ------------------------------------------------------------ */
@Override
public void onClose()
{
super.onClose();
}
/* ------------------------------------------------------------ */
@Override
public void onReadable()

View File

@ -60,8 +60,8 @@ public class SelectChannelEndPointSslTest extends SelectChannelEndPointTest
engine.setUseClientMode(false);
SslConnection sslConnection = new SslConnection(__byteBufferPool, _threadPool, endpoint, engine);
AsyncConnection appConnection = super.newConnection(channel,sslConnection.getAppEndPoint());
sslConnection.getAppEndPoint().setAsyncConnection(appConnection);
AsyncConnection appConnection = super.newConnection(channel,sslConnection.getSslEndPoint());
sslConnection.getSslEndPoint().setAsyncConnection(appConnection);
return sslConnection;
}

View File

@ -0,0 +1,309 @@
package org.eclipse.jetty.io;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutionException;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLSocket;
import org.eclipse.jetty.io.SelectChannelEndPointTest.TestConnection;
import org.eclipse.jetty.io.SelectorManager.ManagedSelector;
import org.eclipse.jetty.io.ssl.SslConnection;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class SslConnectionTest
{
private static SslContextFactory __sslCtxFactory=new SslContextFactory();
private static ByteBufferPool __byteBufferPool = new StandardByteBufferPool();
protected volatile AsyncEndPoint _lastEndp;
protected ServerSocketChannel _connector;
protected QueuedThreadPool _threadPool = new QueuedThreadPool();
private int maxIdleTimeout = 600000; // TODO: use smaller value
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)
{
}
@Override
protected void endPointOpened(AsyncEndPoint endpoint)
{
System.err.println("endPointOpened");
endpoint.getAsyncConnection().onOpen();
}
@Override
protected void endPointUpgraded(AsyncEndPoint endpoint, AsyncConnection oldConnection)
{
}
@Override
public AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint, Object attachment)
{
SSLEngine engine = __sslCtxFactory.newSslEngine();
engine.setUseClientMode(false);
SslConnection sslConnection = new SslConnection(__byteBufferPool, _threadPool, endpoint, engine);
AsyncConnection appConnection = new TestConnection(sslConnection.getSslEndPoint());
sslConnection.getSslEndPoint().setAsyncConnection(appConnection);
System.err.println("New Connection "+sslConnection);
return sslConnection;
}
@Override
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException
{
SelectChannelEndPoint endp = new SelectChannelEndPoint(channel,selectSet,key,getMaxIdleTime());
endp.setAsyncConnection(selectSet.getManager().newConnection(channel,endp, key.attachment()));
_lastEndp=endp;
System.err.println("newEndPoint "+endp);
return endp;
}
};
// Must be volatile or the test may fail spuriously
protected volatile int _blockAt=0;
private volatile int _writeCount=1;
@BeforeClass
public static void initSslEngine() throws Exception
{
File keystore = MavenTestingUtils.getTestResourceFile("keystore");
__sslCtxFactory.setKeyStorePath(keystore.getAbsolutePath());
__sslCtxFactory.setKeyStorePassword("storepwd");
__sslCtxFactory.setKeyManagerPassword("keypwd");
__sslCtxFactory.start();
}
@Before
public void startManager() throws Exception
{
_writeCount=1;
_lastEndp=null;
_connector = ServerSocketChannel.open();
_connector.socket().bind(null);
_threadPool.start();
_manager.start();
}
@After
public void stopManager() throws Exception
{
if (_lastEndp.isOpen())
_lastEndp.close();
_manager.stop();
_threadPool.stop();
_connector.close();
}
public class TestConnection extends AbstractAsyncConnection
{
ByteBuffer _in = BufferUtil.allocate(8*1024);
public TestConnection(AsyncEndPoint endp)
{
super(endp,_threadPool);
}
@Override
public void onOpen()
{
System.err.println("onOpen");
scheduleOnReadable();
}
@Override
public void onClose()
{
System.err.println("onClose");
}
@Override
public synchronized void onReadable()
{
AsyncEndPoint endp = getEndPoint();
System.err.println("onReadable "+endp);
try
{
boolean progress=true;
while(progress)
{
progress=false;
// Fill the input buffer with everything available
int filled=endp.fill(_in);
System.err.println("filled="+filled);
while (filled>0)
{
progress=true;
filled=endp.fill(_in);
System.err.println("filled="+filled);
}
// System.err.println(BufferUtil.toDetailString(_in));
// Write everything
int l=_in.remaining();
if (l>0)
{
FutureCallback<Void> blockingWrite= new FutureCallback<>();
endp.write(null,blockingWrite,_in);
blockingWrite.get();
System.err.println("wrote "+l);
}
// are we done?
if (endp.isInputShutdown())
{
System.err.println("shutdown");
endp.shutdownOutput();
}
}
}
catch(InterruptedException|EofException e)
{
SelectChannelEndPoint.LOG.ignore(e);
}
catch(Exception e)
{
SelectChannelEndPoint.LOG.warn(e);
}
finally
{
if (endp.isOpen())
scheduleOnReadable();
}
}
}
protected Socket newClient() throws IOException
{
SSLSocket socket = __sslCtxFactory.newSslSocket();
socket.connect(_connector.socket().getLocalSocketAddress());
return socket;
}
@Test
public void testHelloWorld() throws Exception
{
//Log.getRootLogger().setDebugEnabled(true);
// Log.getRootLogger().setDebugEnabled(true);
Socket client = newClient();
System.err.println("client="+client);
client.setSoTimeout(600000); // TODO: restore to smaller value
SocketChannel server = _connector.accept();
server.configureBlocking(false);
_manager.accept(server);
client.getOutputStream().write("HelloWorld".getBytes("UTF-8"));
System.err.println("wrote");
byte[] buffer = new byte[1024];
int len = client.getInputStream().read(buffer);
System.err.println(new String(buffer,0,len,"UTF-8"));
client.close();
}
@Test
public void testNasty() throws Exception
{
//Log.getRootLogger().setDebugEnabled(true);
// Log.getRootLogger().setDebugEnabled(true);
final Socket client = newClient();
System.err.println("client="+client);
client.setSoTimeout(600000); // TODO: restore to smaller value
SocketChannel server = _connector.accept();
server.configureBlocking(false);
_manager.accept(server);
new Thread()
{
public void run()
{
try
{
while(true)
{
byte[] buffer = new byte[1024];
int len = client.getInputStream().read(buffer);
if (len<0)
{
System.err.println("===");
return;
}
System.err.println(new String(buffer,0,len,"UTF-8"));
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}.start();
for (int i=0;i<1000000;i++)
{
client.getOutputStream().write(("HelloWorld "+i+"\n").getBytes("UTF-8"));
System.err.println("wrote");
if (i%1000==0)
Thread.sleep(10);
}
Thread.sleep(20000);
client.close();
}
}

View File

@ -56,6 +56,7 @@ public abstract class HttpChannel
{
private static final Logger LOG = Log.getLogger(HttpChannel.class);
private static final ThreadLocal<HttpChannel> __currentChannel = new ThreadLocal<HttpChannel>();
/* ------------------------------------------------------------ */
@ -408,7 +409,7 @@ public abstract class HttpChannel
_in.consumeAll();
}
catch(IOException e)
catch(Exception e)
{
LOG.warn(e);
}
@ -536,13 +537,10 @@ public abstract class HttpChannel
_request.setTimeStamp(System.currentTimeMillis());
_request.setMethod(httpMethod,method);
System.err.printf("%s %s %s%n",method,uri,version);
if (httpMethod==HttpMethod.CONNECT)
_uri.parseConnect(uri);
else
_uri.parse(uri);
System.err.printf("%s%n",_uri.getDecodedPath());
_request.setUri(_uri);
_request.setPathInfo(_uri.getDecodedPath());
_version=version==null?HttpVersion.HTTP_0_9:version;

View File

@ -140,11 +140,7 @@ public class HttpConnection extends AbstractAsyncConnection
_generator.reset();
_channel.reset();
_httpInput.recycle();
if (_requestBuffer!=null && !_requestBuffer.hasRemaining())
{
_bufferPool.release(_requestBuffer);
_requestBuffer=null;
}
releaseRequestBuffer();
if (_responseHeader!=null && !_responseHeader.hasRemaining())
{
_bufferPool.release(_responseHeader);
@ -204,7 +200,7 @@ public class HttpConnection extends AbstractAsyncConnection
* @see org.eclipse.jetty.io.AbstractAsyncConnection#onReadable()
*/
@Override
public void onReadable()
public synchronized void onReadable()
{
LOG.debug("{} onReadable {}",this,_channel.isIdle());
@ -255,7 +251,6 @@ public class HttpConnection extends AbstractAsyncConnection
}
else
{
System.err.println("HB="+_headerBytes);
_headerBytes+=filled;
}
}
@ -263,6 +258,9 @@ public class HttpConnection extends AbstractAsyncConnection
// Parse the buffer
if (_parser.parseNext(_requestBuffer))
{
// For most requests, there will not be a body, so we can try to recycle the buffer now
releaseRequestBuffer();
_headerBytes=0;
// The parser returned true, which indicates the channel is ready
// to handle a request. Call the channel and this will either handle the
@ -275,7 +273,7 @@ public class HttpConnection extends AbstractAsyncConnection
// Return if the channel is still processing the request
if (_channel.isSuspended())
{
// release buffer if all input has been consumed
// release buffer if no input being held
if (_httpInput.available()==0)
releaseRequestBuffer();
return;
@ -290,13 +288,15 @@ public class HttpConnection extends AbstractAsyncConnection
}
else if (_headerBytes>= _connector.getRequestHeaderSize())
{
_parser.reset();
_parser.close();
_channel.getEventHandler().badMessage(HttpStatus.REQUEST_ENTITY_TOO_LARGE_413,null);
}
}
}
catch(Exception e)
{
if (_parser.isClosed())
if (_parser.isIdle())
LOG.debug(e);
else
LOG.warn(this.toString(),e);
@ -387,7 +387,7 @@ public class HttpConnection extends AbstractAsyncConnection
@Override
protected boolean commitError(int status, String reason, String content)
protected synchronized boolean commitError(int status, String reason, String content)
{
if (!super.commitError(status,reason,content))
{
@ -408,7 +408,7 @@ public class HttpConnection extends AbstractAsyncConnection
}
@Override
protected void completed()
protected synchronized void completed()
{
// This is called by HttpChannel#process when it knows that it's handling of the request/response cycle
// is complete. This may be in the original thread dispatched to the connection that has called process from
@ -582,7 +582,9 @@ public class HttpConnection extends AbstractAsyncConnection
{
try
{
if (_generator.isCommitted() || BufferUtil.hasContent(_responseBuffer))
if (_generator.isCommitted())
throw new IllegalStateException("committed");
if (BufferUtil.hasContent(_responseBuffer))
throw new IllegalStateException("!empty");
if (_generator.isComplete())
throw new EofException();

View File

@ -232,8 +232,8 @@ public class Request implements HttpServletRequest
{
content_type = HttpFields.valueParameters(content_type,null);
if (MimeTypes.Type.FORM_ENCODED.is(content_type) && _inputState == __NONE
&& (HttpMethod.POST.equals(getMethod()) || HttpMethod.PUT.equals(getMethod())))
if (MimeTypes.Type.FORM_ENCODED.is(content_type) && _inputState == __NONE &&
(HttpMethod.POST.is(getMethod()) || HttpMethod.PUT.is(getMethod())))
{
int content_length = getContentLength();
if (content_length != 0)

View File

@ -87,7 +87,7 @@ public class DefaultHandler extends AbstractHandler
String method=request.getMethod();
// little cheat for common request
if (_serveIcon && _favicon!=null && method.equals(HttpMethod.GET) && request.getRequestURI().equals("/favicon.ico"))
if (_serveIcon && _favicon!=null && HttpMethod.GET.is(method) && request.getRequestURI().equals("/favicon.ico"))
{
if (request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.toString())==_faviconModified)
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
@ -104,7 +104,7 @@ public class DefaultHandler extends AbstractHandler
}
if (!_showContexts || !method.equals(HttpMethod.GET) || !request.getRequestURI().equals("/"))
if (!_showContexts || !HttpMethod.GET.is(method) || !request.getRequestURI().equals("/"))
{
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;

View File

@ -48,7 +48,7 @@ public class ErrorHandler extends AbstractHandler
{
baseRequest.setHandled(true);
String method = request.getMethod();
if(!method.equals(HttpMethod.GET) && !method.equals(HttpMethod.POST) && !method.equals(HttpMethod.HEAD))
if(!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.is(method))
return;
response.setContentType(MimeTypes.Type.TEXT_HTML_8859_1.asString());
if (_cacheControl!=null)

View File

@ -352,9 +352,9 @@ public class ResourceHandler extends HandlerWrapper
boolean skipContentBody = false;
if(!HttpMethod.GET.equals(request.getMethod()))
if(!HttpMethod.GET.is(request.getMethod()))
{
if(!HttpMethod.HEAD.equals(request.getMethod()))
if(!HttpMethod.HEAD.is(request.getMethod()))
{
//try another handler
super.handle(target, baseRequest, request, response);

View File

@ -538,8 +538,8 @@ public class SslSelectChannelConnector extends SelectChannelConnector implements
{
SSLEngine engine = createSSLEngine(channel);
SslConnection connection = newSslConnection(endpoint, engine);
AsyncConnection delegate = newPlainConnection(channel, connection.getAppEndPoint());
connection.getAppEndPoint().setAsyncConnection(delegate);
AsyncConnection delegate = newPlainConnection(channel, connection.getSslEndPoint());
connection.getSslEndPoint().setAsyncConnection(delegate);
return connection;
}
catch (IOException e)

View File

@ -339,10 +339,9 @@ public class HttpConnectionTest
"\n"+
"abcdefghij\n";
Logger logger=null;
try
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(true);
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(true);
response=connector.getResponses(requests);
offset = checkContains(response,offset,"HTTP/1.1 500");
offset = checkContains(response,offset,"Connection: close");
@ -350,7 +349,7 @@ public class HttpConnectionTest
}
finally
{
((StdErrLog)Log.getLogger(HttpConnection.class)).setHideStacks(false);
((StdErrLog)Log.getLogger(HttpChannel.class)).setHideStacks(false);
}
}
@ -487,6 +486,53 @@ public class HttpConnectionTest
}
}
@Test
public void testOversizedResponse2() throws Exception
{
String str = "thisisastringthatshouldreachover1kbytes-";
for (int i=0;i<500;i++)
str+="xxxxxxxxxxxx";
final String longstr = str;
String response = null;
server.stop();
server.setHandler(new DumpHandler()
{
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
response.setHeader(HttpHeader.CONTENT_TYPE.toString(),MimeTypes.Type.TEXT_HTML.toString());
response.setHeader("LongStr", longstr);
PrintWriter writer = response.getWriter();
writer.write("<html><h1>FOO</h1></html>");
writer.flush();
if (!writer.checkError())
throw new RuntimeException("SHOULD NOT GET HERE");
response.flushBuffer();
}
});
server.start();
try
{
int offset = 0;
response = connector.getResponses("GET / HTTP/1.1\n"+
"Host: localhost\n" +
"\015\012"
);
checkContains(response, offset, "HTTP/1.1 500");
}
catch(Exception e)
{
e.printStackTrace();
if(response != null)
System.err.println(response);
fail("Exception");
}
}
@Test
public void testAsterisk()
{
@ -494,6 +540,7 @@ public class HttpConnectionTest
try
{
((StdErrLog)HttpParser.LOG).setHideStacks(true);
int offset=0;
response=connector.getResponses("OPTIONS * HTTP/1.1\n"+
@ -540,6 +587,10 @@ public class HttpConnectionTest
if (response!=null)
System.err.println(response);
}
finally
{
((StdErrLog)HttpParser.LOG).setHideStacks(false);
}
}

View File

@ -46,6 +46,7 @@ import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
@ -293,6 +294,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
{
points[j]=random.nextInt(bytes.length);
}
System.err.println("points "+points[0]+" "+points[1]);
// Sort the list
Arrays.sort(points);
@ -1088,6 +1090,14 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
avail=in.available();
out.println(avail);
// read remaining no matter what
int b=in.read();
while (b>=0)
{
buf+=(char)b;
b=in.read();
}
out.println(buf);
out.close();
}
@ -1133,9 +1143,9 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// skip header
while(reader.readLine().length()>0);
assertEquals(10,Integer.parseInt(reader.readLine()));
assertThat(Integer.parseInt(reader.readLine()),Matchers.greaterThan(0));
assertEquals(0,Integer.parseInt(reader.readLine()));
assertEquals(20,Integer.parseInt(reader.readLine()));
assertThat(Integer.parseInt(reader.readLine()),Matchers.greaterThan(0));
assertEquals(0,Integer.parseInt(reader.readLine()));
assertEquals("1234567890abcdefghijklmnopqrst",reader.readLine());

View File

@ -42,6 +42,8 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.session.HashSessionManager;
import org.eclipse.jetty.server.session.HashedSession;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
@ -420,6 +422,7 @@ public class RequestTest
{
Handler handler = new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException
{

View File

@ -23,6 +23,7 @@ import java.io.InputStreamReader;
import org.eclipse.jetty.http.HttpContent;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.junit.Test;
@ -240,6 +241,6 @@ public class ResourceCacheTest
if (content==null)
return null;
return content.getIndirectBuffer().toString();
return BufferUtil.toString(content.getIndirectBuffer());
}
}

View File

@ -1,850 +0,0 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SessionIdManager;
import org.eclipse.jetty.server.SessionManager;
import org.junit.Test;
public class SessionHandlerTest
{
@Test
public void testRequestedIdFromCookies()
{
final String cookieName = "SessionId";
final String sessionId = "1234.host";
HttpServletRequest httpRequest = new MockHttpServletRequest()
{
public Cookie[] getCookies()
{
return new Cookie[]
{ new Cookie(cookieName,sessionId) };
}
};
// TODO this probably wont work
Request baseRequest = new Request(null);
baseRequest.setDispatcherType(DispatcherType.REQUEST);
assertEquals(DispatcherType.REQUEST,baseRequest.getDispatcherType());
SessionHandler sessionHandler = new SessionHandler();
sessionHandler.setSessionManager(new MockSessionManager()
{
public SessionCookieConfig getSessionCookieConfig()
{
return new SessionCookieConfig()
{
public String getComment()
{
// TODO Auto-generated method stub
return null;
}
public String getDomain()
{
// TODO Auto-generated method stub
return null;
}
public int getMaxAge()
{
// TODO Auto-generated method stub
return 0;
}
public String getName()
{
return cookieName;
}
public String getPath()
{
// TODO Auto-generated method stub
return null;
}
public boolean isHttpOnly()
{
// TODO Auto-generated method stub
return false;
}
public boolean isSecure()
{
// TODO Auto-generated method stub
return false;
}
public void setComment(String comment)
{
// TODO Auto-generated method stub
}
public void setDomain(String domain)
{
// TODO Auto-generated method stub
}
public void setHttpOnly(boolean httpOnly)
{
// TODO Auto-generated method stub
}
public void setMaxAge(int maxAge)
{
// TODO Auto-generated method stub
}
public void setName(String name)
{
// TODO Auto-generated method stub
}
public void setPath(String path)
{
// TODO Auto-generated method stub
}
public void setSecure(boolean secure)
{
// TODO Auto-generated method stub
}
};
}
public boolean isUsingCookies()
{
return true;
}
public String getSessionCookie()
{
return cookieName;
}
});
sessionHandler.checkRequestedSessionId(baseRequest,httpRequest);
assertEquals(sessionId,baseRequest.getRequestedSessionId());
assertTrue(baseRequest.isRequestedSessionIdFromCookie());
}
@Test
public void testRequestedIdFromURI()
{
final String parameterName = "sessionid";
final String sessionId = "1234.host";
HttpServletRequest httpRequest = new MockHttpServletRequest()
{
@Override
public String getRequestURI()
{
return "http://www.foo.net/app/action.do;" + parameterName + "=" + sessionId + ";p1=abc;p2=def";
}
};
// TODO this probably wont work
Request baseRequest = new Request(null);
baseRequest.setDispatcherType(DispatcherType.REQUEST);
assertEquals(DispatcherType.REQUEST,baseRequest.getDispatcherType());
SessionHandler sessionHandler = new SessionHandler();
sessionHandler.setSessionManager(new MockSessionManager()
{
@Override
public String getSessionIdPathParameterName()
{
return parameterName;
}
@Override
public String getSessionIdPathParameterNamePrefix()
{
return ";"+parameterName+"=";
}
});
sessionHandler.checkRequestedSessionId(baseRequest,httpRequest);
assertEquals(sessionId,baseRequest.getRequestedSessionId());
assertFalse(baseRequest.isRequestedSessionIdFromCookie());
}
/**
* Mock class for HttpServletRequest interface.
*/
@SuppressWarnings("unchecked")
private class MockHttpServletRequest implements HttpServletRequest
{
public String getRequestURI()
{
return null;
}
public Cookie[] getCookies()
{
return null;
}
public String getAuthType()
{
return null;
}
public String getContextPath()
{
return null;
}
public long getDateHeader(String name)
{
return 0;
}
public String getHeader(String name)
{
return null;
}
public Enumeration getHeaderNames()
{
return null;
}
public Enumeration getHeaders(String name)
{
return null;
}
public int getIntHeader(String name)
{
return 0;
}
public String getMethod()
{
return null;
}
public String getPathInfo()
{
return null;
}
public String getPathTranslated()
{
return null;
}
public String getQueryString()
{
return null;
}
public String getRemoteUser()
{
return null;
}
public StringBuffer getRequestURL()
{
return null;
}
public String getRequestedSessionId()
{
return null;
}
public String getServletPath()
{
return null;
}
public HttpSession getSession()
{
return null;
}
public HttpSession getSession(boolean create)
{
return null;
}
public Principal getUserPrincipal()
{
return null;
}
public boolean isRequestedSessionIdFromCookie()
{
return false;
}
public boolean isRequestedSessionIdFromURL()
{
return false;
}
public boolean isRequestedSessionIdFromUrl()
{
return false;
}
public boolean isRequestedSessionIdValid()
{
return false;
}
public boolean isUserInRole(String role)
{
return false;
}
public Object getAttribute(String name)
{
return null;
}
public Enumeration getAttributeNames()
{
return null;
}
public String getCharacterEncoding()
{
return null;
}
public int getContentLength()
{
return 0;
}
public String getContentType()
{
return null;
}
public ServletInputStream getInputStream() throws IOException
{
return null;
}
public String getLocalAddr()
{
return null;
}
public String getLocalName()
{
return null;
}
public int getLocalPort()
{
return 0;
}
public Locale getLocale()
{
return null;
}
public Enumeration getLocales()
{
return null;
}
public String getParameter(String name)
{
return null;
}
public Map getParameterMap()
{
return null;
}
public Enumeration getParameterNames()
{
return null;
}
public String[] getParameterValues(String name)
{
return null;
}
public String getProtocol()
{
return null;
}
public BufferedReader getReader() throws IOException
{
return null;
}
public String getRealPath(String path)
{
return null;
}
public String getRemoteAddr()
{
return null;
}
public String getRemoteHost()
{
return null;
}
public int getRemotePort()
{
return 0;
}
public RequestDispatcher getRequestDispatcher(String path)
{
return null;
}
public String getScheme()
{
return null;
}
public String getServerName()
{
return null;
}
public int getServerPort()
{
return 0;
}
public boolean isSecure()
{
return false;
}
public void removeAttribute(String name)
{
}
public void setAttribute(String name, Object o)
{
}
public void setCharacterEncoding(String env) throws UnsupportedEncodingException
{
}
/**
* @see javax.servlet.http.HttpServletRequest#authenticate(javax.servlet.http.HttpServletResponse)
*/
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException
{
// TODO Auto-generated method stub
return false;
}
/**
* @see javax.servlet.http.HttpServletRequest#getPart(java.lang.String)
*/
public Part getPart(String name) throws IOException, ServletException
{
// TODO Auto-generated method stub
return null;
}
/**
* @see javax.servlet.http.HttpServletRequest#getParts()
*/
public Collection<Part> getParts() throws IOException, ServletException
{
// TODO Auto-generated method stub
return null;
}
/**
* @see javax.servlet.http.HttpServletRequest#login(java.lang.String, java.lang.String)
*/
public void login(String username, String password) throws ServletException
{
// TODO Auto-generated method stub
}
/**
* @see javax.servlet.http.HttpServletRequest#logout()
*/
public void logout() throws ServletException
{
// TODO Auto-generated method stub
}
/**
* @see javax.servlet.ServletRequest#getAsyncContext()
*/
public AsyncContext getAsyncContext()
{
// TODO Auto-generated method stub
return null;
}
/**
* @see javax.servlet.ServletRequest#getDispatcherType()
*/
public DispatcherType getDispatcherType()
{
// TODO Auto-generated method stub
return null;
}
/**
* @see javax.servlet.ServletRequest#getServletContext()
*/
public ServletContext getServletContext()
{
// TODO Auto-generated method stub
return null;
}
/**
* @see javax.servlet.ServletRequest#isAsyncStarted()
*/
public boolean isAsyncStarted()
{
// TODO Auto-generated method stub
return false;
}
/**
* @see javax.servlet.ServletRequest#isAsyncSupported()
*/
public boolean isAsyncSupported()
{
// TODO Auto-generated method stub
return false;
}
/**
* @see javax.servlet.ServletRequest#startAsync()
*/
public AsyncContext startAsync() throws IllegalStateException
{
// TODO Auto-generated method stub
return null;
}
/**
* @see javax.servlet.ServletRequest#startAsync(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
*/
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException
{
// TODO Auto-generated method stub
return null;
}
}
/**
* Mock class for SessionManager interface.
*/
private class MockSessionManager implements SessionManager
{
public HttpCookie access(HttpSession session, boolean secure)
{
return null;
}
public void addEventListener(EventListener listener)
{
}
public void clearEventListeners()
{
}
public void complete(HttpSession session)
{
}
public String getClusterId(HttpSession session)
{
return null;
}
public boolean getHttpOnly()
{
return false;
}
public HttpSession getHttpSession(String id)
{
return null;
}
public SessionIdManager getSessionIdManager()
{
return null;
}
public int getMaxCookieAge()
{
return 0;
}
public int getMaxInactiveInterval()
{
return 0;
}
public SessionIdManager getMetaManager()
{
return null;
}
public String getNodeId(HttpSession session)
{
return null;
}
public boolean getSecureCookies()
{
return false;
}
public HttpCookie getSessionCookie(HttpSession session, String contextPath, boolean requestIsSecure)
{
return null;
}
public String getSessionCookie()
{
return null;
}
public String getSessionDomain()
{
return null;
}
public String getSessionIdPathParameterName()
{
return null;
}
public String getSessionIdPathParameterNamePrefix()
{
return null;
}
public String getSessionPath()
{
return null;
}
public boolean isUsingCookies()
{
return false;
}
public boolean isValid(HttpSession session)
{
return false;
}
public HttpSession newHttpSession(HttpServletRequest request)
{
return null;
}
public void removeEventListener(EventListener listener)
{
}
public void setSessionIdManager(SessionIdManager idManager)
{
}
public void setMaxCookieAge(int maxCookieAge)
{
}
public void setMaxInactiveInterval(int seconds)
{
}
public void setSessionCookie(String cookieName)
{
}
public void setSessionDomain(String domain)
{
}
public void setSessionHandler(SessionHandler handler)
{
}
public void setSessionIdPathParameterName(String parameterName)
{
}
public void setSessionPath(String path)
{
}
public void addLifeCycleListener(Listener listener)
{
}
public boolean isFailed()
{
return false;
}
public boolean isRunning()
{
return false;
}
public boolean isStarted()
{
return false;
}
public boolean isStarting()
{
return false;
}
public boolean isStopped()
{
return false;
}
public boolean isStopping()
{
return false;
}
public void removeLifeCycleListener(Listener listener)
{
}
public void start() throws Exception
{
}
public void stop() throws Exception
{
}
/**
* @see org.eclipse.jetty.server.SessionManager#getDefaultSessionTrackingModes()
*/
public Set<SessionTrackingMode> getDefaultSessionTrackingModes()
{
// TODO Auto-generated method stub
return null;
}
/**
* @see org.eclipse.jetty.server.SessionManager#getEffectiveSessionTrackingModes()
*/
public Set<SessionTrackingMode> getEffectiveSessionTrackingModes()
{
// TODO Auto-generated method stub
return null;
}
/**
* @see org.eclipse.jetty.server.SessionManager#getSessionCookieConfig()
*/
public SessionCookieConfig getSessionCookieConfig()
{
return null;
}
/**
* @see org.eclipse.jetty.server.SessionManager#isUsingURLs()
*/
public boolean isUsingURLs()
{
// TODO Auto-generated method stub
return false;
}
/**
* @see org.eclipse.jetty.server.SessionManager#setSessionTrackingModes(java.util.Set)
*/
public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes)
{
// TODO Auto-generated method stub
}
private boolean _checkRemote=false;
public boolean isCheckingRemoteSessionIdEncoding()
{
return _checkRemote;
}
public void setCheckingRemoteSessionIdEncoding(boolean remote)
{
_checkRemote=remote;
}
public void changeSessionIdOnAuthentication(HttpServletRequest request, HttpServletResponse response)
{
}
}
}

View File

@ -50,7 +50,9 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@ -81,11 +83,12 @@ public class SSLEngineTest
private static final int BODY_SIZE=300;
private static Server server;
private static SslSelectChannelConnector connector;
private Server server;
private SslSelectChannelConnector connector;
@BeforeClass
public static void startServer() throws Exception
@Before
public void startServer() throws Exception
{
server=new Server();
connector=new SslSelectChannelConnector();
@ -101,20 +104,20 @@ public class SSLEngineTest
server.setConnectors(new Connector[]{connector });
server.setHandler(new HelloWorldHandler());
server.start();
}
@AfterClass
public static void stopServer() throws Exception
@After
public void stopServer() throws Exception
{
server.stop();
server.join();
}
@Test
@Ignore
public void testBigResponse() throws Exception
{
server.start();
SSLContext ctx=SSLContext.getInstance("TLS");
ctx.init(null,SslContextFactory.TRUST_ALL_CERTS,new java.security.SecureRandom());
@ -138,11 +141,12 @@ public class SSLEngineTest
}
@Test
@Ignore
public void testRequestJettyHttps() throws Exception
{
final int loops=10;
final int numConns=10;
server.start();
final int loops=20;
final int numConns=20;
Socket[] client=new Socket[numConns];
@ -183,7 +187,7 @@ public class SSLEngineTest
// Read the response.
String responses=readResponse(client[i]);
// Check the response
assertEquals(String.format("responses %d %d",l,i),RESPONSE0+RESPONSE0+RESPONSE1,responses);
assertEquals(String.format("responses loop=%d connection=%d",l,i),RESPONSE0+RESPONSE0+RESPONSE1,responses);
}
}
finally
@ -205,10 +209,8 @@ public class SSLEngineTest
}
@Test
@Ignore
public void testServletPost() throws Exception
public void testURLConnectionChunkedPost() throws Exception
{
stopServer();
StreamHandler handler = new StreamHandler();
server.setHandler(handler);

View File

@ -82,11 +82,6 @@ public class SelectChannelServerSslTest extends HttpServerTestBase
}
}
public void testRequest2Fragments() throws Exception
{
super.testRequest2Fragments();
}
@Test
public void testRequest2FixedFragments() throws Exception
{

View File

@ -661,7 +661,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
{
try
{
if (!request.getMethod().equals(HttpMethods.HEAD) )
if (!HttpMethods.HEAD.is(request.getMethod()))
{
String ifms=request.getHeader(HttpHeaders.IF_MODIFIED_SINCE);
if (ifms!=null)

View File

@ -62,7 +62,7 @@ public class ErrorPageErrorHandler extends ErrorHandler
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
String method = request.getMethod();
if(!method.equals(HttpMethods.GET) && !method.equals(HttpMethods.POST) && !method.equals(HttpMethods.HEAD))
if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.isMethod())
{
AbstractHttpConnection.getCurrentConnection().getRequest().setHandled(true);
return;

View File

@ -327,7 +327,7 @@ public class SPDYClient
}
};
endPoint.setAsyncConnection(sslConnection);
AsyncEndPoint sslEndPoint = sslConnection.getAppEndPoint();
AsyncEndPoint sslEndPoint = sslConnection.getSslEndPoint();
sslEndPointRef.set(sslEndPoint);
// Instances of the ClientProvider inner class strong reference the

View File

@ -190,7 +190,7 @@ public class SPDYServerConnector extends SelectChannelConnector
}
};
endPoint.setAsyncConnection(sslConnection);
AsyncEndPoint sslEndPoint = sslConnection.getAppEndPoint();
AsyncEndPoint sslEndPoint = sslConnection.getSslEndPoint();
sslEndPointRef.set(sslEndPoint);
// Instances of the ServerProvider inner class strong reference the