First pass to fix #308862.

git-svn-id: svn+ssh://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk@1763 7e9141cc-0065-0410-87d8-b60c137991c4
This commit is contained in:
Simone Bordet 2010-05-12 11:28:48 +00:00
parent 8d9ecd3268
commit 79633ecf96
28 changed files with 1256 additions and 1409 deletions

View File

@ -51,7 +51,7 @@
</execution>
</executions>
<configuration>
<archive>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
@ -80,6 +80,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit4-version}</version>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -4,11 +4,11 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server.nio;
@ -45,20 +45,20 @@ import org.eclipse.jetty.util.thread.Timeout.Task;
* 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.
* 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
* 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 SelectChannelConnector extends AbstractNIOConnector
public class SelectChannelConnector extends AbstractNIOConnector
{
protected ServerSocketChannel _acceptChannel;
private int _lowResourcesConnections;
@ -98,7 +98,7 @@ public class SelectChannelConnector extends AbstractNIOConnector
// TODO handle max connections and low resources
connectionOpened(endpoint.getConnection());
}
@Override
protected void endPointUpgraded(ConnectedEndPoint endpoint, Connection oldConnection)
{
@ -117,23 +117,23 @@ public class SelectChannelConnector extends AbstractNIOConnector
return SelectChannelConnector.this.newEndPoint(channel,selectSet,sKey);
}
};
/* ------------------------------------------------------------------------------- */
/**
* Constructor.
*
*
*/
public SelectChannelConnector()
{
}
/* ------------------------------------------------------------ */
@Override
public void accept(int acceptorID) throws IOException
{
_manager.doSelect(acceptorID);
}
/* ------------------------------------------------------------ */
public void close() throws IOException
{
@ -156,7 +156,7 @@ public class SelectChannelConnector extends AbstractNIOConnector
_localPort=-2;
}
}
/* ------------------------------------------------------------------------------- */
@Override
public void customize(EndPoint endpoint, Request request) throws IOException
@ -166,7 +166,7 @@ public class SelectChannelConnector extends AbstractNIOConnector
request.setTimeStamp(cep.getSelectSet().getNow());
super.customize(endpoint, request);
}
/* ------------------------------------------------------------------------------- */
@Override
public void persist(EndPoint endpoint) throws IOException
@ -210,10 +210,10 @@ public class SelectChannelConnector extends AbstractNIOConnector
_localPort=_acceptChannel.socket().getLocalPort();
if (_localPort<=0)
throw new IOException("Server channel not bound");
// Set to non blocking mode
_acceptChannel.configureBlocking(false);
}
}
}
@ -269,10 +269,10 @@ public class SelectChannelConnector extends AbstractNIOConnector
public void setLowResourcesMaxIdleTime(int lowResourcesMaxIdleTime)
{
_lowResourcesMaxIdleTime=lowResourcesMaxIdleTime;
super.setLowResourcesMaxIdleTime(lowResourcesMaxIdleTime);
super.setLowResourcesMaxIdleTime(lowResourcesMaxIdleTime);
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.server.AbstractConnector#doStart()
@ -296,7 +296,7 @@ public class SelectChannelConnector extends AbstractNIOConnector
*/
@Override
protected void doStop() throws Exception
{
{
super.doStop();
}

View File

@ -15,47 +15,50 @@ package org.eclipse.jetty.server;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationListener;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.session.SessionHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AsyncContextTest extends TestCase
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class AsyncContextTest
{
protected Server _server = new Server();
protected SuspendHandler _handler = new SuspendHandler();
protected LocalConnector _connector;
@Override
protected void setUp() throws Exception
@Before
public void init() throws Exception
{
_connector = new LocalConnector();
_server.setConnectors(new Connector[]{ _connector });
SessionHandler session = new SessionHandler();
session.setHandler(_handler);
_server.setHandler(session);
_server.start();
}
@Override
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
_server.stop();
_server.join();
}
@Test
public void testSuspendResume() throws Exception
{
String response;
_handler.setRead(0);
_handler.setSuspendFor(1000);
_handler.setResumeAfter(-1);
@ -98,7 +101,6 @@ public class AsyncContextTest extends TestCase
_handler.setCompleteAfter(100);
check("COMPLETED",process("wibble"));
_handler.setRead(6);
_handler.setResumeAfter(0);
@ -124,7 +126,7 @@ public class AsyncContextTest extends TestCase
assertTrue(response.contains(content));
}
public synchronized String process(String content) throws Exception
private synchronized String process(String content) throws Exception
{
String request = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n";
@ -144,8 +146,8 @@ public class AsyncContextTest extends TestCase
private long _completeAfter=-1;
public SuspendHandler()
{}
{
}
public int getRead()
{
@ -187,8 +189,6 @@ public class AsyncContextTest extends TestCase
_completeAfter = completeAfter;
}
@Override
public void handle(String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
@ -280,9 +280,7 @@ public class AsyncContextTest extends TestCase
}
}
private static ContinuationListener __asyncListener =
new ContinuationListener()
private static ContinuationListener __asyncListener = new ContinuationListener()
{
public void onComplete(Continuation continuation)
{
@ -293,6 +291,5 @@ public class AsyncContextTest extends TestCase
continuation.setAttribute("TIMEOUT",Boolean.TRUE);
continuation.resume();
}
};
}

View File

@ -4,30 +4,26 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationListener;
import org.eclipse.jetty.server.handler.HandlerWrapper;
@ -35,8 +31,13 @@ import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class AsyncStressTest extends TestCase
import static org.junit.Assert.assertEquals;
public class AsyncStressTest
{
protected Server _server = new Server();
protected SuspendHandler _handler = new SuspendHandler();
@ -46,9 +47,18 @@ public class AsyncStressTest extends TestCase
protected Random _random = new Random();
protected QueuedThreadPool _threads=new QueuedThreadPool();
protected boolean _stress;
private final static String[][] __paths =
{
{"/path","NORMAL"},
{"/path/info","NORMAL"},
{"/path?sleep=<PERIOD>","SLEPT"},
{"/path?suspend=<PERIOD>","TIMEOUT"},
{"/path?suspend=60000&resume=<PERIOD>","RESUMED"},
{"/path?suspend=60000&complete=<PERIOD>","COMPLETED"},
};
@Override
protected void setUp() throws Exception
@Before
public void init() throws Exception
{
_stress= Boolean.getBoolean("STRESS");
_threads.setMaxThreads(50);
@ -62,23 +72,28 @@ public class AsyncStressTest extends TestCase
_addr=InetAddress.getLocalHost();
}
@Override
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
_server.stop();
_server.join();
}
final static String[][] __paths =
@Test
public void testAsync() throws Throwable
{
{"/path","NORMAL"},
{"/path/info","NORMAL"},
{"/path?sleep=<PERIOD>","SLEPT"},
{"/path?suspend=<PERIOD>","TIMEOUT"},
{"/path?suspend=60000&resume=<PERIOD>","RESUMED"},
{"/path?suspend=60000&complete=<PERIOD>","COMPLETED"},
};
public void doConnections(int connections,final int loops) throws Throwable
if (_stress)
{
System.err.println("STRESS!");
doConnections(1600,240);
}
else
{
doConnections(80,80);
}
}
private void doConnections(int connections,final int loops) throws Throwable
{
Socket[] socket = new Socket[connections];
int [][] path = new int[connections][loops];
@ -105,13 +120,13 @@ public class AsyncStressTest extends TestCase
String uri=__paths[p][0].replace("<PERIOD>",Integer.toString(period));
long start=System.currentTimeMillis();
String request =
"GET "+uri+" HTTP/1.1\r\n"+
"Host: localhost\r\n"+
"start: "+start+"\r\n"+
"result: "+__paths[p][1]+"\r\n"+
((l+1<loops)?"":"Connection: close\r\n")+
"\r\n";
String request =
"GET "+uri+" HTTP/1.1\r\n"+
"Host: localhost\r\n"+
"start: "+start+"\r\n"+
"result: "+__paths[p][1]+"\r\n"+
((l+1<loops)?"":"Connection: close\r\n")+
"\r\n";
socket[i].getOutputStream().write(request.getBytes("UTF-8"));
socket[i].getOutputStream().flush();
}
@ -123,7 +138,7 @@ public class AsyncStressTest extends TestCase
System.err.println();
Log.info("Sent "+(loops*__paths.length)+" requests");
String[] results=new String[connections];
for (int i=0;i<connections;i++)
{
@ -137,14 +152,14 @@ public class AsyncStressTest extends TestCase
Log.info("Read "+connections+" connections");
for (int i=0;i<connections;i++)
{
{
int offset=0;
String result=results[i];
for (int l=0;l<loops;l++)
{
String expect = __paths[path[i][l]][1];
expect=expect+" "+expect;
offset=result.indexOf("200 OK",offset)+6;
offset=result.indexOf("\r\n\r\n",offset)+4;
int end=result.indexOf("\n",offset);
@ -155,28 +170,15 @@ public class AsyncStressTest extends TestCase
}
}
public void testAsync() throws Throwable
{
if (_stress)
{
System.err.println("STRESS!");
doConnections(1600,240);
}
else
{
doConnections(80,80);
}
}
private static class SuspendHandler extends HandlerWrapper
{
private final Timer _timer;
public SuspendHandler()
private SuspendHandler()
{
_timer=new Timer();
}
@Override
public void handle(String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
@ -185,9 +187,9 @@ public class AsyncStressTest extends TestCase
long suspend_for=-1;
long resume_after=-1;
long complete_after=-1;
final String uri=baseRequest.getUri().toString();
if (request.getParameter("read")!=null)
read_before=Integer.parseInt(request.getParameter("read"));
if (request.getParameter("sleep")!=null)
@ -198,7 +200,7 @@ public class AsyncStressTest extends TestCase
resume_after=Integer.parseInt(request.getParameter("resume"));
if (request.getParameter("complete")!=null)
complete_after=Integer.parseInt(request.getParameter("complete"));
if (DispatcherType.REQUEST.equals(baseRequest.getDispatcherType()))
{
if (read_before>0)
@ -220,7 +222,7 @@ public class AsyncStressTest extends TestCase
asyncContext.addContinuationListener(__asyncListener);
if (suspend_for>0)
asyncContext.setTimeout(suspend_for);
if (complete_after>0)
{
TimerTask complete = new TimerTask()
@ -242,7 +244,7 @@ public class AsyncStressTest extends TestCase
System.err.println(baseRequest+"=="+br);
System.err.println(uri+"=="+br.getUri());
System.err.println(asyncContext+"=="+br.getAsyncContinuation());
Log.warn(e);
System.exit(1);
}
@ -279,7 +281,7 @@ public class AsyncStressTest extends TestCase
{
asyncContext.dispatch();
}
}
else if (sleep_for>=0)
{
@ -294,14 +296,12 @@ public class AsyncStressTest extends TestCase
response.setStatus(200);
response.getOutputStream().println("SLEPT "+request.getHeader("result"));
baseRequest.setHandled(true);
return;
}
else
{
response.setStatus(200);
response.getOutputStream().println("NORMAL "+request.getHeader("result"));
baseRequest.setHandled(true);
return;
}
}
else if (request.getAttribute("TIMEOUT")!=null)
@ -318,10 +318,9 @@ public class AsyncStressTest extends TestCase
}
}
}
private static ContinuationListener __asyncListener =
new ContinuationListener()
private static ContinuationListener __asyncListener = new ContinuationListener()
{
public void onComplete(Continuation continuation)
{
@ -332,6 +331,5 @@ public class AsyncStressTest extends TestCase
continuation.setAttribute("TIMEOUT",Boolean.TRUE);
continuation.resume();
}
};
}

View File

@ -20,89 +20,92 @@ import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
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.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @version $Revision: 889 $ $Date: 2009-09-14 14:52:16 +1000 (Mon, 14 Sep 2009) $
*/
public class AsyncUploadTest extends TestCase
public class AsyncUploadTest
{
int _total;
public void test() throws Exception
private static Server server;
private static Connector connector;
private static int total;
@BeforeClass
public static void startServer() throws Exception
{
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
server = new Server();
connector = new SelectChannelConnector();
server.addConnector(connector);
server.setHandler(new EmptyHandler());
server.start();
try
{
_total=0;
final Socket socket = new Socket("localhost",connector.getLocalPort());
byte[] content = new byte[16*4096];
Arrays.fill(content, (byte)120);
long start = System.nanoTime();
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\n".getBytes());
out.write("Host: localhost\r\n".getBytes());
out.write(("Content-Length: "+content.length+"\r\n").getBytes());
out.write("Content-Type: bytes\r\n".getBytes());
out.write("Connection: close\r\n".getBytes());
out.write("\r\n".getBytes());
out.flush();
out.write(content,0,4*4096);
Thread.sleep(100);
out.write(content,8192,4*4096);
Thread.sleep(100);
out.write(content,8*4096,content.length-8*4096);
out.flush();
InputStream in = socket.getInputStream();
String response = IO.toString(in);
// System.err.println(response);
assertTrue(response.indexOf("200 OK")>0);
long end = System.nanoTime();
System.err.println("upload time: " + TimeUnit.NANOSECONDS.toMillis(end - start));
assertEquals(content.length,_total);
}
finally
{
server.stop();
}
}
private class EmptyHandler extends AbstractHandler
@AfterClass
public static void stopServer() throws Exception
{
server.stop();
server.join();
}
@Test
public void test() throws Exception
{
final Socket socket = new Socket("localhost",connector.getLocalPort());
byte[] content = new byte[16*4096];
Arrays.fill(content, (byte)120);
long start = System.nanoTime();
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\n".getBytes());
out.write("Host: localhost\r\n".getBytes());
out.write(("Content-Length: "+content.length+"\r\n").getBytes());
out.write("Content-Type: bytes\r\n".getBytes());
out.write("Connection: close\r\n".getBytes());
out.write("\r\n".getBytes());
out.flush();
out.write(content,0,4*4096);
Thread.sleep(100);
out.write(content,8192,4*4096);
Thread.sleep(100);
out.write(content,8*4096,content.length-8*4096);
out.flush();
InputStream in = socket.getInputStream();
String response = IO.toString(in);
// System.err.println(response);
assertTrue(response.indexOf("200 OK")>0);
long end = System.nanoTime();
System.err.println("upload time: " + TimeUnit.NANOSECONDS.toMillis(end - start));
assertEquals(content.length, total);
}
private static class EmptyHandler extends AbstractHandler
{
public void handle(String path, final Request request, HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws IOException, ServletException
{
// System.out.println("path = " + path);
final Continuation continuation = ContinuationSupport.getContinuation(request);
httpResponse.setStatus(500);
request.setHandled(true);
new Thread()
{
@Override
@ -113,20 +116,15 @@ public class AsyncUploadTest extends TestCase
Thread.sleep(100);
InputStream in = request.getInputStream();
byte[] b = new byte[4*4096];
int l;
while((l=in.read(b))>=0)
{
// System.err.println("read "+l);
_total+=l;
}
System.err.println("Read "+_total);
int read;
while((read =in.read(b))>=0)
total += read;
System.err.println("Read "+ total);
}
catch(Exception e)
{
e.printStackTrace();
_total=-1;
total =-1;
}
finally
{
@ -135,16 +133,8 @@ public class AsyncUploadTest extends TestCase
}
}
}.start();
continuation.suspend();
}
}
private class EmptyHostnameVerifier implements HostnameVerifier
{
public boolean verify(String s, SSLSession sslSession)
{
return true;
}
}
}

View File

@ -4,42 +4,31 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Test AbstractConnector#checkForwardedHeaders(EndPoint, Request)
*
*/
public class CheckReverseProxyHeadersTest extends TestCase
public class CheckReverseProxyHeadersTest
{
Server server=new Server();
LocalConnector connector=new LocalConnector();
/**
* Constructor for CheckReverseProxyHeadersTest.
* @param name test case name.
*/
public CheckReverseProxyHeadersTest(String name)
{
super(name);
}
@Test
public void testCheckReverseProxyHeaders() throws Exception
{
// Classic ProxyPass from example.com:80 to localhost:8080
@ -56,7 +45,7 @@ public class CheckReverseProxyHeadersTest extends TestCase
assertEquals("example.com", request.getHeader("Host"));
}
});
// ProxyPass from example.com:81 to localhost:8080
testRequest("Host: localhost:8080\n" +
"X-Forwarded-For: 10.20.30.40\n" +
@ -72,7 +61,7 @@ public class CheckReverseProxyHeadersTest extends TestCase
assertEquals("example.com:81", request.getHeader("Host"));
}
});
// Multiple ProxyPass from example.com:80 to rp.example.com:82 to localhost:8080
testRequest("Host: localhost:8080\n" +
"X-Forwarded-For: 10.20.30.40, 10.0.0.1\n" +
@ -94,21 +83,21 @@ public class CheckReverseProxyHeadersTest extends TestCase
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
// Activate reverse proxy headers checking
connector.setForwarded(true);
server.setConnectors(new Connector[] {connector});
ValidationHandler validationHandler = new ValidationHandler(requestValidator);
server.setHandler(validationHandler);
try
{
server.start();
connector.getResponses("GET / HTTP/1.1\n" + headers + "\n\n");
Error error = validationHandler.getError();
if (error != null)
{
throw error;
@ -137,18 +126,14 @@ public class CheckReverseProxyHeadersTest extends TestCase
*/
private static class ValidationHandler extends AbstractHandler
{
private RequestValidator _requestValidator;
private final RequestValidator _requestValidator;
private Error _error;
/**
* Create the validation handler with a request validator.
* @param requestValidator the request validator.
*/
public ValidationHandler(RequestValidator requestValidator)
private ValidationHandler(RequestValidator requestValidator)
{
_requestValidator = requestValidator;
}
/**
* Retrieve the validation error.
* @return the validation error or <code>null</code> if there was no error.
@ -157,7 +142,7 @@ public class CheckReverseProxyHeadersTest extends TestCase
{
return _error;
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
try

View File

@ -4,11 +4,11 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
@ -16,28 +16,28 @@ package org.eclipse.jetty.server;
import java.net.URLDecoder;
import java.net.URLEncoder;
import junit.framework.TestCase;
import org.eclipse.jetty.http.EncodedHttpURI;
import org.junit.Test;
public class EncodedHttpURITest extends TestCase
import static org.junit.Assert.assertEquals;
public class EncodedHttpURITest
{
public void testNonURIAscii ()
throws Exception
@Test
public void testNonURIAscii() throws Exception
{
String url = "http://www.foo.com/ma\u00F1ana";
byte[] asISO = url.getBytes("ISO-8859-1");
String str = new String(asISO, "ISO-8859-1");
//use a non UTF-8 charset as the encoding and url-escape as per
//http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
String s = URLEncoder.encode(url, "ISO-8859-1");
String s = URLEncoder.encode(url, "ISO-8859-1");
EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
//parse it, using the same encoding
uri.parse(s);
//decode the url encoding
String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
assertEquals(url, d);

View File

@ -21,60 +21,48 @@ package org.eclipse.jetty.server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
*
*
*/
public class HttpConnectionTest extends TestCase
public class HttpConnectionTest
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
private Server server;
private LocalConnector connector;
/**
* Constructor
* @param arg0
*/
public HttpConnectionTest(String arg0)
@Before
public void init() throws Exception
{
super(arg0);
server.setConnectors(new Connector[]{connector});
server = new Server();
connector = new LocalConnector();
server.addConnector(connector);
connector.setHeaderBufferSize(1024);
server.setHandler(new DumpHandler());
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
connector.setHeaderBufferSize(1024);
server.start();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
super.tearDown();
server.stop();
server.join();
}
/* --------------------------------------------------------------- */
@Test
public void testFragmentedChunk()
{
String response=null;
@ -118,7 +106,7 @@ public class HttpConnectionTest extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void testEmpty() throws Exception
{
String response=connector.getResponses("GET /R1 HTTP/1.1\n"+
@ -133,7 +121,7 @@ public class HttpConnectionTest extends TestCase
offset = checkContains(response,offset,"/R1");
}
/* --------------------------------------------------------------- */
@Test
public void testBad() throws Exception
{
String response=connector.getResponses("GET & HTTP/1.1\n"+
@ -163,7 +151,7 @@ public class HttpConnectionTest extends TestCase
}
/* --------------------------------------------------------------- */
@Test
public void testAutoFlush() throws Exception
{
String response=null;
@ -184,7 +172,7 @@ public class HttpConnectionTest extends TestCase
offset = checkContains(response,offset,"12345");
}
/* --------------------------------------------------------------- */
@Test
public void testCharset()
{
@ -246,17 +234,15 @@ public class HttpConnectionTest extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void testUnconsumedError() throws Exception
{
{
String response=null;
String requests=null;
int offset=0;
offset=0;
offset=0;
requests="GET /R1?read=1&error=500 HTTP/1.1\n"+
"Host: localhost\n"+
"Transfer-Encoding: chunked\n"+
@ -280,17 +266,17 @@ public class HttpConnectionTest extends TestCase
offset = checkContains(response,offset,"/R2");
offset = checkContains(response,offset,"encoding=UTF-8");
offset = checkContains(response,offset,"abcdefghij");
}
/* --------------------------------------------------------------- */
@Test
public void testUnconsumedException() throws Exception
{
{
String response=null;
String requests=null;
int offset=0;
offset=0;
offset=0;
requests="GET /R1?read=1&ISE=true HTTP/1.1\n"+
"Host: localhost\n"+
"Transfer-Encoding: chunked\n"+
@ -328,7 +314,8 @@ public class HttpConnectionTest extends TestCase
}
}
public void testConnection ()
@Test
public void testConnection()
{
String response=null;
try
@ -356,6 +343,7 @@ public class HttpConnectionTest extends TestCase
}
}
@Test
public void testOversizedBuffer()
{
String response = null;
@ -381,11 +369,10 @@ public class HttpConnectionTest extends TestCase
}
}
public void testOversizedResponse ()
throws Exception
{
@Test
public void testOversizedResponse() throws Exception
{
String str = "thisisastringthatshouldreachover1kbytes";
for (int i=0;i<400;i++)
str+="xxxxxxxxxxxx";
@ -393,7 +380,7 @@ public class HttpConnectionTest extends TestCase
String response = null;
server.stop();
server.setHandler(new DumpHandler()
{
{
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
try
@ -402,7 +389,7 @@ public class HttpConnectionTest extends TestCase
response.setHeader(HttpHeaders.CONTENT_TYPE,MimeTypes.TEXT_HTML);
response.setHeader("LongStr", longstr);
PrintWriter writer = response.getWriter();
writer.write("<html><h1>FOO</h1></html>");
writer.write("<html><h1>FOO</h1></html>");
writer.flush();
writer.close();
throw new RuntimeException("SHOULD NOT GET HERE");
@ -415,28 +402,28 @@ public class HttpConnectionTest extends TestCase
}
});
server.start();
try
try
{
int offset = 0;
response = connector.getResponses("GET / HTTP/1.1\n"+
"Host: localhost\n" +
"\015\012"
);
offset = checkContains(response, offset, "HTTP/1.1 500");
}
}
catch(Exception e)
{
e.printStackTrace();
if(response != null)
System.err.println(response);
fail("Exception");
fail("Exception");
}
}
@Test
public void testAsterisk()
{
String response = null;
@ -491,7 +478,8 @@ public class HttpConnectionTest extends TestCase
}
}
@Test
public void testCONNECT()
{
String response = null;

View File

@ -4,63 +4,67 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
import junit.framework.TestCase;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.junit.Test;
public class HttpURITest extends TestCase
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class HttpURITest
{
String[][] partial_tests=
{
/* 0*/ {"/path/info",null,null,null,null,"/path/info",null,null,null},
/* 1*/ {"/path/info#fragment",null,null,null,null,"/path/info",null,null,"fragment"},
/* 2*/ {"/path/info?query",null,null,null,null,"/path/info",null,"query",null},
/* 3*/ {"/path/info?query#fragment",null,null,null,null,"/path/info",null,"query","fragment"},
/* 4*/ {"/path/info;param",null,null,null,null,"/path/info","param",null,null},
/* 5*/ {"/path/info;param#fragment",null,null,null,null,"/path/info","param",null,"fragment"},
/* 6*/ {"/path/info;param?query",null,null,null,null,"/path/info","param","query",null},
/* 7*/ {"/path/info;param?query#fragment",null,null,null,null,"/path/info","param","query","fragment"},
/* 8*/ {"//host/path/info",null,"//host","host",null,"/path/info",null,null,null},
/* 9*/ {"//user@host/path/info",null,"//user@host","host",null,"/path/info",null,null,null},
/*10*/ {"//user@host:8080/path/info",null,"//user@host:8080","host","8080","/path/info",null,null,null},
/*11*/ {"//host:8080/path/info",null,"//host:8080","host","8080","/path/info",null,null,null},
/*12*/ {"http:/path/info","http",null,null,null,"/path/info",null,null,null},
/*13*/ {"http:/path/info#fragment","http",null,null,null,"/path/info",null,null,"fragment"},
/*14*/ {"http:/path/info?query","http",null,null,null,"/path/info",null,"query",null},
/*15*/ {"http:/path/info?query#fragment","http",null,null,null,"/path/info",null,"query","fragment"},
/*16*/ {"http:/path/info;param","http",null,null,null,"/path/info","param",null,null},
/*17*/ {"http:/path/info;param#fragment","http",null,null,null,"/path/info","param",null,"fragment"},
/*18*/ {"http:/path/info;param?query","http",null,null,null,"/path/info","param","query",null},
/*19*/ {"http:/path/info;param?query#fragment","http",null,null,null,"/path/info","param","query","fragment"},
/*20*/ {"http://user@host:8080/path/info;param?query#fragment","http","//user@host:8080","host","8080","/path/info","param","query","fragment"},
/*21*/ {"xxxxx://user@host:8080/path/info;param?query#fragment","xxxxx","//user@host:8080","host","8080","/path/info","param","query","fragment"},
/*22*/ {"http:///;?#","http","//",null,null,"/","","",""},
/*23*/ {"/path/info?a=?query",null,null,null,null,"/path/info",null,"a=?query",null},
/*24*/ {"/path/info?a=;query",null,null,null,null,"/path/info",null,"a=;query",null},
/*25*/ {"//host:8080//",null,"//host:8080","host","8080","//",null,null,null},
/*26*/ {"file:///path/info","file","//",null,null,"/path/info",null,null,null},
/*27*/ {"//",null,"//",null,null,null,null,null,null},
private final String[][] partial_tests=
{
/* 0*/ {"/path/info",null,null,null,null,"/path/info",null,null,null},
/* 1*/ {"/path/info#fragment",null,null,null,null,"/path/info",null,null,"fragment"},
/* 2*/ {"/path/info?query",null,null,null,null,"/path/info",null,"query",null},
/* 3*/ {"/path/info?query#fragment",null,null,null,null,"/path/info",null,"query","fragment"},
/* 4*/ {"/path/info;param",null,null,null,null,"/path/info","param",null,null},
/* 5*/ {"/path/info;param#fragment",null,null,null,null,"/path/info","param",null,"fragment"},
/* 6*/ {"/path/info;param?query",null,null,null,null,"/path/info","param","query",null},
/* 7*/ {"/path/info;param?query#fragment",null,null,null,null,"/path/info","param","query","fragment"},
/* 8*/ {"//host/path/info",null,"//host","host",null,"/path/info",null,null,null},
/* 9*/ {"//user@host/path/info",null,"//user@host","host",null,"/path/info",null,null,null},
/*10*/ {"//user@host:8080/path/info",null,"//user@host:8080","host","8080","/path/info",null,null,null},
/*11*/ {"//host:8080/path/info",null,"//host:8080","host","8080","/path/info",null,null,null},
/*12*/ {"http:/path/info","http",null,null,null,"/path/info",null,null,null},
/*13*/ {"http:/path/info#fragment","http",null,null,null,"/path/info",null,null,"fragment"},
/*14*/ {"http:/path/info?query","http",null,null,null,"/path/info",null,"query",null},
/*15*/ {"http:/path/info?query#fragment","http",null,null,null,"/path/info",null,"query","fragment"},
/*16*/ {"http:/path/info;param","http",null,null,null,"/path/info","param",null,null},
/*17*/ {"http:/path/info;param#fragment","http",null,null,null,"/path/info","param",null,"fragment"},
/*18*/ {"http:/path/info;param?query","http",null,null,null,"/path/info","param","query",null},
/*19*/ {"http:/path/info;param?query#fragment","http",null,null,null,"/path/info","param","query","fragment"},
/*20*/ {"http://user@host:8080/path/info;param?query#fragment","http","//user@host:8080","host","8080","/path/info","param","query","fragment"},
/*21*/ {"xxxxx://user@host:8080/path/info;param?query#fragment","xxxxx","//user@host:8080","host","8080","/path/info","param","query","fragment"},
/*22*/ {"http:///;?#","http","//",null,null,"/","","",""},
/*23*/ {"/path/info?a=?query",null,null,null,null,"/path/info",null,"a=?query",null},
/*24*/ {"/path/info?a=;query",null,null,null,null,"/path/info",null,"a=;query",null},
/*25*/ {"//host:8080//",null,"//host:8080","host","8080","//",null,null,null},
/*26*/ {"file:///path/info","file","//",null,null,"/path/info",null,null,null},
/*27*/ {"//",null,"//",null,null,null,null,null,null},
/*28*/ {"/;param",null, null, null,null,"/", "param",null,null},
/*29*/ {"/?x=y",null, null, null,null,"/", null,"x=y",null},
/*30*/ {"/?abc=test",null, null, null,null,"/", null,"abc=test",null},
/*31*/ {"/#fragment",null, null, null,null,"/", null,null,"fragment"},
/*31*/ {"/#fragment",null, null, null,null,"/", null,null,"fragment"},
};
public void testPartialURIs()
throws Exception
@Test
public void testPartialURIs() throws Exception
{
HttpURI uri = new HttpURI(true);
for (int t=0;t<partial_tests.length;t++)
{
uri.parse(partial_tests[t][0].getBytes(),0,partial_tests[t][0].length());
@ -74,39 +78,39 @@ public class HttpURITest extends TestCase
assertEquals(t+" "+partial_tests[t][0],partial_tests[t][8],uri.getFragment());
assertEquals(partial_tests[t][0], uri.toString());
}
}
String[][] path_tests=
{
/* 0*/ {"/path/info",null,null,null,null,"/path/info",null,null,null},
/* 1*/ {"/path/info#fragment",null,null,null,null,"/path/info",null,null,"fragment"},
/* 2*/ {"/path/info?query",null,null,null,null,"/path/info",null,"query",null},
/* 3*/ {"/path/info?query#fragment",null,null,null,null,"/path/info",null,"query","fragment"},
/* 4*/ {"/path/info;param",null,null,null,null,"/path/info","param",null,null},
/* 5*/ {"/path/info;param#fragment",null,null,null,null,"/path/info","param",null,"fragment"},
/* 6*/ {"/path/info;param?query",null,null,null,null,"/path/info","param","query",null},
/* 7*/ {"/path/info;param?query#fragment",null,null,null,null,"/path/info","param","query","fragment"},
/* 8*/ {"//host/path/info",null,null,null,null,"//host/path/info",null,null,null},
/* 9*/ {"//user@host/path/info",null,null,null,null,"//user@host/path/info",null,null,null},
/*10*/ {"//user@host:8080/path/info",null,null,null,null,"//user@host:8080/path/info",null,null,null},
/*11*/ {"//host:8080/path/info",null,null,null,null,"//host:8080/path/info",null,null,null},
/*12*/ {"http:/path/info","http",null,null,null,"/path/info",null,null,null},
/*13*/ {"http:/path/info#fragment","http",null,null,null,"/path/info",null,null,"fragment"},
/*14*/ {"http:/path/info?query","http",null,null,null,"/path/info",null,"query",null},
/*15*/ {"http:/path/info?query#fragment","http",null,null,null,"/path/info",null,"query","fragment"},
/*16*/ {"http:/path/info;param","http",null,null,null,"/path/info","param",null,null},
/*17*/ {"http:/path/info;param#fragment","http",null,null,null,"/path/info","param",null,"fragment"},
/*18*/ {"http:/path/info;param?query","http",null,null,null,"/path/info","param","query",null},
/*19*/ {"http:/path/info;param?query#fragment","http",null,null,null,"/path/info","param","query","fragment"},
/*20*/ {"http://user@host:8080/path/info;param?query#fragment","http","//user@host:8080","host","8080","/path/info","param","query","fragment"},
/*21*/ {"xxxxx://user@host:8080/path/info;param?query#fragment","xxxxx","//user@host:8080","host","8080","/path/info","param","query","fragment"},
/*22*/ {"http:///;?#","http","//",null,null,"/","","",""},
/*23*/ {"/path/info?a=?query",null,null,null,null,"/path/info",null,"a=?query",null},
/*24*/ {"/path/info?a=;query",null,null,null,null,"/path/info",null,"a=;query",null},
/*25*/ {"//host:8080//",null,null,null,null,"//host:8080//",null,null,null},
/*26*/ {"file:///path/info","file","//",null,null,"/path/info",null,null,null},
/*27*/ {"//",null,null,null,null,"//",null,null,null},
private final String[][] path_tests=
{
/* 0*/ {"/path/info",null,null,null,null,"/path/info",null,null,null},
/* 1*/ {"/path/info#fragment",null,null,null,null,"/path/info",null,null,"fragment"},
/* 2*/ {"/path/info?query",null,null,null,null,"/path/info",null,"query",null},
/* 3*/ {"/path/info?query#fragment",null,null,null,null,"/path/info",null,"query","fragment"},
/* 4*/ {"/path/info;param",null,null,null,null,"/path/info","param",null,null},
/* 5*/ {"/path/info;param#fragment",null,null,null,null,"/path/info","param",null,"fragment"},
/* 6*/ {"/path/info;param?query",null,null,null,null,"/path/info","param","query",null},
/* 7*/ {"/path/info;param?query#fragment",null,null,null,null,"/path/info","param","query","fragment"},
/* 8*/ {"//host/path/info",null,null,null,null,"//host/path/info",null,null,null},
/* 9*/ {"//user@host/path/info",null,null,null,null,"//user@host/path/info",null,null,null},
/*10*/ {"//user@host:8080/path/info",null,null,null,null,"//user@host:8080/path/info",null,null,null},
/*11*/ {"//host:8080/path/info",null,null,null,null,"//host:8080/path/info",null,null,null},
/*12*/ {"http:/path/info","http",null,null,null,"/path/info",null,null,null},
/*13*/ {"http:/path/info#fragment","http",null,null,null,"/path/info",null,null,"fragment"},
/*14*/ {"http:/path/info?query","http",null,null,null,"/path/info",null,"query",null},
/*15*/ {"http:/path/info?query#fragment","http",null,null,null,"/path/info",null,"query","fragment"},
/*16*/ {"http:/path/info;param","http",null,null,null,"/path/info","param",null,null},
/*17*/ {"http:/path/info;param#fragment","http",null,null,null,"/path/info","param",null,"fragment"},
/*18*/ {"http:/path/info;param?query","http",null,null,null,"/path/info","param","query",null},
/*19*/ {"http:/path/info;param?query#fragment","http",null,null,null,"/path/info","param","query","fragment"},
/*20*/ {"http://user@host:8080/path/info;param?query#fragment","http","//user@host:8080","host","8080","/path/info","param","query","fragment"},
/*21*/ {"xxxxx://user@host:8080/path/info;param?query#fragment","xxxxx","//user@host:8080","host","8080","/path/info","param","query","fragment"},
/*22*/ {"http:///;?#","http","//",null,null,"/","","",""},
/*23*/ {"/path/info?a=?query",null,null,null,null,"/path/info",null,"a=?query",null},
/*24*/ {"/path/info?a=;query",null,null,null,null,"/path/info",null,"a=;query",null},
/*25*/ {"//host:8080//",null,null,null,null,"//host:8080//",null,null,null},
/*26*/ {"file:///path/info","file","//",null,null,"/path/info",null,null,null},
/*27*/ {"//",null,null,null,null,"//",null,null,null},
/*28*/ {"http://localhost/","http","//localhost","localhost",null,"/",null,null,null},
/*29*/ {"http://localhost:8080/", "http", "//localhost:8080", "localhost","8080","/", null, null,null},
/*30*/ {"http://localhost/?x=y", "http", "//localhost", "localhost",null,"/", null,"x=y",null},
@ -122,13 +126,12 @@ public class HttpURITest extends TestCase
/*40*/ {"http://user@[2001:db8::1]:8080/","http","//user@[2001:db8::1]:8080","[2001:db8::1]","8080","/",null,null,null},
/*41*/ {"*",null,null,null,null,"*",null, null,null}
};
public void testPathURIs()
throws Exception
@Test
public void testPathURIs() throws Exception
{
HttpURI uri = new HttpURI();
for (int t=0;t<path_tests.length;t++)
{
uri.parse(path_tests[t][0].getBytes(),0,path_tests[t][0].length());
@ -142,17 +145,18 @@ public class HttpURITest extends TestCase
assertEquals(t+" "+path_tests[t][0],path_tests[t][8],uri.getFragment());
assertEquals(path_tests[t][0], uri.toString());
}
}
@Test
public void testInvalidAddress() throws Exception
{
assertInvalidURI("http://[ffff::1:8080/", "Invalid URL; no closing ']' -- should throw exception");
assertInvalidURI("**", "only '*', not '**'");
assertInvalidURI("*/", "only '*', not '*/'");
}
public void assertInvalidURI(String invalidURI, String message)
private void assertInvalidURI(String invalidURI, String message)
{
HttpURI uri = new HttpURI();
try
@ -166,38 +170,38 @@ public class HttpURITest extends TestCase
}
}
String[][] encoding_tests=
{
/* 0*/ {"/path/info","/path/info"},
/* 1*/ {"/path/%69nfo","/path/info"},
/* 2*/ {"http://host/path/%69nfo","/path/info"},
/* 3*/ {"http://host/path/%69nf%c2%a4","/path/inf\u00a4"},
private final String[][] encoding_tests=
{
/* 0*/ {"/path/info","/path/info"},
/* 1*/ {"/path/%69nfo","/path/info"},
/* 2*/ {"http://host/path/%69nfo","/path/info"},
/* 3*/ {"http://host/path/%69nf%c2%a4","/path/inf\u00a4"},
};
@Test
public void testEncoded()
{
HttpURI uri = new HttpURI();
for (int t=0;t<encoding_tests.length;t++)
{
uri.parse(encoding_tests[t][0]);
assertEquals(""+t,encoding_tests[t][1],uri.getDecodedPath());
}
}
String[][] connect_tests=
{
/* 0*/ {" localhost:8080 ","localhost","8080"},
/* 1*/ {" 127.0.0.1:8080 ","127.0.0.1","8080"},
/* 2*/ {" [127::0::0::1]:8080 ","[127::0::0::1]","8080"},
/* 3*/ {" error ",null,null},
/* 4*/ {" http://localhost:8080/ ",null,null},
private final String[][] connect_tests=
{
/* 0*/ {" localhost:8080 ","localhost","8080"},
/* 1*/ {" 127.0.0.1:8080 ","127.0.0.1","8080"},
/* 2*/ {" [127::0::0::1]:8080 ","[127::0::0::1]","8080"},
/* 3*/ {" error ",null,null},
/* 4*/ {" http://localhost:8080/ ",null,null},
};
public void testCONNECT()
throws Exception
@Test
public void testCONNECT() throws Exception
{
HttpURI uri = new HttpURI();
for (int i=0;i<connect_tests.length;i++)
@ -213,7 +217,7 @@ public class HttpURITest extends TestCase
catch(Exception e)
{
assertNull("error"+i,connect_tests[i][1]);
}
}
}
}
}

View File

@ -2,8 +2,6 @@ package org.eclipse.jetty.server;
import java.io.IOException;
import junit.framework.TestCase;
import org.eclipse.jetty.http.AbstractGenerator;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpGenerator;
@ -13,18 +11,22 @@ import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.io.ByteArrayEndPoint;
import org.eclipse.jetty.io.SimpleBuffers;
import org.eclipse.jetty.util.StringUtil;
import org.junit.Before;
import org.junit.Test;
public class HttpWriterTest extends TestCase
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HttpWriterTest
{
HttpWriter _writer;
ByteArrayBuffer _bytes;
/* ------------------------------------------------------------ */
@Override
protected void setUp() throws Exception
private HttpWriter _writer;
private ByteArrayBuffer _bytes;
@Before
public void init() throws Exception
{
_bytes = new ByteArrayBuffer(2048);
Buffers buffers = new SimpleBuffers(new ByteArrayBuffer(1024),new ByteArrayBuffer(1024));
ByteArrayEndPoint endp = new ByteArrayEndPoint();
AbstractGenerator generator = new AbstractGenerator(buffers,endp)
@ -34,13 +36,13 @@ public class HttpWriterTest extends TestCase
{
return false;
}
@Override
public boolean isResponse()
{
return true;
}
@Override
public void completeHeader(HttpFields fields, boolean allContentAdded) throws IOException
{
@ -68,37 +70,33 @@ public class HttpWriterTest extends TestCase
{
return false;
}
};
HttpOutput httpOut = new HttpOutput(generator,60000);
_writer = new HttpWriter(httpOut);
}
private void assertArrayEquals(byte[] b1, byte[] b2)
{
assertEquals(b1.length,b2.length);
for (int i=0;i<b1.length;i++)
assertEquals(""+i,b1[i],b2[i]);
}
@Test
public void testSimpleUTF8() throws Exception
{
_writer.setCharacterEncoding(StringUtil.__UTF8);
_writer.write("Now is the time");
_writer.write("Now is the time");
assertArrayEquals("Now is the time".getBytes(StringUtil.__UTF8),_bytes.asArray());
}
@Test
public void testUTF8() throws Exception
{
_writer.setCharacterEncoding(StringUtil.__UTF8);
_writer.write("How now \uFF22rown cow");
_writer.write("How now \uFF22rown cow");
assertArrayEquals("How now \uFF22rown cow".getBytes(StringUtil.__UTF8),_bytes.asArray());
}
@Test
public void testMultiByteOverflowUTF8() throws Exception
{
_writer.setCharacterEncoding(StringUtil.__UTF8);
_writer.setCharacterEncoding(StringUtil.__UTF8);
final String singleByteStr = "a";
final String multiByteDuplicateStr = "\uFF22";
int remainSize = 1;
@ -121,41 +119,47 @@ public class HttpWriterTest extends TestCase
assertEquals(sb.toString(),new String(_bytes.asArray(),StringUtil.__UTF8));
}
@Test
public void testISO8859() throws Exception
{
_writer.setCharacterEncoding(StringUtil.__ISO_8859_1);
_writer.write("How now \uFF22rown cow");
_writer.write("How now \uFF22rown cow");
assertEquals("How now ?rown cow",new String(_bytes.asArray(),StringUtil.__ISO_8859_1));
}
public void testOutput()
throws Exception
@Test
public void testOutput() throws Exception
{
Buffer sb=new ByteArrayBuffer(1500);
Buffer bb=new ByteArrayBuffer(8096);
HttpFields fields = new HttpFields();
ByteArrayEndPoint endp = new ByteArrayEndPoint(new byte[0],4096);
HttpGenerator hb = new HttpGenerator(new SimpleBuffers(sb,bb),endp);
hb.setResponse(200,"OK");
HttpOutput output = new HttpOutput(hb,10000);
HttpWriter writer = new HttpWriter(output);
writer.setCharacterEncoding(StringUtil.__UTF8);
char[] chars = new char[1024];
for (int i=0;i<chars.length;i++)
chars[i]=(char)('0'+(i%10));
chars[0]='\u0553';
writer.write(chars);
hb.completeHeader(fields,true);
hb.flush(10000);
String response = new String(endp.getOut().asArray(),StringUtil.__UTF8);
assertTrue(response.startsWith("HTTP/1.1 200 OK\r\nContent-Length: 1025\r\n\r\n\u05531234567890"));
}
}
private void assertArrayEquals(byte[] b1, byte[] b2)
{
assertEquals(b1.length,b2.length);
for (int i=0;i<b1.length;i++)
assertEquals(""+i,b1[i],b2[i]);
}
}

View File

@ -5,13 +5,13 @@
// 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
// 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.apache.org/licenses/LICENSE-2.0.txt
//
// You may elect to redistribute this code under either of these licenses.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
@ -19,9 +19,13 @@ package org.eclipse.jetty.server;
import java.util.List;
import java.util.Vector;
import junit.framework.TestCase;
import org.junit.Test;
public class InclusiveByteRangeTest extends TestCase
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class InclusiveByteRangeTest
{
@SuppressWarnings("unchecked")
private void assertInvalidRange(String rangeString)
@ -32,7 +36,7 @@ public class InclusiveByteRangeTest extends TestCase
List ranges = InclusiveByteRange.satisfiableRanges(strings.elements(),200);
assertNull("Invalid Range [" + rangeString + "] should result in no satisfiable ranges",ranges);
}
private void assertRange(String msg, int expectedFirst, int expectedLast, int size, InclusiveByteRange actualRange)
{
assertEquals(msg + " - first",expectedFirst,actualRange.getFirst(size));
@ -74,25 +78,28 @@ public class InclusiveByteRangeTest extends TestCase
assertNotNull("Satisfiable Ranges should not be null",ranges);
return ranges;
}
@Test
public void testHeader416RangeString()
{
assertEquals("416 Header on size 100","bytes */100",InclusiveByteRange.to416HeaderRangeString(100));
assertEquals("416 Header on size 123456789","bytes */123456789",InclusiveByteRange.to416HeaderRangeString(123456789));
}
@Test
public void testInvalidRanges()
{
// Invalid if parsing "Range" header
assertInvalidRange("bytes=a-b"); // letters invalid
assertInvalidRange("byte=10-3"); // key is bad
assertInvalidRange("onceuponatime=5-10"); // key is bad
assertInvalidRange("bytes=300-310"); // outside of size (200)
assertInvalidRange("bytes=300-310"); // outside of size (200)
}
/**
* Ranges have a multiple ranges, all absolutely defined.
*/
@Test
public void testMultipleAbsoluteRanges()
{
int size = 50;
@ -109,6 +116,7 @@ public class InclusiveByteRangeTest extends TestCase
/**
* Range definition has a range that is clipped due to the size.
*/
@Test
public void testMultipleRangesClipped()
{
String rangeString;
@ -122,6 +130,7 @@ public class InclusiveByteRangeTest extends TestCase
assertRange("Range [" + rangeString + "]",45,49,50,ranges.get(2));
}
@Test
public void testMultipleRangesOverlapping()
{
String rangeString;
@ -134,6 +143,7 @@ public class InclusiveByteRangeTest extends TestCase
assertRange("Range [" + rangeString + "]",15,25,200,ranges.get(1));
}
@Test
public void testMultipleRangesSplit()
{
String rangeString;
@ -145,6 +155,7 @@ public class InclusiveByteRangeTest extends TestCase
assertRange("Range [" + rangeString + "]",15,20,200,ranges.get(1));
}
@Test
public void testSimpleRange()
{
assertSimpleRange(5,10,"bytes=5-10",200);

View File

@ -23,33 +23,32 @@ import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import junit.framework.TestCase;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
*
*
*/
public class RFC2616Test extends TestCase
public class RFC2616Test
{
Server server=new Server();
LocalConnector connector=new LocalConnector();
private Server server;
private LocalConnector connector;
/**
* Constructor for RFC2616Test.
*
* @param arg0
*/
public RFC2616Test(String arg0)
@Before
public void init() throws Exception
{
super(arg0);
server.setConnectors(new Connector[]
{ connector });
server = new Server();
connector = new LocalConnector();
server.addConnector(connector);
ContextHandler vcontext=new ContextHandler();
vcontext.setContextPath("/");
@ -66,28 +65,18 @@ public class RFC2616Test extends TestCase
{ vcontext, context });
server.setHandler(collection);
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
server.start();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
super.tearDown();
server.stop();
server.join();
}
/* --------------------------------------------------------------- */
@Test
public void test3_3()
{
try
@ -114,10 +103,9 @@ public class RFC2616Test extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void test3_6()
{
String response=null;
try
{
@ -178,7 +166,7 @@ public class RFC2616Test extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void test3_9()
{
try
@ -202,12 +190,11 @@ public class RFC2616Test extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void test4_4()
{
try
{
String response;
int offset=0;
@ -265,7 +252,7 @@ public class RFC2616Test extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void test5_2() throws Exception
{
String response;
@ -297,10 +284,9 @@ public class RFC2616Test extends TestCase
offset=0;
response=connector.getResponses("GET /path/R1 HTTP/1.1\n"+"\n");
offset=checkContains(response,offset,"HTTP/1.1 400","3. no host")+1;
}
/* --------------------------------------------------------------- */
@Test
public void test8_1()
{
try
@ -335,7 +321,7 @@ public class RFC2616Test extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void test8_2()
{
try
@ -394,7 +380,7 @@ public class RFC2616Test extends TestCase
// Expect 100 not sent
((StdErrLog)Log.getLog()).setHideStacks(true);
offset=0;
response=connector.getResponses("GET /R1?error=401 HTTP/1.1\n"+
"Host: localhost\n"+
"Expect: 100-continue\n"+
@ -404,7 +390,7 @@ public class RFC2616Test extends TestCase
checkNotContained(response,offset,"HTTP/1.1 100","8.2.3 expect 100");
offset=checkContains(response,offset,"HTTP/1.1 401 ","8.2.3 expect 100")+1;
offset=checkContains(response,offset,"Connection: close","8.2.3 expect 100")+1;
((StdErrLog)Log.getLog()).setHideStacks(false);
}
catch (Exception e)
@ -412,12 +398,9 @@ public class RFC2616Test extends TestCase
e.printStackTrace();
assertTrue(false);
}
finally
{
}
}
/* --------------------------------------------------------------- */
@Test
public void test9_2()
{
// TODO
@ -434,7 +417,7 @@ public class RFC2616Test extends TestCase
*/
}
/* --------------------------------------------------------------- */
@Test
public void test9_4()
{
try
@ -457,7 +440,7 @@ public class RFC2616Test extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void test9_8()
{
// TODO
@ -475,7 +458,7 @@ public class RFC2616Test extends TestCase
*/
}
/* --------------------------------------------------------------- */
@Test
public void test10_2_7()
{
// TODO
@ -528,7 +511,7 @@ public class RFC2616Test extends TestCase
*/
}
/* --------------------------------------------------------------- */
@Test
public void test10_3()
{
// TODO
@ -578,61 +561,7 @@ public class RFC2616Test extends TestCase
*/
}
/* --------------------------------------------------------------- */
public void checkContentRange(LocalConnector listener, String tname, String path, String reqRanges, int expectedStatus, String expectedRange,
String expectedData)
{
try
{
String response;
int offset=0;
String byteRangeHeader="";
if (reqRanges!=null)
{
byteRangeHeader="Range: "+reqRanges+"\n";
}
response=connector.getResponses("GET /"+path+" HTTP/1.1\n"+"Host: localhost\n"+byteRangeHeader+"Connection: close\n"+"\n");
switch (expectedStatus)
{
case 200:
{
offset=checkContains(response,offset,"HTTP/1.1 200 OK\r\n",tname+".1. proper 200 OK status code");
break;
}
case 206:
{
offset=checkContains(response,offset,"HTTP/1.1 206 Partial Content\r\n",tname+".1. proper 206 Partial Content status code");
break;
}
case 416:
{
offset=checkContains(response,offset,"HTTP/1.1 416 Requested Range Not Satisfiable\r\n",tname
+".1. proper 416 Requested Range not Satisfiable status code");
break;
}
}
if (expectedRange!=null)
{
String expectedContentRange="Content-Range: bytes "+expectedRange+"\r\n";
offset=checkContains(response,offset,expectedContentRange,tname+".2. _content range "+expectedRange);
}
if (expectedStatus==200||expectedStatus==206)
{
offset=checkContains(response,offset,expectedData,tname+".3. subrange data: \""+expectedData+"\"");
}
}
catch (Exception e)
{
e.printStackTrace();
assertTrue(false);
}
}
@Test
public void test14_16()
{
// TODO
@ -685,12 +614,11 @@ public class RFC2616Test extends TestCase
*/
}
/* --------------------------------------------------------------- */
@Test
public void test14_23()
{
try
{
String response;
int offset=0;
@ -719,7 +647,7 @@ public class RFC2616Test extends TestCase
}
}
/* --------------------------------------------------------------- */
@Test
public void test14_35()
{
// TODO
@ -756,7 +684,7 @@ public class RFC2616Test extends TestCase
* catch(Exception e) { e.printStackTrace(); assertTrue(false); }
*/}
/* --------------------------------------------------------------- */
@Test
public void test14_39()
{
// TODO
@ -778,12 +706,11 @@ public class RFC2616Test extends TestCase
*/
}
/* --------------------------------------------------------------- */
@Test
public void test19_6()
{
try
{
String response;
int offset=0;
@ -835,7 +762,59 @@ public class RFC2616Test extends TestCase
offset=checkContains(response,offset,"/R2","19.6.2 Keep-alive close")+3;
assertEquals("19.6.2 closed",-1,response.indexOf("/R3"));
}
catch (Exception e)
{
e.printStackTrace();
assertTrue(false);
}
}
private void checkContentRange(LocalConnector listener, String tname, String path, String reqRanges, int expectedStatus, String expectedRange, String expectedData)
{
try
{
String response;
int offset=0;
String byteRangeHeader="";
if (reqRanges!=null)
{
byteRangeHeader="Range: "+reqRanges+"\n";
}
response=connector.getResponses("GET /"+path+" HTTP/1.1\n"+"Host: localhost\n"+byteRangeHeader+"Connection: close\n"+"\n");
switch (expectedStatus)
{
case 200:
{
offset=checkContains(response,offset,"HTTP/1.1 200 OK\r\n",tname+".1. proper 200 OK status code");
break;
}
case 206:
{
offset=checkContains(response,offset,"HTTP/1.1 206 Partial Content\r\n",tname+".1. proper 206 Partial Content status code");
break;
}
case 416:
{
offset=checkContains(response,offset,"HTTP/1.1 416 Requested Range Not Satisfiable\r\n",tname
+".1. proper 416 Requested Range not Satisfiable status code");
break;
}
}
if (expectedRange!=null)
{
String expectedContentRange="Content-Range: bytes "+expectedRange+"\r\n";
offset=checkContains(response,offset,expectedContentRange,tname+".2. _content range "+expectedRange);
}
if (expectedStatus==200||expectedStatus==206)
{
offset=checkContains(response,offset,expectedData,tname+".3. subrange data: \""+expectedData+"\"");
}
}
catch (Exception e)
{

View File

@ -18,73 +18,58 @@ import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
*
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class RequestTest extends TestCase
public class RequestTest
{
Server _server = new Server();
LocalConnector _connector = new LocalConnector();
RequestHandler _handler = new RequestHandler();
private Server _server;
private LocalConnector _connector;
private RequestHandler _handler;
@Before
public void init() throws Exception
{
_server = new Server();
_connector = new LocalConnector();
_connector.setHeaderBufferSize(512);
_connector.setRequestBufferSize(1024);
_connector.setResponseBufferSize(2048);
}
public RequestTest(String arg0)
{
super(arg0);
_server.setConnectors(new Connector[]{_connector});
}
public static void main(String[] args)
{
junit.textui.TestRunner.run(RequestTest.class);
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
_server.addConnector(_connector);
_handler = new RequestHandler();
_server.setHandler(_handler);
_server.start();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
super.tearDown();
_server.stop();
_server.join();
}
public void testContentTypeEncoding()
throws Exception
@Test
public void testContentTypeEncoding() throws Exception
{
final ArrayList results = new ArrayList();
final ArrayList<String> results = new ArrayList<String>();
_handler._checker = new RequestTester()
{
public boolean check(HttpServletRequest request,HttpServletResponse response)
@ -127,18 +112,13 @@ public class RequestTest extends TestCase
assertEquals("text/html; charset=\"utf8\"",results.get(i++));
assertEquals("utf8",results.get(i++));
assertTrue(((String)results.get(i++)).startsWith("text/html"));
assertTrue(results.get(i++).startsWith("text/html"));
assertEquals(" x=z; ",results.get(i++));
}
public void testContent()
throws Exception
@Test
public void testContent() throws Exception
{
final int[] length=new int[1];
_handler._checker = new RequestTester()
@ -170,8 +150,8 @@ public class RequestTest extends TestCase
}
}
public void testPartialRead()
throws Exception
@Test
public void testPartialRead() throws Exception
{
Handler handler = new AbstractHandler()
{
@ -185,7 +165,7 @@ public class RequestTest extends TestCase
response.getOutputStream().write(b);
response.flushBuffer();
}
};
_server.stop();
_server.setHandler(handler);
@ -207,17 +187,16 @@ public class RequestTest extends TestCase
String responses = _connector.getResponses(request);
System.err.println("response="+responses);
int index=responses.indexOf("read="+(int)'0');
assertTrue(index>0);
index=responses.indexOf("read="+(int)'A',index+7);
assertTrue(index>0);
}
public void testPartialInput()
throws Exception
@Test
public void testPartialInput() throws Exception
{
Handler handler = new AbstractHandler()
{
@ -259,11 +238,10 @@ public class RequestTest extends TestCase
index=responses.indexOf("read="+(int)'A',index+7);
assertTrue(index>0);
}
public void testConnectionClose()
throws Exception
@Test
public void testConnectionClose() throws Exception
{
String response;
@ -306,8 +284,6 @@ public class RequestTest extends TestCase
assertTrue(response.indexOf("Connection: close")>0);
assertTrue(response.indexOf("Hello World")>0);
response=_connector.getResponses(
"GET / HTTP/1.0\n"+
"Host: whatever\n"+
@ -337,9 +313,6 @@ public class RequestTest extends TestCase
assertTrue(response.indexOf("Connection: keep-alive")>0);
assertTrue(response.indexOf("Hello World")>0);
_handler._checker = new RequestTester()
{
public boolean check(HttpServletRequest request,HttpServletResponse response) throws IOException
@ -371,10 +344,10 @@ public class RequestTest extends TestCase
assertTrue(response.indexOf("Hello World")>0);
}
@Test
public void testCookies() throws Exception
{
final ArrayList cookies = new ArrayList();
final ArrayList<Cookie> cookies = new ArrayList<Cookie>();
_handler._checker = new RequestTester()
{
@ -409,8 +382,8 @@ public class RequestTest extends TestCase
);
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
assertEquals(1,cookies.size());
assertEquals("name",((Cookie)cookies.get(0)).getName());
assertEquals("quoted=\\\"value\\\"",((Cookie)cookies.get(0)).getValue());
assertEquals("name", cookies.get(0).getName());
assertEquals("quoted=\\\"value\\\"", cookies.get(0).getValue());
cookies.clear();
response=_connector.getResponses(
@ -421,10 +394,10 @@ public class RequestTest extends TestCase
);
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
assertEquals(2,cookies.size());
assertEquals("name",((Cookie)cookies.get(0)).getName());
assertEquals("value",((Cookie)cookies.get(0)).getValue());
assertEquals("other",((Cookie)cookies.get(1)).getName());
assertEquals("quoted=;value",((Cookie)cookies.get(1)).getValue());
assertEquals("name", cookies.get(0).getName());
assertEquals("value", cookies.get(0).getValue());
assertEquals("other", cookies.get(1).getName());
assertEquals("quoted=;value", cookies.get(1).getValue());
cookies.clear();
@ -442,14 +415,13 @@ public class RequestTest extends TestCase
);
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
assertEquals(4,cookies.size());
assertEquals("name",((Cookie)cookies.get(0)).getName());
assertEquals("value",((Cookie)cookies.get(0)).getValue());
assertEquals("other",((Cookie)cookies.get(1)).getName());
assertEquals("quoted=;value",((Cookie)cookies.get(1)).getValue());
assertTrue((Cookie)cookies.get(0)==(Cookie)cookies.get(2));
assertTrue((Cookie)cookies.get(1)==(Cookie)cookies.get(3));
assertEquals("name", cookies.get(0).getName());
assertEquals("value", cookies.get(0).getValue());
assertEquals("other", cookies.get(1).getName());
assertEquals("quoted=;value", cookies.get(1).getValue());
assertSame(cookies.get(0), cookies.get(2));
assertSame(cookies.get(1), cookies.get(3));
cookies.clear();
response=_connector.getResponses(
@ -466,13 +438,13 @@ public class RequestTest extends TestCase
);
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
assertEquals(4,cookies.size());
assertEquals("name",((Cookie)cookies.get(0)).getName());
assertEquals("value",((Cookie)cookies.get(0)).getValue());
assertEquals("other",((Cookie)cookies.get(1)).getName());
assertEquals("quoted=;value",((Cookie)cookies.get(1)).getValue());
assertEquals("name", cookies.get(0).getName());
assertEquals("value", cookies.get(0).getValue());
assertEquals("other", cookies.get(1).getName());
assertEquals("quoted=;value", cookies.get(1).getValue());
assertTrue((Cookie)cookies.get(0)!=(Cookie)cookies.get(2));
assertTrue((Cookie)cookies.get(1)!=(Cookie)cookies.get(3));
assertNotSame(cookies.get(0), cookies.get(2));
assertNotSame(cookies.get(1), cookies.get(3));
cookies.clear();
response=_connector.getResponses(
@ -484,33 +456,31 @@ public class RequestTest extends TestCase
"Connection: close\r\n"+
"\r\n");
assertEquals("name0",((Cookie)cookies.get(0)).getName());
assertEquals("value0",((Cookie)cookies.get(0)).getValue());
assertEquals("name1",((Cookie)cookies.get(1)).getName());
assertEquals("value1",((Cookie)cookies.get(1)).getValue());
assertEquals("\"name2\"",((Cookie)cookies.get(2)).getName());
assertEquals("\"value2\"",((Cookie)cookies.get(2)).getValue());
assertEquals("name3",((Cookie)cookies.get(3)).getName());
assertEquals("value3=value3",((Cookie)cookies.get(3)).getValue());
assertEquals(2,((Cookie)cookies.get(3)).getVersion());
assertEquals("/path",((Cookie)cookies.get(3)).getPath());
assertEquals("acme.com",((Cookie)cookies.get(3)).getDomain());
assertEquals("$port=8080",((Cookie)cookies.get(3)).getComment());
assertEquals("name4",((Cookie)cookies.get(4)).getName());
assertEquals("",((Cookie)cookies.get(4)).getValue());
assertEquals("name5",((Cookie)cookies.get(5)).getName());
assertEquals("",((Cookie)cookies.get(5)).getValue());
assertEquals("name6",((Cookie)cookies.get(6)).getName());
assertEquals("",((Cookie)cookies.get(6)).getValue());
assertEquals("name7",((Cookie)cookies.get(7)).getName());
assertEquals("value7",((Cookie)cookies.get(7)).getValue());
assertEquals("name0", cookies.get(0).getName());
assertEquals("value0", cookies.get(0).getValue());
assertEquals("name1", cookies.get(1).getName());
assertEquals("value1", cookies.get(1).getValue());
assertEquals("\"name2\"", cookies.get(2).getName());
assertEquals("\"value2\"", cookies.get(2).getValue());
assertEquals("name3", cookies.get(3).getName());
assertEquals("value3=value3", cookies.get(3).getValue());
assertEquals(2, cookies.get(3).getVersion());
assertEquals("/path", cookies.get(3).getPath());
assertEquals("acme.com", cookies.get(3).getDomain());
assertEquals("$port=8080", cookies.get(3).getComment());
assertEquals("name4", cookies.get(4).getName());
assertEquals("", cookies.get(4).getValue());
assertEquals("name5", cookies.get(5).getName());
assertEquals("", cookies.get(5).getValue());
assertEquals("name6", cookies.get(6).getName());
assertEquals("", cookies.get(6).getValue());
assertEquals("name7", cookies.get(7).getName());
assertEquals("value7", cookies.get(7).getValue());
}
public void testCookieLeak()
throws Exception
@Test
public void testCookieLeak() throws Exception
{
final String[] cookie=new String[10];
_handler._checker = new RequestTester()
@ -529,7 +499,6 @@ public class RequestTest extends TestCase
}
};
String request="POST / HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Cookie: other=cookie\r\n"+
@ -561,7 +530,6 @@ public class RequestTest extends TestCase
assertEquals(null,cookie[0]);
assertEquals(null,cookie[1]);
request="POST / HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Cookie: name=value\r\n"+
@ -579,22 +547,17 @@ public class RequestTest extends TestCase
assertEquals("value",cookie[0]);
assertEquals(null,cookie[1]);
}
interface RequestTester
{
boolean check(HttpServletRequest request,HttpServletResponse response) throws IOException;
}
class RequestHandler extends AbstractHandler
private class RequestHandler extends AbstractHandler
{
RequestTester _checker;
String _content;
private RequestTester _checker;
private String _content;
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
@ -607,9 +570,6 @@ public class RequestTest extends TestCase
response.setStatus(200);
else
response.sendError(500);
}
}
}

View File

@ -4,11 +4,11 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
@ -16,27 +16,27 @@ package org.eclipse.jetty.server;
import java.io.File;
import java.io.FileOutputStream;
import junit.framework.TestCase;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.ResourceCache.Content;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ResourceCacheTest extends TestCase
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ResourceCacheTest
{
Resource directory;
File[] files=new File[10];
String[] names=new String[files.length];
ResourceCache cache = new ResourceCache(new MimeTypes());
ResourceFactory factory;
/* ------------------------------------------------------------ */
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception
private Resource directory;
private File[] files=new File[10];
private String[] names=new String[files.length];
private ResourceCache cache = new ResourceCache(new MimeTypes());
private ResourceFactory factory;
@Before
public void init() throws Exception
{
for (int i=0;i<files.length;i++)
{
@ -49,9 +49,9 @@ public class ResourceCacheTest extends TestCase
out.write('\n');
out.close();
}
directory=Resource.newResource(files[0].getParentFile().getAbsolutePath());
factory = new ResourceFactory()
{
public Resource getResource(String path)
@ -65,7 +65,7 @@ public class ResourceCacheTest extends TestCase
return null;
}
}
};
cache.setMaxCacheSize(95);
cache.setMaxCachedFileSize(85);
@ -73,54 +73,50 @@ public class ResourceCacheTest extends TestCase
cache.start();
}
/* ------------------------------------------------------------ */
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
cache.stop();
}
/* ------------------------------------------------------------ */
@Test
public void testResourceCache() throws Exception
{
assertTrue(cache.lookup("does not exist",factory)==null);
assertTrue(cache.lookup(names[9],factory)==null);
Content content;
content=cache.lookup(names[8],factory);
assertTrue(content!=null);
assertEquals(80,content.getContentLength());
assertEquals(80,cache.getCachedSize());
assertEquals(1,cache.getCachedFiles());
content=cache.lookup(names[1],factory);
assertEquals(90,cache.getCachedSize());
assertEquals(2,cache.getCachedFiles());
content=cache.lookup(names[2],factory);
assertEquals(30,cache.getCachedSize());
assertEquals(2,cache.getCachedFiles());
content=cache.lookup(names[3],factory);
assertEquals(60,cache.getCachedSize());
assertEquals(3,cache.getCachedFiles());
content=cache.lookup(names[4],factory);
assertEquals(90,cache.getCachedSize());
assertEquals(3,cache.getCachedFiles());
content=cache.lookup(names[5],factory);
assertEquals(90,cache.getCachedSize());
assertEquals(2,cache.getCachedFiles());
content=cache.lookup(names[6],factory);
assertEquals(60,cache.getCachedSize());
assertEquals(1,cache.getCachedFiles());
FileOutputStream out = new FileOutputStream(files[6]);
out.write(' ');
out.close();
@ -131,27 +127,25 @@ public class ResourceCacheTest extends TestCase
content=cache.lookup(names[6],factory);
assertEquals(71,cache.getCachedSize());
assertEquals(2,cache.getCachedFiles());
content=cache.lookup(names[0],factory);
assertEquals(72,cache.getCachedSize());
assertEquals(3,cache.getCachedFiles());
content=cache.lookup(names[1],factory);
assertEquals(82,cache.getCachedSize());
assertEquals(4,cache.getCachedFiles());
content=cache.lookup(names[2],factory);
assertEquals(32,cache.getCachedSize());
assertEquals(4,cache.getCachedFiles());
content=cache.lookup(names[3],factory);
assertEquals(61,cache.getCachedSize());
assertEquals(4,cache.getCachedFiles());
cache.flushCache();
assertEquals(0,cache.getCachedSize());
assertEquals(0,cache.getCachedFiles());
}
}

View File

@ -21,15 +21,12 @@ import java.net.Socket;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionContext;
import junit.framework.TestCase;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.io.ByteArrayEndPoint;
@ -39,54 +36,43 @@ import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.session.AbstractSessionManager;
import org.eclipse.jetty.server.session.HashSessionIdManager;
import org.eclipse.jetty.server.session.HashSessionManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
*
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class ResponseTest extends TestCase
public class ResponseTest
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
private Server server;
private LocalConnector connector;
public ResponseTest(String arg0)
@Before
public void init() throws Exception
{
super(arg0);
server.setConnectors(new Connector[]{connector});
server = new Server();
connector = new LocalConnector();
server.addConnector(connector);
server.setHandler(new DumpHandler());
}
public static void main(String[] args)
{
junit.textui.TestRunner.run(ResponseTest.class);
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
server.start();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
super.tearDown();
server.stop();
server.join();
}
public void testContentType()
throws Exception
@Test
public void testContentType() throws Exception
{
HttpConnection connection = new HttpConnection(connector,new ByteArrayEndPoint(), connector.getServer());
Response response = connection.getResponse();
@ -120,9 +106,8 @@ public class ResponseTest extends TestCase
response.recycle();
}
public void testLocale()
throws Exception
@Test
public void testLocale() throws Exception
{
HttpConnection connection = new HttpConnection(connector,new ByteArrayEndPoint(), connector.getServer());
@ -146,8 +131,8 @@ public class ResponseTest extends TestCase
assertTrue(response.toString().indexOf("charset=UTF-8")>0);
}
public void testContentTypeCharacterEncoding()
throws Exception
@Test
public void testContentTypeCharacterEncoding() throws Exception
{
HttpConnection connection = new HttpConnection(connector,new ByteArrayEndPoint(), connector.getServer());
@ -179,8 +164,8 @@ public class ResponseTest extends TestCase
}
public void testCharacterEncodingContentType()
throws Exception
@Test
public void testCharacterEncodingContentType() throws Exception
{
Response response = new Response(new HttpConnection(connector,new ByteArrayEndPoint(), connector.getServer()));
@ -208,8 +193,8 @@ public class ResponseTest extends TestCase
}
public void testContentTypeWithCharacterEncoding()
throws Exception
@Test
public void testContentTypeWithCharacterEncoding() throws Exception
{
Response response = new Response(new HttpConnection(connector,new ByteArrayEndPoint(), connector.getServer()));
@ -237,8 +222,8 @@ public class ResponseTest extends TestCase
}
public void testContentTypeWithOther()
throws Exception
@Test
public void testContentTypeWithOther() throws Exception
{
Response response = new Response(new HttpConnection(connector,new ByteArrayEndPoint(), connector.getServer()));
@ -260,9 +245,8 @@ public class ResponseTest extends TestCase
assertEquals("text/xml;charset=UTF-8",response.getContentType());
}
public void testContentTypeWithCharacterEncodingAndOther()
throws Exception
@Test
public void testContentTypeWithCharacterEncodingAndOther() throws Exception
{
Response response = new Response(new HttpConnection(connector,new ByteArrayEndPoint(), connector.getServer()));
@ -290,6 +274,7 @@ public class ResponseTest extends TestCase
}
@Test
public void testStatusCodes() throws Exception
{
Response response=newResponse();
@ -319,6 +304,7 @@ public class ResponseTest extends TestCase
assertEquals("must-revalidate,no-cache,no-store", response.getHeader(HttpHeaders.CACHE_CONTROL));
}
@Test
public void testEncodeRedirect()
throws Exception
{
@ -339,21 +325,21 @@ public class ResponseTest extends TestCase
request.setSession(new TestSession(manager,"12345"));
manager.setCheckingRemoteSessionIdEncoding(false);
assertEquals("http://myhost:8888/path/info;param;jsessionid=12345?query=0&more=1#target",response.encodeURL("http://myhost:8888/path/info;param?query=0&more=1#target"));
assertEquals("http://other:8888/path/info;param;jsessionid=12345?query=0&more=1#target",response.encodeURL("http://other:8888/path/info;param?query=0&more=1#target"));
assertEquals("http://myhost/path/info;param;jsessionid=12345?query=0&more=1#target",response.encodeURL("http://myhost/path/info;param?query=0&more=1#target"));
assertEquals("http://myhost:8888/other/info;param;jsessionid=12345?query=0&more=1#target",response.encodeURL("http://myhost:8888/other/info;param?query=0&more=1#target"));
manager.setCheckingRemoteSessionIdEncoding(true);
assertEquals("http://myhost:8888/path/info;param;jsessionid=12345?query=0&more=1#target",response.encodeURL("http://myhost:8888/path/info;param?query=0&more=1#target"));
assertEquals("http://other:8888/path/info;param?query=0&more=1#target",response.encodeURL("http://other:8888/path/info;param?query=0&more=1#target"));
assertEquals("http://myhost/path/info;param?query=0&more=1#target",response.encodeURL("http://myhost/path/info;param?query=0&more=1#target"));
assertEquals("http://myhost:8888/other/info;param?query=0&more=1#target",response.encodeURL("http://myhost:8888/other/info;param?query=0&more=1#target"));
assertEquals("http://myhost:8888/other/info;param?query=0&more=1#target",response.encodeURL("http://myhost:8888/other/info;param?query=0&more=1#target"));
}
public void testSetBufferSize ()
throws Exception
@Test
public void testSetBufferSize () throws Exception
{
Response response = new Response(new HttpConnection(connector,new ByteArrayEndPoint(), connector.getServer()));
response.setBufferSize(20*1024);
@ -369,6 +355,7 @@ public class ResponseTest extends TestCase
}
}
@Test
public void testHead() throws Exception
{
Server server = new Server();
@ -428,7 +415,7 @@ public class ResponseTest extends TestCase
return response;
}
class TestSession extends AbstractSessionManager.Session
private class TestSession extends AbstractSessionManager.Session
{
public TestSession(AbstractSessionManager abstractSessionManager, String id)
{
@ -518,7 +505,6 @@ public class ResponseTest extends TestCase
protected Map newAttributeMap()
{
// TODO Auto-generated method stub
return null;
}
}

View File

@ -4,30 +4,33 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
import java.util.Random;
import junit.framework.TestCase;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @version $Revision$
*/
public class ServerTest extends TestCase
public class ServerTest
{
/**
* JETTY-87, adding a handler to a server without any handlers should not
* throw an exception
*/
@Test
public void testAddHandlerToEmptyServer()
{
Server server=new Server();
@ -42,6 +45,7 @@ public class ServerTest extends TestCase
}
}
@Test
public void testServerWithPort()
{
int port=new Random().nextInt(20000)+10000;

View File

@ -4,11 +4,11 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server;
@ -17,17 +17,17 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class UnreadInputTest extends TestCase
public class UnreadInputTest
{
public static final String __OK_RESPONSE = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nServer: Jetty(7.0.x)\r\n\r\n";
protected Server _server = new Server();
@ -36,23 +36,9 @@ public class UnreadInputTest extends TestCase
protected Socket _socket;
protected OutputStream _outputStream;
protected InputStream _inputStream;
public class NoopHandler extends AbstractHandler
{
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException
{
//don't read the input, just send something back
((Request)request).setHandled(true);
response.setStatus(200);
}
}
@Override
protected void setUp() throws Exception
@Before
public void init() throws Exception
{
//server side
_connector = new SocketConnector();
@ -60,23 +46,24 @@ public class UnreadInputTest extends TestCase
_server.setHandler(new NoopHandler());
_server.start();
_port = _connector.getLocalPort();
//client side
_socket = new Socket((String)null, _port);
_outputStream = _socket.getOutputStream();
_inputStream = _socket.getInputStream();
}
@Override
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
_socket.close();
_server.stop();
_server.join();
}
public void testUnreadInput ()
throws Exception
@Test
public void testUnreadInput () throws Exception
{
for (int i=0; i<2; i++)
{
@ -107,18 +94,24 @@ public class UnreadInputTest extends TestCase
Thread.sleep(1000L);
//write the rest
_outputStream.write(bytes, bytes.length/2, (bytes.length - bytes.length/2));
_outputStream.write(bytes, bytes.length/2, (bytes.length - bytes.length/2));
}
byte[] inbuf = new byte[__OK_RESPONSE.getBytes().length*2];
int x = _inputStream.read(inbuf);
System.err.println(new String(inbuf, 0, x));
_inputStream.close();
_outputStream.close();
_socket.close();
}
public class NoopHandler extends AbstractHandler
{
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException
{
//don't read the input, just send something back
((Request)request).setHandled(true);
response.setStatus(200);
}
}
}

View File

@ -9,59 +9,60 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @version $Revision$ $Date$
*/
public abstract class AbstractProxyHandlerTest extends TestCase
public abstract class AbstractProxyHandlerTest
{
protected Server server;
protected Connector serverConnector;
protected Server proxy;
protected Connector proxyConnector;
protected static Server server;
protected static Connector serverConnector;
protected static Server proxy;
protected static Connector proxyConnector;
@Override
protected void setUp() throws Exception
protected static void startServer(Connector connector, Handler handler) throws Exception
{
server = new Server();
serverConnector = newServerConnector();
serverConnector = connector;
server.addConnector(serverConnector);
configureServer(server);
server.setHandler(handler);
server.start();
}
protected static void startProxy() throws Exception
{
proxy = new Server();
proxyConnector = new SelectChannelConnector();
proxy.addConnector(proxyConnector);
configureProxy(proxy);
proxy.setHandler(new ProxyHandler());
proxy.start();
}
protected SelectChannelConnector newServerConnector()
@AfterClass
public static void stop() throws Exception
{
return new SelectChannelConnector();
stopProxy();
stopServer();
}
protected void configureServer(Server server)
protected static void stopServer() throws Exception
{
server.stop();
server.join();
}
protected void configureProxy(Server proxy)
{
proxy.setHandler(new ProxyHandler());
}
@Override
protected void tearDown() throws Exception
protected static void stopProxy() throws Exception
{
proxy.stop();
proxy.join();
server.stop();
server.join();
}
protected Response readResponse(BufferedReader reader) throws IOException

View File

@ -4,30 +4,32 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.junit.Test;
public class ContextHandlerCollectionTest extends TestCase
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ContextHandlerCollectionTest
{
@Test
public void testVirtualHostNormalization() throws Exception
{
Server server = new Server();
@ -83,23 +85,23 @@ public class ContextHandlerCollectionTest extends TestCase
{
server.stop();
}
}
@Test
public void testVirtualHostWildcard() throws Exception
{
Server server = new Server();
LocalConnector connector = new LocalConnector();
server.setConnectors(new Connector[] { connector });
ContextHandler context = new ContextHandler("/");
IsHandledHandler handler = new IsHandledHandler();
context.setHandler(handler);
ContextHandlerCollection c = new ContextHandlerCollection();
c.addHandler(context);
server.setHandler(c);
try
@ -107,19 +109,19 @@ public class ContextHandlerCollectionTest extends TestCase
server.start();
checkWildcardHost(true,server,null,new String[] {"example.com", ".example.com", "vhost.example.com"});
checkWildcardHost(false,server,new String[] {null},new String[] {"example.com", ".example.com", "vhost.example.com"});
checkWildcardHost(true,server,new String[] {"example.com", "*.example.com"}, new String[] {"example.com", ".example.com", "vhost.example.com"});
checkWildcardHost(false,server,new String[] {"example.com", "*.example.com"}, new String[] {"badexample.com", ".badexample.com", "vhost.badexample.com"});
checkWildcardHost(false,server,new String[] {"*."}, new String[] {"anything.anything"});
checkWildcardHost(true,server,new String[] {"*.example.com"}, new String[] {"vhost.example.com", ".example.com"});
checkWildcardHost(false,server,new String[] {"*.example.com"}, new String[] {"vhost.www.example.com", "example.com", "www.vhost.example.com"});
checkWildcardHost(true,server,new String[] {"*.sub.example.com"}, new String[] {"vhost.sub.example.com", ".sub.example.com"});
checkWildcardHost(false,server,new String[] {"*.sub.example.com"}, new String[] {".example.com", "sub.example.com", "vhost.example.com"});
checkWildcardHost(false,server,new String[] {"example.*.com","example.com.*"}, new String[] {"example.vhost.com", "example.com.vhost", "example.com"});
checkWildcardHost(false,server,new String[] {"example.*.com","example.com.*"}, new String[] {"example.vhost.com", "example.com.vhost", "example.com"});
}
finally
{
@ -137,11 +139,11 @@ public class ContextHandlerCollectionTest extends TestCase
context.setVirtualHosts(contextHosts);
// trigger this manually; it's supposed to be called when adding the handler
handlerCollection.mapContexts();
for(String host : requestHosts)
{
connector.getResponses("GET / HTTP/1.1\n" + "Host: "+host+"\n\n");
if(succeed)
if(succeed)
assertTrue("'"+host+"' should have been handled.",handler.isHandled());
else
assertFalse("'"+host + "' should not have been handled.", handler.isHandled());
@ -149,8 +151,8 @@ public class ContextHandlerCollectionTest extends TestCase
}
}
public static final class IsHandledHandler extends AbstractHandler
private static final class IsHandledHandler extends AbstractHandler
{
private boolean handled;
@ -170,5 +172,4 @@ public class ContextHandlerCollectionTest extends TestCase
handled = false;
}
}
}

View File

@ -5,86 +5,53 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server.handler;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @version $Revision$
*/
public class ContextHandlerTest extends TestCase
public class ContextHandlerTest
{
@Test
public void testGetResourcePathsWhenSuppliedPathEndsInSlash() throws Exception
{
checkResourcePathsForExampleWebApp("/WEB-INF/");
}
@Test
public void testGetResourcePathsWhenSuppliedPathDoesNotEndInSlash() throws Exception
{
checkResourcePathsForExampleWebApp("/WEB-INF");
}
private void checkResourcePathsForExampleWebApp(String root) throws IOException, MalformedURLException
{
File testDirectory = setupTestDirectory();
ContextHandler handler = new ContextHandler();
assertTrue("Not a directory " + testDirectory,testDirectory.isDirectory());
handler.setBaseResource(Resource.newResource(testDirectory.toURL()));
List paths = new ArrayList(handler.getResourcePaths(root));
assertEquals(2,paths.size());
Collections.sort(paths);
assertEquals("/WEB-INF/jsp/",paths.get(0));
assertEquals("/WEB-INF/web.xml",paths.get(1));
}
private File setupTestDirectory() throws IOException
{
File tmpDir = new File( System.getProperty( "basedir" ) + "/target/tmp/ContextHandlerTest" );
tmpDir.mkdirs();
File tmp = File.createTempFile("cht",null, tmpDir );
tmp.delete();
tmp.mkdir();
tmp.deleteOnExit();
File root = new File(tmp,getClass().getName());
root.mkdir();
File webInf = new File(root,"WEB-INF");
webInf.mkdir();
new File(webInf,"jsp").mkdir();
new File(webInf,"web.xml").createNewFile();
return root;
}
@Test
public void testVirtualHostNormalization() throws Exception
{
Server server = new Server();
@ -142,7 +109,8 @@ public class ContextHandlerTest extends TestCase
}
}
@Test
public void testVirtualHostWildcard() throws Exception
{
Server server = new Server();
@ -150,7 +118,7 @@ public class ContextHandlerTest extends TestCase
server.setConnectors(new Connector[] { connector });
ContextHandler context = new ContextHandler("/");
IsHandledHandler handler = new IsHandledHandler();
context.setHandler(handler);
@ -161,19 +129,19 @@ public class ContextHandlerTest extends TestCase
server.start();
checkWildcardHost(true,server,null,new String[] {"example.com", ".example.com", "vhost.example.com"});
checkWildcardHost(false,server,new String[] {null},new String[] {"example.com", ".example.com", "vhost.example.com"});
checkWildcardHost(true,server,new String[] {"example.com", "*.example.com"}, new String[] {"example.com", ".example.com", "vhost.example.com"});
checkWildcardHost(false,server,new String[] {"example.com", "*.example.com"}, new String[] {"badexample.com", ".badexample.com", "vhost.badexample.com"});
checkWildcardHost(false,server,new String[] {"*."}, new String[] {"anything.anything"});
checkWildcardHost(true,server,new String[] {"*.example.com"}, new String[] {"vhost.example.com", ".example.com"});
checkWildcardHost(false,server,new String[] {"*.example.com"}, new String[] {"vhost.www.example.com", "example.com", "www.vhost.example.com"});
checkWildcardHost(true,server,new String[] {"*.sub.example.com"}, new String[] {"vhost.sub.example.com", ".sub.example.com"});
checkWildcardHost(false,server,new String[] {"*.sub.example.com"}, new String[] {".example.com", "sub.example.com", "vhost.example.com"});
checkWildcardHost(false,server,new String[] {"example.*.com","example.com.*"}, new String[] {"example.vhost.com", "example.com.vhost", "example.com"});
checkWildcardHost(false,server,new String[] {"example.*.com","example.com.*"}, new String[] {"example.vhost.com", "example.com.vhost", "example.com"});
}
finally
{
@ -181,17 +149,88 @@ public class ContextHandlerTest extends TestCase
}
}
@Test
public void testAttributes() throws Exception
{
ContextHandler handler = new ContextHandler();
handler.setAttribute("aaa","111");
handler.getServletContext().setAttribute("bbb","222");
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals("222",handler.getAttribute("bbb"));
handler.start();
handler.getServletContext().setAttribute("aaa","000");
handler.setAttribute("ccc","333");
handler.getServletContext().setAttribute("ddd","444");
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals("222",handler.getServletContext().getAttribute("bbb"));
assertEquals("333",handler.getServletContext().getAttribute("ccc"));
assertEquals("444",handler.getServletContext().getAttribute("ddd"));
assertEquals("111",handler.getAttribute("aaa"));
assertEquals("222",handler.getAttribute("bbb"));
assertEquals("333",handler.getAttribute("ccc"));
assertEquals(null,handler.getAttribute("ddd"));
handler.stop();
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals("222",handler.getServletContext().getAttribute("bbb"));
assertEquals("333",handler.getServletContext().getAttribute("ccc"));
assertEquals(null,handler.getServletContext().getAttribute("ddd"));
}
private void checkResourcePathsForExampleWebApp(String root) throws IOException
{
File testDirectory = setupTestDirectory();
ContextHandler handler = new ContextHandler();
assertTrue("Not a directory " + testDirectory,testDirectory.isDirectory());
handler.setBaseResource(Resource.newResource(testDirectory.toURI().toURL()));
List<String> paths = new ArrayList<String>(handler.getResourcePaths(root));
assertEquals(2,paths.size());
Collections.sort(paths);
assertEquals("/WEB-INF/jsp/",paths.get(0));
assertEquals("/WEB-INF/web.xml",paths.get(1));
}
private File setupTestDirectory() throws IOException
{
File tmpDir = new File( System.getProperty( "basedir" ) + "/target/tmp/ContextHandlerTest" );
if (!tmpDir.exists())
assertTrue(tmpDir.mkdirs());
File tmp = File.createTempFile("cht",null, tmpDir );
assertTrue(tmp.delete());
assertTrue(tmp.mkdir());
tmp.deleteOnExit();
File root = new File(tmp,getClass().getName());
assertTrue(root.mkdir());
File webInf = new File(root,"WEB-INF");
assertTrue(webInf.mkdir());
assertTrue(new File(webInf,"jsp").mkdir());
assertTrue(new File(webInf,"web.xml").createNewFile());
return root;
}
private void checkWildcardHost(boolean succeed, Server server, String[] contextHosts, String[] requestHosts) throws Exception
{
LocalConnector connector = (LocalConnector)server.getConnectors()[0];
ContextHandler context = (ContextHandler)server.getHandler();
context.setVirtualHosts(contextHosts);
IsHandledHandler handler = (IsHandledHandler)context.getHandler();
for(String host : requestHosts)
{
connector.getResponses("GET / HTTP/1.1\n" + "Host: "+host+"\n\n");
if(succeed)
if(succeed)
assertTrue("'"+host+"' should have been handled.",handler.isHandled());
else
assertFalse("'"+host + "' should not have been handled.", handler.isHandled());
@ -199,8 +238,8 @@ public class ContextHandlerTest extends TestCase
}
}
public static final class IsHandledHandler extends AbstractHandler
private static final class IsHandledHandler extends AbstractHandler
{
private boolean handled;
@ -220,38 +259,4 @@ public class ContextHandlerTest extends TestCase
handled = false;
}
}
public void testAttributes() throws Exception
{
ContextHandler handler = new ContextHandler();
handler.setAttribute("aaa","111");
handler.getServletContext().setAttribute("bbb","222");
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals("222",handler.getAttribute("bbb"));
handler.start();
handler.getServletContext().setAttribute("aaa","000");
handler.setAttribute("ccc","333");
handler.getServletContext().setAttribute("ddd","444");
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals("222",handler.getServletContext().getAttribute("bbb"));
assertEquals("333",handler.getServletContext().getAttribute("ccc"));
assertEquals("444",handler.getServletContext().getAttribute("ddd"));
assertEquals("111",handler.getAttribute("aaa"));
assertEquals("222",handler.getAttribute("bbb"));
assertEquals("333",handler.getAttribute("ccc"));
assertEquals(null,handler.getAttribute("ddd"));
handler.stop();
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals("222",handler.getServletContext().getAttribute("bbb"));
assertEquals("333",handler.getServletContext().getAttribute("ccc"));
assertEquals(null,handler.getServletContext().getAttribute("ddd"));
}
}

View File

@ -22,17 +22,20 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* @version $Revision$ $Date$
*/
public class ProxyHandlerConnectSSLTest extends AbstractProxyHandlerTest
{
@Override
protected SelectChannelConnector newServerConnector()
@BeforeClass
public static void init() throws Exception
{
SslSelectChannelConnector connector = new SslSelectChannelConnector();
@ -42,15 +45,11 @@ public class ProxyHandlerConnectSSLTest extends AbstractProxyHandlerTest
connector.setPassword("storepwd");
connector.setKeyPassword("keypwd");
return connector;
}
@Override
protected void configureServer(Server server)
{
server.setHandler(new ServerHandler());
startServer(connector, new ServerHandler());
startProxy();
}
@Test
public void testGETRequest() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -103,6 +102,7 @@ public class ProxyHandlerConnectSSLTest extends AbstractProxyHandlerTest
}
}
@Test
public void testPOSTRequests() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -187,7 +187,7 @@ public class ProxyHandlerConnectSSLTest extends AbstractProxyHandlerTest
}
}
private class ServerHandler extends AbstractHandler
private static class ServerHandler extends AbstractHandler
{
public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException
{

View File

@ -17,19 +17,25 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @version $Revision$ $Date$
*/
public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
{
@Override
protected void configureServer(Server server)
@BeforeClass
public static void init() throws Exception
{
server.setHandler(new ServerHandler());
startServer(new SelectChannelConnector(), new ServerHandler());
startProxy();
}
@Test
public void testCONNECT() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -56,6 +62,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
@Test
public void testCONNECTAndGET() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -93,6 +100,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
@Test
public void testCONNECT10AndGET() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -130,6 +138,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
@Test
public void testCONNECTAndGETPipelined() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -164,6 +173,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
@Test
public void testCONNECTAndMultipleGETs() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -204,6 +214,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
@Test
public void testCONNECTAndGETServerStop() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -236,8 +247,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
assertEquals("GET /echo", response.getBody());
// Idle server is shut down
server.stop();
server.join();
stopServer();
int read = input.read();
assertEquals(-1, read);
@ -245,9 +255,12 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
finally
{
socket.close();
// Restart the server for the next test
server.start();
}
}
@Test
public void testCONNECTAndGETAndServerSideClose() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -284,6 +297,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
@Test
public void testCONNECTAndPOSTAndGET() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -334,6 +348,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
@Test
public void testCONNECTAndPOSTWithBigBody() throws Exception
{
String hostPort = "localhost:" + serverConnector.getLocalPort();
@ -378,13 +393,14 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
@Test
public void testCONNECTAndPOSTWithContext() throws Exception
{
final String contextKey = "contextKey";
final String contextValue = "contextValue";
// Replace the default ProxyHandler with a subclass to test context information passing
proxy.stop();
stopProxy();
proxy.setHandler(new ProxyHandler()
{
@Override
@ -463,7 +479,7 @@ public class ProxyHandlerConnectTest extends AbstractProxyHandlerTest
}
}
private class ServerHandler extends AbstractHandler
private static class ServerHandler extends AbstractHandler
{
public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException
{

View File

@ -1,23 +1,29 @@
package org.eclipse.jetty.server.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.server.Request;
import org.junit.Before;
import org.junit.Test;
public class ScopedHandlerTest extends TestCase
import static org.junit.Assert.assertEquals;
public class ScopedHandlerTest
{
StringBuilder _history=new StringBuilder();
private StringBuilder _history=new StringBuilder();
public void testSingle()
throws Exception
@Before
public void resetHistory()
{
_history.setLength(0);
}
@Test
public void testSingle() throws Exception
{
TestHandler handler0 = new TestHandler("0");
handler0.start();
handler0.handle("target",null,null,null);
@ -27,10 +33,9 @@ public class ScopedHandlerTest extends TestCase
assertEquals(">S0>W0<W0<S0",history);
}
public void testSimpleDouble()
throws Exception
@Test
public void testSimpleDouble() throws Exception
{
_history.setLength(0);
TestHandler handler0 = new TestHandler("0");
TestHandler handler1 = new TestHandler("1");
handler0.setHandler(handler1);
@ -42,10 +47,9 @@ public class ScopedHandlerTest extends TestCase
assertEquals(">S0>S1>W0>W1<W1<W0<S1<S0",history);
}
public void testSimpleTriple()
throws Exception
@Test
public void testSimpleTriple() throws Exception
{
_history.setLength(0);
TestHandler handler0 = new TestHandler("0");
TestHandler handler1 = new TestHandler("1");
TestHandler handler2 = new TestHandler("2");
@ -59,10 +63,9 @@ public class ScopedHandlerTest extends TestCase
assertEquals(">S0>S1>S2>W0>W1>W2<W2<W1<W0<S2<S1<S0",history);
}
public void testDouble()
throws Exception
@Test
public void testDouble() throws Exception
{
_history.setLength(0);
TestHandler handler0 = new TestHandler("0");
OtherHandler handlerA = new OtherHandler("A");
TestHandler handler1 = new TestHandler("1");
@ -78,10 +81,9 @@ public class ScopedHandlerTest extends TestCase
assertEquals(">S0>S1>W0>HA>W1>HB<HB<W1<HA<W0<S1<S0",history);
}
public void testTriple()
throws Exception
@Test
public void testTriple() throws Exception
{
_history.setLength(0);
TestHandler handler0 = new TestHandler("0");
OtherHandler handlerA = new OtherHandler("A");
TestHandler handler1 = new TestHandler("1");
@ -100,15 +102,16 @@ public class ScopedHandlerTest extends TestCase
System.err.println(history);
assertEquals(">S0>S1>S2>W0>HA>W1>HB>W2>HC<HC<W2<HB<W1<HA<W0<S2<S1<S0",history);
}
private class TestHandler extends ScopedHandler
{
String _name;
TestHandler(String name)
private final String _name;
private TestHandler(String name)
{
_name=name;
}
@Override
public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
@ -122,7 +125,7 @@ public class ScopedHandlerTest extends TestCase
_history.append("<S").append(_name);
}
}
@Override
public void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
@ -138,16 +141,16 @@ public class ScopedHandlerTest extends TestCase
}
}
private class OtherHandler extends HandlerWrapper
{
String _name;
OtherHandler(String name)
private final String _name;
private OtherHandler(String name)
{
_name=name;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{

View File

@ -18,29 +18,34 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
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.Request;
import org.eclipse.jetty.server.Server;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class StatisticsHandlerTest extends TestCase
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class StatisticsHandlerTest
{
private Server _server;
private LocalConnector _connector;
private LatchHandler _latchHandler;
private StatisticsHandler _statsHandler;
@Override
protected void setUp() throws Exception
@Before
public void init() throws Exception
{
_server = new Server();
@ -55,17 +60,18 @@ public class StatisticsHandlerTest extends TestCase
_latchHandler.setHandler(_statsHandler);
}
@Override
protected void tearDown() throws Exception
@After
public void destroy() throws Exception
{
_server.stop();
_server.join();
}
@Test
public void testRequest() throws Exception
{
final CyclicBarrier barrier[] = { new CyclicBarrier(2), new CyclicBarrier(2)};
_statsHandler.setHandler(new AbstractHandler()
{
public void handle(String path, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException
@ -75,7 +81,7 @@ public class StatisticsHandlerTest extends TestCase
{
barrier[0].await();
barrier[1].await();
}
catch (Exception x)
{
@ -94,11 +100,11 @@ public class StatisticsHandlerTest extends TestCase
barrier[0].await();
assertEquals(1, _connector.getConnectionsOpen());
assertEquals(1, _statsHandler.getRequests());
assertEquals(1, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getRequestsActiveMax());
assertEquals(1, _statsHandler.getDispatched());
assertEquals(1, _statsHandler.getDispatchedActive());
assertEquals(1, _statsHandler.getDispatchedActiveMax());
@ -107,11 +113,11 @@ public class StatisticsHandlerTest extends TestCase
barrier[1].await();
boolean passed = _latchHandler.await(1000);
assertTrue(passed);
assertEquals(1, _statsHandler.getRequests());
assertEquals(0, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getRequestsActiveMax());
assertEquals(1, _statsHandler.getDispatched());
assertEquals(0, _statsHandler.getDispatchedActive());
assertEquals(1, _statsHandler.getDispatchedActiveMax());
@ -120,21 +126,21 @@ public class StatisticsHandlerTest extends TestCase
assertEquals(0, _statsHandler.getResumes());
assertEquals(0, _statsHandler.getExpires());
assertEquals(1, _statsHandler.getResponses2xx());
_latchHandler.reset();
barrier[0].reset();
barrier[1].reset();
_connector.executeRequest(request);
barrier[0].await();
assertEquals(2, _connector.getConnectionsOpen());
assertEquals(2, _statsHandler.getRequests());
assertEquals(1, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getRequestsActiveMax());
assertEquals(2, _statsHandler.getDispatched());
assertEquals(1, _statsHandler.getDispatchedActive());
assertEquals(1, _statsHandler.getDispatchedActiveMax());
@ -143,11 +149,11 @@ public class StatisticsHandlerTest extends TestCase
barrier[1].await();
passed = _latchHandler.await(1000);
assertTrue(passed);
assertEquals(2, _statsHandler.getRequests());
assertEquals(0, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getRequestsActiveMax());
assertEquals(2, _statsHandler.getDispatched());
assertEquals(0, _statsHandler.getDispatchedActive());
assertEquals(1, _statsHandler.getDispatchedActiveMax());
@ -160,18 +166,18 @@ public class StatisticsHandlerTest extends TestCase
_latchHandler.reset(2);
barrier[0]=new CyclicBarrier(3);
barrier[1]=new CyclicBarrier(3);
_connector.executeRequest(request);
_connector.executeRequest(request);
barrier[0].await();
assertEquals(4, _connector.getConnectionsOpen());
assertEquals(4, _statsHandler.getRequests());
assertEquals(2, _statsHandler.getRequestsActive());
assertEquals(2, _statsHandler.getRequestsActiveMax());
assertEquals(4, _statsHandler.getDispatched());
assertEquals(2, _statsHandler.getDispatchedActive());
assertEquals(2, _statsHandler.getDispatchedActiveMax());
@ -180,11 +186,11 @@ public class StatisticsHandlerTest extends TestCase
barrier[1].await();
passed = _latchHandler.await(1000);
assertTrue(passed);
assertEquals(4, _statsHandler.getRequests());
assertEquals(0, _statsHandler.getRequestsActive());
assertEquals(2, _statsHandler.getRequestsActiveMax());
assertEquals(4, _statsHandler.getDispatched());
assertEquals(0, _statsHandler.getDispatchedActive());
assertEquals(2, _statsHandler.getDispatchedActiveMax());
@ -193,10 +199,11 @@ public class StatisticsHandlerTest extends TestCase
assertEquals(0, _statsHandler.getResumes());
assertEquals(0, _statsHandler.getExpires());
assertEquals(4, _statsHandler.getResponses2xx());
}
@Test
public void testSuspendResume() throws Exception
{
final AtomicReference<Continuation> continuationHandle = new AtomicReference<Continuation>();
@ -217,7 +224,7 @@ public class StatisticsHandlerTest extends TestCase
continuation.suspend();
continuationHandle.set(continuation);
}
}
catch (Exception x)
{
@ -232,8 +239,9 @@ public class StatisticsHandlerTest extends TestCase
}
catch (Exception x)
{
x.printStackTrace();
Thread.currentThread().interrupt();
throw (IOException)new IOException().initCause(x);
fail();
}
}
@ -245,12 +253,12 @@ public class StatisticsHandlerTest extends TestCase
"Host: localhost\r\n" +
"\r\n";
_connector.executeRequest(request);
barrier[0].await();
assertEquals(1, _connector.getConnectionsOpen());
assertEquals(1, _statsHandler.getRequests());
assertEquals(1, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getDispatched());
@ -260,7 +268,7 @@ public class StatisticsHandlerTest extends TestCase
assertTrue(_latchHandler.await(1000));
assertNotNull(continuationHandle.get());
assertTrue(continuationHandle.get().isSuspended());
assertEquals(1, _statsHandler.getRequests());
assertEquals(1, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getDispatched());
@ -270,24 +278,24 @@ public class StatisticsHandlerTest extends TestCase
_latchHandler.reset();
barrier[0].reset();
barrier[1].reset();
continuationHandle.get().addContinuationListener(new ContinuationListener()
{
public void onTimeout(Continuation continuation)
{
}
public void onComplete(Continuation continuation)
{
try { barrier[2].await(); } catch(Exception e) {}
}
});
continuationHandle.get().resume();
barrier[0].await();
assertEquals(1, _connector.getConnectionsOpen());
assertEquals(1, _statsHandler.getRequests());
@ -298,29 +306,30 @@ public class StatisticsHandlerTest extends TestCase
barrier[1].await();
assertTrue(_latchHandler.await(1000));
barrier[2].await();
assertEquals(1, _statsHandler.getRequests());
assertEquals(0, _statsHandler.getRequestsActive());
assertEquals(2, _statsHandler.getDispatched());
assertEquals(0, _statsHandler.getDispatchedActive());
assertEquals(1, _statsHandler.getSuspends());
assertEquals(1, _statsHandler.getResumes());
assertEquals(0, _statsHandler.getExpires());
assertEquals(1, _statsHandler.getResponses2xx());
assertTrue(_statsHandler.getRequestTimeTotal()>=30);
assertEquals(_statsHandler.getRequestTimeTotal(),_statsHandler.getRequestTimeMax());
assertEquals(_statsHandler.getRequestTimeTotal()*1.0,_statsHandler.getRequestTimeMean());
assertEquals(_statsHandler.getRequestTimeTotal(),_statsHandler.getRequestTimeMean(), 0.01);
assertTrue(_statsHandler.getDispatchedTimeTotal()>=20);
assertTrue(_statsHandler.getDispatchedTimeMean()+10<=_statsHandler.getDispatchedTimeTotal());
assertTrue(_statsHandler.getDispatchedTimeMax()+10<=_statsHandler.getDispatchedTimeTotal());
}
@Test
public void testSuspendExpire() throws Exception
{
final AtomicReference<Continuation> continuationHandle = new AtomicReference<Continuation>();
@ -342,7 +351,7 @@ public class StatisticsHandlerTest extends TestCase
continuation.suspend();
continuationHandle.set(continuation);
}
}
catch (Exception x)
{
@ -357,8 +366,9 @@ public class StatisticsHandlerTest extends TestCase
}
catch (Exception x)
{
x.printStackTrace();
Thread.currentThread().interrupt();
throw (IOException)new IOException().initCause(x);
fail();
}
}
@ -370,10 +380,10 @@ public class StatisticsHandlerTest extends TestCase
"Host: localhost\r\n" +
"\r\n";
_connector.executeRequest(request);
barrier[0].await();
assertEquals(1, _connector.getConnectionsOpen());
assertEquals(1, _statsHandler.getRequests());
@ -385,19 +395,19 @@ public class StatisticsHandlerTest extends TestCase
assertTrue(_latchHandler.await(1000));
assertNotNull(continuationHandle.get());
assertTrue(continuationHandle.get().isSuspended());
continuationHandle.get().addContinuationListener(new ContinuationListener()
{
public void onTimeout(Continuation continuation)
{
}
public void onComplete(Continuation continuation)
{
try { barrier[2].await(); } catch(Exception e) {}
}
});
assertEquals(1, _statsHandler.getRequests());
assertEquals(1, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getDispatched());
@ -408,7 +418,7 @@ public class StatisticsHandlerTest extends TestCase
barrier[1].reset();
barrier[0].await();
assertEquals(1, _statsHandler.getRequests());
assertEquals(1, _statsHandler.getRequestsActive());
assertEquals(2, _statsHandler.getDispatched());
@ -417,28 +427,29 @@ public class StatisticsHandlerTest extends TestCase
barrier[1].await();
assertTrue(_latchHandler.await(1000));
barrier[2].await();
assertEquals(1, _statsHandler.getRequests());
assertEquals(0, _statsHandler.getRequestsActive());
assertEquals(2, _statsHandler.getDispatched());
assertEquals(0, _statsHandler.getDispatchedActive());
assertEquals(1, _statsHandler.getSuspends());
assertEquals(1, _statsHandler.getResumes());
assertEquals(1, _statsHandler.getExpires());
assertEquals(1, _statsHandler.getResponses2xx());
assertTrue(_statsHandler.getRequestTimeTotal()>=30);
assertEquals(_statsHandler.getRequestTimeTotal(),_statsHandler.getRequestTimeMax());
assertEquals(_statsHandler.getRequestTimeTotal()*1.0,_statsHandler.getRequestTimeMean());
assertEquals(_statsHandler.getRequestTimeTotal(),_statsHandler.getRequestTimeMean(), 0.01);
assertTrue(_statsHandler.getDispatchedTimeTotal()>=20);
assertTrue(_statsHandler.getDispatchedTimeMean()+10<=_statsHandler.getDispatchedTimeTotal());
assertTrue(_statsHandler.getDispatchedTimeMax()+10<=_statsHandler.getDispatchedTimeTotal());
}
@Test
public void testSuspendComplete() throws Exception
{
final AtomicReference<Continuation> continuationHandle = new AtomicReference<Continuation>();
@ -460,7 +471,7 @@ public class StatisticsHandlerTest extends TestCase
continuation.suspend();
continuationHandle.set(continuation);
}
}
catch (Exception x)
{
@ -475,8 +486,9 @@ public class StatisticsHandlerTest extends TestCase
}
catch (Exception x)
{
x.printStackTrace();
Thread.currentThread().interrupt();
throw (IOException)new IOException().initCause(x);
fail();
}
}
@ -488,18 +500,18 @@ public class StatisticsHandlerTest extends TestCase
"Host: localhost\r\n" +
"\r\n";
_connector.executeRequest(request);
barrier[0].await();
assertEquals(1, _connector.getConnectionsOpen());
assertEquals(1, _statsHandler.getRequests());
assertEquals(1, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getDispatched());
assertEquals(1, _statsHandler.getDispatchedActive());
barrier[1].await();
assertTrue(_latchHandler.await(1000));
assertNotNull(continuationHandle.get());
@ -509,13 +521,13 @@ public class StatisticsHandlerTest extends TestCase
public void onTimeout(Continuation continuation)
{
}
public void onComplete(Continuation continuation)
{
try { barrier[2].await(); } catch(Exception e) {}
}
});
assertEquals(1, _statsHandler.getRequests());
assertEquals(1, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getDispatched());
@ -524,27 +536,27 @@ public class StatisticsHandlerTest extends TestCase
Thread.sleep(10);
continuationHandle.get().complete();
barrier[2].await();
assertEquals(1, _statsHandler.getRequests());
assertEquals(0, _statsHandler.getRequestsActive());
assertEquals(1, _statsHandler.getDispatched());
assertEquals(0, _statsHandler.getDispatchedActive());
assertEquals(1, _statsHandler.getSuspends());
assertEquals(0, _statsHandler.getResumes());
assertEquals(0, _statsHandler.getExpires());
assertEquals(1, _statsHandler.getResponses2xx());
assertTrue(_statsHandler.getRequestTimeTotal()>=20);
assertEquals(_statsHandler.getRequestTimeTotal(),_statsHandler.getRequestTimeMax());
assertEquals(_statsHandler.getRequestTimeTotal()*1.0,_statsHandler.getRequestTimeMean());
assertEquals(_statsHandler.getRequestTimeTotal(),_statsHandler.getRequestTimeMean(), 0.01);
assertTrue(_statsHandler.getDispatchedTimeTotal()>=10);
assertTrue(_statsHandler.getDispatchedTimeTotal()<_statsHandler.getRequestTimeTotal());
assertEquals(_statsHandler.getDispatchedTimeTotal(),_statsHandler.getDispatchedTimeMax());
assertEquals(_statsHandler.getDispatchedTimeTotal()*1.0,_statsHandler.getDispatchedTimeMean());
assertEquals(_statsHandler.getDispatchedTimeTotal(),_statsHandler.getDispatchedTimeMean(), 0.01);
}
/**
* This handler is external to the statistics handler and it is used to ensure that statistics handler's
@ -573,12 +585,12 @@ public class StatisticsHandlerTest extends TestCase
{
_latch=new CountDownLatch(1);
}
private void reset(int count)
{
_latch=new CountDownLatch(count);
}
private boolean await(long ms) throws InterruptedException
{
return _latch.await(ms, TimeUnit.MILLISECONDS);

View File

@ -8,28 +8,28 @@ import java.util.Enumeration;
import java.util.EventListener;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.server.DispatcherType;
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 extends TestCase
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SessionHandlerTest
{
@Test
public void testRequestedIdFromCookies()
{
final String cookieName = "SessionId";
final String sessionId = "1234.host";
HttpServletRequest httpRequest = new MockHttpServletRequest()
@ -43,7 +43,7 @@ public class SessionHandlerTest extends TestCase
Request baseRequest = new Request();
baseRequest.setDispatcherType(DispatcherType.REQUEST);
Assert.assertEquals(DispatcherType.REQUEST,baseRequest.getDispatcherType());
assertEquals(DispatcherType.REQUEST,baseRequest.getDispatcherType());
SessionHandler sessionHandler = new SessionHandler();
sessionHandler.setSessionManager(new MockSessionManager()
@ -60,14 +60,13 @@ public class SessionHandlerTest extends TestCase
});
sessionHandler.setRequestedId(baseRequest,httpRequest);
Assert.assertEquals(sessionId,baseRequest.getRequestedSessionId());
Assert.assertTrue(baseRequest.isRequestedSessionIdFromCookie());
assertEquals(sessionId,baseRequest.getRequestedSessionId());
assertTrue(baseRequest.isRequestedSessionIdFromCookie());
}
@Test
public void testRequestedIdFromURI()
{
final String parameterName = "sessionid";
final String sessionId = "1234.host";
HttpServletRequest httpRequest = new MockHttpServletRequest()
@ -81,7 +80,7 @@ public class SessionHandlerTest extends TestCase
Request baseRequest = new Request();
baseRequest.setDispatcherType(DispatcherType.REQUEST);
Assert.assertEquals(DispatcherType.REQUEST,baseRequest.getDispatcherType());
assertEquals(DispatcherType.REQUEST,baseRequest.getDispatcherType());
SessionHandler sessionHandler = new SessionHandler();
sessionHandler.setSessionManager(new MockSessionManager()
@ -101,17 +100,16 @@ public class SessionHandlerTest extends TestCase
sessionHandler.setRequestedId(baseRequest,httpRequest);
Assert.assertEquals(sessionId,baseRequest.getRequestedSessionId());
Assert.assertFalse(baseRequest.isRequestedSessionIdFromCookie());
assertEquals(sessionId,baseRequest.getRequestedSessionId());
assertFalse(baseRequest.isRequestedSessionIdFromCookie());
}
/**
* Mock class for HttpServletRequest interface.
*/
@SuppressWarnings("unchecked")
class MockHttpServletRequest implements HttpServletRequest
private class MockHttpServletRequest implements HttpServletRequest
{
public String getRequestURI()
{
return null;
@ -383,7 +381,7 @@ public class SessionHandlerTest extends TestCase
/**
* Mock class for SessionManager interface.
*/
class MockSessionManager implements SessionManager
private class MockSessionManager implements SessionManager
{
public HttpCookie access(HttpSession session, boolean secure)
{
@ -574,7 +572,8 @@ public class SessionHandlerTest extends TestCase
{
}
boolean _checkRemote=false;
private boolean _checkRemote=false;
public boolean isCheckingRemoteSessionIdEncoding()
{
return _checkRemote;
@ -584,7 +583,5 @@ public class SessionHandlerTest extends TestCase
{
_checkRemote=remote;
}
}
}

View File

@ -4,11 +4,11 @@
// 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
// 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.
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
// JettyTest.java --
@ -29,7 +29,6 @@ import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
@ -41,22 +40,24 @@ import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.IO;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* HttpServer Tester.
*
*/
public class SSLEngineTest extends TestCase
public class SSLEngineTest
{
// ~ Static fields/initializers
// ---------------------------------------------
// Useful constants
private static final String HELLO_WORLD="Hello world. The quick brown fox jumped over the lazy dog. How now brown cow. The rain in spain falls mainly on the plain.\n";
private static final String JETTY_VERSION=Server.getVersion();
@ -68,7 +69,7 @@ public class SSLEngineTest extends TestCase
private static final String REQUEST_CONTENT="<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
+"<requests xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"+" xsi:noNamespaceSchemaLocation=\"commander.xsd\" version=\""
+PROTOCOL_VERSION+"\">\n"+"</requests>";
private static final String REQUEST0=REQUEST0_HEADER+REQUEST_CONTENT.getBytes().length+"\n\n"+REQUEST_CONTENT;
private static final String REQUEST1=REQUEST1_HEADER+REQUEST_CONTENT.getBytes().length+"\n\n"+REQUEST_CONTENT;
@ -76,8 +77,10 @@ public class SSLEngineTest extends TestCase
private static final String RESPONSE0="HTTP/1.1 200 OK\n"+"Content-Length: "+HELLO_WORLD.length()+"\n"+"Server: Jetty("+JETTY_VERSION+")\n"+'\n'+HELLO_WORLD;
private static final String RESPONSE1="HTTP/1.1 200 OK\n"+"Connection: close\n"+"Server: Jetty("+JETTY_VERSION+")\n"+'\n'+HELLO_WORLD;
private static final int BODY_SIZE=300;
private static final TrustManager[] s_dummyTrustManagers=new TrustManager[]
{
{
new X509TrustManager()
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
@ -86,33 +89,29 @@ public class SSLEngineTest extends TestCase
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
{
}
}
};
Server server;
SslSelectChannelConnector connector;
// ~ Methods
// ----------------------------------------------------------------
private static Server server;
private static SslSelectChannelConnector connector;
@Override
public void setUp() throws Exception
@BeforeClass
public static void startServer() throws Exception
{
super.setUp();
server=new Server();
connector=new SslSelectChannelConnector();
String keystore = System.getProperty("user.dir") + File.separator +
"src" + File.separator +
"test" + File.separator +
"resources" + File.separator +
"keystore";
String keystore = System.getProperty("user.dir")+File.separator+"src"+File.separator+"test"+File.separator+"resources"+File.separator+"keystore";
connector.setPort(0);
connector.setKeystore(keystore);
connector.setPassword("storepwd");
@ -120,32 +119,19 @@ public class SSLEngineTest extends TestCase
connector.setRequestBufferSize(512);
connector.setRequestHeaderSize(512);
server.setConnectors(new Connector[]
{ connector });
server.setConnectors(new Connector[]{connector });
server.setHandler(new HelloWorldHandler());
server.start();
Thread.sleep(100);
}
@Override
public void tearDown() throws Exception
{
Thread.sleep(2000);
server.stop();
super.tearDown();
}
public void testNothing() throws Exception
{
}
/**
* Feed the server the entire request at once.
*
* @throws Exception
*/
@AfterClass
public static void stopServer() throws Exception
{
server.stop();
server.join();
}
@Test
public void testBigResponse() throws Exception
{
SSLContext ctx=SSLContext.getInstance("SSLv3");
@ -156,25 +142,21 @@ public class SSLEngineTest extends TestCase
Socket client=ctx.getSocketFactory().createSocket("localhost",port);
OutputStream os=client.getOutputStream();
String request =
String request =
"GET /?dump=102400 HTTP/1.1\r\n"+
"Host: localhost:8080\r\n"+
"Connection: close\r\n"+
"\r\n";
os.write(request.getBytes());
os.flush();
String response = IO.toString(client.getInputStream());
assertTrue(response.length()>102400);
}
/**
* Feed the server the entire request at once.
*
* @throws Exception
*/
@Test
public void testRequestJettyHttps() throws Exception
{
final int loops=10;
@ -231,8 +213,6 @@ public class SSLEngineTest extends TestCase
client[i].close();
}
}
}
}
}
@ -241,22 +221,74 @@ public class SSLEngineTest extends TestCase
System.err.println();
}
}
@Test
public void testServletPost() throws Exception
{
stopServer();
StreamHandler handler = new StreamHandler();
server.setHandler(handler);
server.start();
SSLContext context = SSLContext.getInstance("SSL");
context.init(null,s_dummyTrustManagers,new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
URL url = new URL("https://localhost:"+connector.getLocalPort()+"/test");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if (conn instanceof HttpsURLConnection)
{
((HttpsURLConnection)conn).setHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
return true;
}
});
}
conn.setConnectTimeout(10000);
conn.setReadTimeout(100000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","text/plain");
conn.setChunkedStreamingMode(128);
conn.connect();
byte[] b = new byte[BODY_SIZE];
for (int i = 0; i < BODY_SIZE; i++)
{
b[i] = 'x';
}
OutputStream os = conn.getOutputStream();
os.write(b);
os.flush();
int len = 0;
InputStream is = conn.getInputStream();
int bytes=0;
while ((len = is.read(b)) > -1)
bytes+=len;
is.close();
assertEquals(BODY_SIZE,handler.bytes);
assertEquals(BODY_SIZE,bytes);
}
/**
* Read entire response from the client. Close the output.
*
* @param client
* Open client socket.
*
* Reads entire response from the client. Close the output.
*
* @param client Open client socket.
* @return The response string.
*
* @throws IOException
* @throws IOException in case of I/O errors
*/
private static String readResponse(Socket client) throws IOException
{
BufferedReader br=null;
StringBuilder sb=new StringBuilder(1000);
try
{
client.setSoTimeout(5000);
@ -287,9 +319,6 @@ public class SSLEngineTest extends TestCase
private static class HelloWorldHandler extends AbstractHandler
{
// ~ Methods
// ------------------------------------------------------------
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// System.err.println("HANDLE "+request.getRequestURI());
@ -304,7 +333,7 @@ public class SSLEngineTest extends TestCase
buf[i]=(byte)('0'+(i%10));
out.write(buf);
out.close();
}
}
else
{
PrintWriter out=response.getWriter();
@ -313,92 +342,11 @@ public class SSLEngineTest extends TestCase
}
}
}
public final static int BODY_SIZE=300;
public void testServletPost() throws Exception
private static class StreamHandler extends AbstractHandler
{
Server server=new Server();
SslSelectChannelConnector connector=new SslSelectChannelConnector();
private int bytes=0;
String keystore = System.getProperty("user.dir")+File.separator+"src"+File.separator+"test"+File.separator+"resources"+File.separator+"keystore";
connector.setPort(0);
connector.setKeystore(keystore);
connector.setPassword("storepwd");
connector.setKeyPassword("keypwd");
connector.setTruststore(keystore);
connector.setTrustPassword("storepwd");
server.setConnectors(new Connector[]
{ connector });
StreamHandler handler = new StreamHandler();
server.setHandler(handler);
try
{
SSLContext context = SSLContext.getInstance("SSL");
context.init(null,s_dummyTrustManagers,new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
server.start();
URL url = new URL("https://localhost:"+connector.getLocalPort()+"/test");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if (conn instanceof HttpsURLConnection)
{
((HttpsURLConnection)conn).setHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
return true;
}
});
}
conn.setConnectTimeout(10000);
conn.setReadTimeout(100000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","text/plain"); //$NON-NLS-1$
conn.setChunkedStreamingMode(128);
conn.connect();
byte[] b = new byte[BODY_SIZE];
for (int i = 0; i < BODY_SIZE; i++)
{
b[i] = 'x';
}
OutputStream os = conn.getOutputStream();
os.write(b);
os.flush();
int rc = conn.getResponseCode();
int len = 0;
InputStream is = conn.getInputStream();
int bytes=0;
while ((len = is.read(b)) > -1)
bytes+=len;
is.close();
assertEquals(BODY_SIZE,handler.bytes);
assertEquals(BODY_SIZE,bytes);
}
finally
{
server.stop();
}
}
public static class StreamHandler extends AbstractHandler
{
public int bytes=0;
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/plain");
@ -406,7 +354,6 @@ public class SSLEngineTest extends TestCase
byte[] b = new byte[BODY_SIZE];
int len = 0;
InputStream is = request.getInputStream();
while ((len = is.read(b)) > -1)
{
bytes+=len;

View File

@ -6,16 +6,14 @@ import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLProtocolException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -27,14 +25,14 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
import org.junit.Test;
import junit.framework.TestCase;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SslRenegotiateTest extends TestCase
public class SslRenegotiateTest
{
static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager()
private static final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager()
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
@ -50,49 +48,41 @@ public class SslRenegotiateTest extends TestCase
}
} };
static HostnameVerifier hostnameVerifier = new HostnameVerifier()
{
public boolean verify( String urlHostName, SSLSession session )
{
Log.warn( "Warning: URL Host: " + urlHostName + " vs." + session.getPeerHost() );
return true;
}
};
ByteBuffer _outAppB;
ByteBuffer _outPacketB;
ByteBuffer _inAppB;
ByteBuffer _inPacketB;
SocketChannel _socket;
SSLEngine _engine;
private ByteBuffer _outAppB;
private ByteBuffer _outPacketB;
private ByteBuffer _inAppB;
private ByteBuffer _inPacketB;
private SocketChannel _socket;
private SSLEngine _engine;
@Test
public void testRenegNIO() throws Exception
{
/* TODO This test breaks on JVMs with the fix
doRequests(new SslSelectChannelConnector(),true);
*/
// TODO This test breaks on JVMs with the fix
// doRequests(new SslSelectChannelConnector(),true);
}
@Test
public void testNoRenegNIO() throws Exception
{
doRequests(new SslSelectChannelConnector(),false);
}
@Test
public void testRenegBIO() throws Exception
{
/** TODO - this test is too non deterministic due to call back timing
doRequests(new SslSocketConnector(),true);
*/
}
public void testNoRenegBIO() throws Exception
{
/** TODO - this test is too non deterministic due to call back timing
doRequests(new SslSocketConnector(),false);
*/
// TODO - this test is too non deterministic due to call back timing
// doRequests(new SslSocketConnector(),true);
}
public void doRequests(SslConnector connector,boolean reneg) throws Exception
@Test
public void testNoRenegBIO() throws Exception
{
// TODO - this test is too non deterministic due to call back timing
// doRequests(new SslSocketConnector(),false);
}
private void doRequests(SslConnector connector, boolean reneg) throws Exception
{
Server server=new Server();
try
@ -108,29 +98,29 @@ public class SslRenegotiateTest extends TestCase
server.setHandler(new HelloWorldHandler());
server.start();
SocketAddress addr = new InetSocketAddress("localhost",connector.getLocalPort());
_socket = SocketChannel.open(addr);
_socket.configureBlocking(true);
SSLContext context=SSLContext.getInstance("SSL");
context.init( null, trustAllCerts, new java.security.SecureRandom() );
_engine = context.createSSLEngine();
_engine.setUseClientMode(true);
SSLSession session=_engine.getSession();
_outAppB = ByteBuffer.allocate(session.getApplicationBufferSize());
_outPacketB = ByteBuffer.allocate(session.getPacketBufferSize());
_inAppB = ByteBuffer.allocate(session.getApplicationBufferSize());
_inPacketB = ByteBuffer.allocate(session.getPacketBufferSize());
_outAppB.put("GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n".getBytes(StringUtil.__ISO_8859_1));
_outAppB.flip();
_engine.beginHandshake();
runHandshake();
doWrap();
@ -139,7 +129,7 @@ public class SslRenegotiateTest extends TestCase
String response=new IndirectNIOBuffer(_inAppB,true).toString();
// System.err.println(response);
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
if (response.indexOf("HELLO WORLD")<0)
{
_inAppB.clear();
@ -147,9 +137,9 @@ public class SslRenegotiateTest extends TestCase
_inAppB.flip();
response=new IndirectNIOBuffer(_inAppB,true).toString();
}
assertTrue(response.indexOf("HELLO WORLD")>=0);
_inAppB.clear();
_outAppB.clear();
_outAppB.put("GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n".getBytes(StringUtil.__ISO_8859_1));
@ -160,7 +150,7 @@ public class SslRenegotiateTest extends TestCase
session.invalidate();
_engine.beginHandshake();
runHandshake();
doWrap();
doUnwrap();
_inAppB.flip();
@ -178,25 +168,19 @@ public class SslRenegotiateTest extends TestCase
Log.warn(e);
assertFalse(reneg);
}
return;
}
}
finally
{
server.stop();
server.join();
}
}
void runHandshake() throws Exception
{
SSLEngineResult result;
while (true)
{
//System.err.println();
//System.err.println(_engine.getHandshakeStatus());
switch(_engine.getHandshakeStatus())
{
case NEED_TASK:
@ -205,25 +189,25 @@ public class SslRenegotiateTest extends TestCase
_engine.getDelegatedTask().run();
break;
}
case NEED_WRAP:
{
doWrap();
break;
}
case NEED_UNWRAP:
{
doUnwrap();
break;
}
default:
return;
}
}
}
private void doWrap() throws Exception
{
SSLEngineResult result =_engine.wrap(_outAppB,_outPacketB);
@ -237,7 +221,7 @@ public class SslRenegotiateTest extends TestCase
}
_outPacketB.clear();
}
private void doUnwrap() throws Exception
{
_inPacketB.clear();
@ -245,7 +229,7 @@ public class SslRenegotiateTest extends TestCase
// System.err.println("read "+l);
if (l<0)
throw new IOException("EOF");
_inPacketB.flip();
SSLEngineResult result;
@ -253,17 +237,15 @@ public class SslRenegotiateTest extends TestCase
{
result =_engine.unwrap(_inPacketB,_inAppB);
// System.err.println("unwrapped "+result.bytesConsumed()+" to "+result.bytesProduced()+" "+_engine.getHandshakeStatus());
}
while(result.bytesConsumed()>0 &&
_inPacketB.remaining()>0 &&
_inPacketB.remaining()>0 &&
(_engine.getHandshakeStatus()==HandshakeStatus.NEED_UNWRAP || _engine.getHandshakeStatus()==HandshakeStatus.NOT_HANDSHAKING));
}
private static class HelloWorldHandler extends AbstractHandler
{
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);

View File

@ -21,34 +21,37 @@ import java.io.OutputStream;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.IO;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @version $Revision$ $Date$
*/
public class SslUploadTest extends TestCase
public class SslUploadTest
{
int _total;
public void test() throws Exception
private static Server server;
private static SslSelectChannelConnector connector;
private static int total;
@BeforeClass
public static void startServer() throws Exception
{
Server server = new Server();
SslConnector connector = new SslSelectChannelConnector();
server = new Server();
connector = new SslSelectChannelConnector();
server.addConnector(connector);
String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore";
@ -61,100 +64,86 @@ public class SslUploadTest extends TestCase
server.setHandler(new EmptyHandler());
server.start();
try
{
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(keystorePath), "storepwd".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
_total=0;
final SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket("localhost",connector.getLocalPort());
// Simulate async close
/*
new Thread()
{
@Override
public void run()
{
try
{
sleep(100);
socket.close();
}
catch (IOException x)
{
x.printStackTrace();
}
catch (InterruptedException x)
{
Thread.currentThread().interrupt();
}
}
}.start();
*/
long start = System.nanoTime();
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\n".getBytes());
out.write("Host: localhost\r\n".getBytes());
out.write("Content-Length: 16777216\r\n".getBytes());
out.write("Content-Type: bytes\r\n".getBytes());
out.write("Connection: close\r\n".getBytes());
out.write("\r\n".getBytes());
out.flush();
byte[] requestContent = new byte[16777216];
Arrays.fill(requestContent, (byte)120);
out.write(requestContent);
out.flush();
InputStream in = socket.getInputStream();
String response = IO.toString(in);
// System.err.println(response);
long end = System.nanoTime();
System.out.println("upload time: " + TimeUnit.NANOSECONDS.toMillis(end - start));
assertEquals(requestContent.length,_total);
}
finally
{
server.stop();
}
}
private class EmptyHandler extends AbstractHandler
@AfterClass
public static void stopServer() throws Exception
{
server.stop();
server.join();
}
@Test
public void test() throws Exception
{
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(connector.getKeystore()), "storepwd".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
final SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket("localhost",connector.getLocalPort());
// Simulate async close
/*
new Thread()
{
@Override
public void run()
{
try
{
sleep(100);
socket.close();
}
catch (IOException x)
{
x.printStackTrace();
}
catch (InterruptedException x)
{
Thread.currentThread().interrupt();
}
}
}.start();
*/
long start = System.nanoTime();
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\n".getBytes());
out.write("Host: localhost\r\n".getBytes());
out.write("Content-Length: 16777216\r\n".getBytes());
out.write("Content-Type: bytes\r\n".getBytes());
out.write("Connection: close\r\n".getBytes());
out.write("\r\n".getBytes());
out.flush();
byte[] requestContent = new byte[16777216];
Arrays.fill(requestContent, (byte)120);
out.write(requestContent);
out.flush();
InputStream in = socket.getInputStream();
String response = IO.toString(in);
// System.err.println(response);
long end = System.nanoTime();
System.out.println("upload time: " + TimeUnit.NANOSECONDS.toMillis(end - start));
assertEquals(requestContent.length, total);
}
private static class EmptyHandler extends AbstractHandler
{
public void handle(String path, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException
{
// System.out.println("path = " + path);
request.setHandled(true);
InputStream in = request.getInputStream();
byte[] b = new byte[4096*4];
int l;
while((l=in.read(b))>=0)
{
// System.out.println("Read "+l);
_total+=l;
}
System.err.println("Read "+_total);
}
}
private class EmptyHostnameVerifier implements HostnameVerifier
{
public boolean verify(String s, SSLSession sslSession)
{
return true;
int read;
while((read = in.read(b))>=0)
total += read;
System.err.println("Read "+ total);
}
}
}