Merge branch 'jetty-9' of ssh://git.eclipse.org/gitroot/jetty/org.eclipse.jetty.project into jetty-9

This commit is contained in:
Joakim Erdfelt 2012-07-16 09:32:38 -07:00
commit 1cf2035580
30 changed files with 761 additions and 1714 deletions

View File

@ -24,11 +24,6 @@
<artifactId>jetty-servlets</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-rewrite</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-deploy</artifactId>
@ -38,32 +33,16 @@
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jmx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-ajp</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-test-helper</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-websocket</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>test-jetty-servlet</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -382,7 +382,19 @@ public class HttpFields implements Iterable<HttpFields.Field>
/* -------------------------------------------------------------- */
public String getStringField(HttpHeader header)
{
return getStringField(header.toString());
return getStringField(header.asString());
}
/* -------------------------------------------------------------- */
public String get(HttpHeader header)
{
return getStringField(header.asString());
}
/* -------------------------------------------------------------- */
public String get(String header)
{
return getStringField(header);
}
/* -------------------------------------------------------------- */

View File

@ -0,0 +1,334 @@
package org.eclipse.jetty.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.StringUtil;
public class HttpTester
{
private HttpTester(){};
public static Request newRequest()
{
return new Request();
}
public static Request parseRequest(String request)
{
Request r=new Request();
HttpParser parser =new HttpParser(r);
parser.parseNext(BufferUtil.toBuffer(request));
return r;
}
public static Request parseRequest(ByteBuffer request)
{
Request r=new Request();
HttpParser parser =new HttpParser(r);
parser.parseNext(request);
return r;
}
public static Response parseResponse(String response)
{
Response r=new Response();
HttpParser parser =new HttpParser(r);
parser.parseNext(BufferUtil.toBuffer(response));
return r;
}
public static Response parseResponse(ByteBuffer response)
{
Response r=new Response();
HttpParser parser =new HttpParser(r);
parser.parseNext(response);
return r;
}
public abstract static class Message extends HttpFields implements HttpParser.HttpHandler
{
ByteArrayOutputStream _content;
HttpVersion _version=HttpVersion.HTTP_1_0;
public HttpVersion getVersion()
{
return _version;
}
public void setVersion(String version)
{
setVersion(HttpVersion.CACHE.get(version));
}
public void setVersion(HttpVersion version)
{
_version=version;
}
public void setContent(String content)
{
try
{
_content=new ByteArrayOutputStream();
_content.write(StringUtil.getBytes(content));
}
catch (IOException e)
{
throw new RuntimeIOException(e);
}
}
public void setContent(ByteBuffer content)
{
try
{
_content=new ByteArrayOutputStream();
_content.write(BufferUtil.toArray(content));
}
catch (IOException e)
{
throw new RuntimeIOException(e);
}
}
@Override
public boolean parsedHeader(HttpHeader header, String name, String value)
{
put(name,value);
return false;
}
@Override
public boolean messageComplete(long contentLength)
{
return true;
}
@Override
public boolean headerComplete(boolean hasBody, boolean persistent)
{
if (hasBody)
_content=new ByteArrayOutputStream();
return false;
}
@Override
public boolean earlyEOF()
{
return true;
}
@Override
public boolean content(ByteBuffer ref)
{
try
{
_content.write(BufferUtil.toArray(ref));
}
catch (IOException e)
{
throw new RuntimeIOException(e);
}
return false;
}
@Override
public void badMessage(int status, String reason)
{
throw new RuntimeIOException(reason);
}
public ByteBuffer generate()
{
try
{
HttpGenerator generator = new HttpGenerator();
HttpGenerator.Info info = getInfo();
System.err.println(info.getClass());
System.err.println(info);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteBuffer header=BufferUtil.allocate(8192);
ByteBuffer buffer=BufferUtil.allocate(8192);
ByteBuffer chunk=BufferUtil.allocate(16);
ByteBuffer content=_content==null?null:ByteBuffer.wrap(_content.toByteArray());
loop: while(true)
{
HttpGenerator.Result result = generator.generate(info,header,chunk,buffer,content,HttpGenerator.Action.COMPLETE);
switch(result)
{
case NEED_BUFFER:
case NEED_HEADER:
case NEED_CHUNK:
case NEED_INFO:
throw new IllegalStateException();
case FLUSH:
if (BufferUtil.hasContent(header))
{
out.write(BufferUtil.toArray(header));
BufferUtil.clear(header);
}
if (BufferUtil.hasContent(chunk))
{
out.write(BufferUtil.toArray(chunk));
BufferUtil.clear(chunk);
}
if (BufferUtil.hasContent(buffer))
{
out.write(BufferUtil.toArray(buffer));
BufferUtil.clear(buffer);
}
break;
case FLUSH_CONTENT:
if (BufferUtil.hasContent(header))
{
out.write(BufferUtil.toArray(header));
BufferUtil.clear(header);
}
if (BufferUtil.hasContent(chunk))
{
out.write(BufferUtil.toArray(chunk));
BufferUtil.clear(chunk);
}
if (BufferUtil.hasContent(content))
{
out.write(BufferUtil.toArray(content));
BufferUtil.clear(content);
}
break;
case OK:
case SHUTDOWN_OUT:
break loop;
}
}
return ByteBuffer.wrap(out.toByteArray());
}
catch (IOException e)
{
throw new RuntimeIOException(e);
}
}
abstract public HttpGenerator.Info getInfo();
}
public static class Request extends Message implements HttpParser.RequestHandler
{
private String _method;
private String _uri;
@Override
public boolean startRequest(HttpMethod method, String methodString, String uri, HttpVersion version)
{
_method=methodString;
_uri=uri;
_version=version;
return false;
}
public String getMethod()
{
return _method;
}
public String getUri()
{
return _uri;
}
public void setMethod(String method)
{
_method=method;
}
public void setURI(String uri)
{
_uri=uri;
}
@Override
public HttpGenerator.RequestInfo getInfo()
{
return new HttpGenerator.RequestInfo(_version,this,_content==null?0:_content.size(),_method,_uri);
}
public String toString()
{
return String.format("%s %s %s\n%s\n",_method,_uri,_version,super.toString());
}
public void setHeader(String name, String value)
{
put(name,value);
}
}
public static class Response extends Message implements HttpParser.ResponseHandler
{
private int _status;
private String _reason;
@Override
public boolean startResponse(HttpVersion version, int status, String reason)
{
_version=version;
_status=status;
_reason=reason;
return false;
}
public int getStatus()
{
return _status;
}
public String getReason()
{
return _reason;
}
public byte[] getContentBytes()
{
if (_content==null)
return null;
return _content.toByteArray();
}
public String getContent()
{
if (_content==null)
return null;
byte[] bytes=_content.toByteArray();
String content_type=get(HttpHeader.CONTENT_TYPE);
String encoding=MimeTypes.getCharsetFromContentType(content_type);
Charset charset=encoding==null?StringUtil.__UTF8_CHARSET:Charset.forName(encoding);
return new String(bytes,charset);
}
@Override
public HttpGenerator.ResponseInfo getInfo()
{
return new HttpGenerator.ResponseInfo(_version,this,_content==null?-1:_content.size(),_status,_reason,false);
}
public String toString()
{
return String.format("%s %s %s\n%s\n",_version,_status,_reason,super.toString());
}
}
}

View File

@ -250,6 +250,8 @@ public class MimeTypes
/* ------------------------------------------------------------ */
public static String getCharsetFromContentType(String value)
{
if (value==null)
return null;
int end=value.length();
int state=0;
int start=0;

93
jetty-proxy/pom.xml Normal file
View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>jetty-project</artifactId>
<groupId>org.eclipse.jetty</groupId>
<version>9.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jetty-proxy</artifactId>
<name>Jetty :: Proxy</name>
<description>Jetty Proxy</description>
<properties>
<bundle-symbolic-name>${project.groupId}.servlets</bundle-symbolic-name>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>manifest</goal>
</goals>
<configuration>
<instructions>
<Import-Package>javax.servlet.*;version="2.6.0",*</Import-Package>
</instructions>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<!--
Required for OSGI
-->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<configuration>
<onlyAnalyze>org.eclipse.jetty.servlets.*</onlyAnalyze>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-test-helper</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-continuation</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.orbit</groupId>
<artifactId>javax.servlet</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -11,7 +11,7 @@
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.servlets;
package org.eclipse.jetty.proxy;
import java.io.IOException;
import java.io.InputStream;

View File

@ -11,7 +11,7 @@
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.servlets;
package org.eclipse.jetty.proxy;
import java.util.EnumSet;

View File

@ -1,4 +1,4 @@
package org.eclipse.jetty.servlets;
package org.eclipse.jetty.proxy;
import java.io.File;
import java.io.FileInputStream;
@ -20,6 +20,7 @@ import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.proxy.ProxyServlet;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;

View File

@ -323,7 +323,10 @@ public class Server extends HandlerWrapper implements Attributes
if (_connectors!=null)
{
for (int i=_connectors.length;i-->0;)
try{_connectors[i].stop();}catch(Throwable e){mex.add(e);}
{
if (_connectors[i]!=null)
try{_connectors[i].stop();}catch(Throwable e){mex.add(e);}
}
}
try {super.doStop(); } catch(Throwable e) { mex.add(e);}

View File

@ -84,7 +84,7 @@ public class ServletContextHandler extends ContextHandler
protected JspConfigDescriptor _jspConfig;
protected Object _restrictedContextListeners;
private boolean _restrictListeners = true;
/* ------------------------------------------------------------ */
public ServletContextHandler()
{

View File

@ -0,0 +1,210 @@
package org.eclipse.jetty.servlet;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.LocalHttpConnector;
import org.eclipse.jetty.server.SelectChannelConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.component.AggregateLifeCycle;
import org.eclipse.jetty.util.resource.Resource;
public class ServletTester extends AggregateLifeCycle
{
private final Server _server=new Server();
private final LocalHttpConnector _connector=new LocalHttpConnector();
private final ServletContextHandler _context;
public void setVirtualHosts(String[] vhosts)
{
_context.setVirtualHosts(vhosts);
}
public void addVirtualHosts(String[] virtualHosts)
{
_context.addVirtualHosts(virtualHosts);
}
public ServletHolder addServlet(String className, String pathSpec)
{
return _context.addServlet(className,pathSpec);
}
public ServletHolder addServlet(Class<? extends Servlet> servlet, String pathSpec)
{
return _context.addServlet(servlet,pathSpec);
}
public void addServlet(ServletHolder servlet, String pathSpec)
{
_context.addServlet(servlet,pathSpec);
}
public void addFilter(FilterHolder holder, String pathSpec, EnumSet<DispatcherType> dispatches)
{
_context.addFilter(holder,pathSpec,dispatches);
}
public FilterHolder addFilter(Class<? extends Filter> filterClass, String pathSpec, EnumSet<DispatcherType> dispatches)
{
return _context.addFilter(filterClass,pathSpec,dispatches);
}
public FilterHolder addFilter(String filterClass, String pathSpec, EnumSet<DispatcherType> dispatches)
{
return _context.addFilter(filterClass,pathSpec,dispatches);
}
public Object getAttribute(String name)
{
return _context.getAttribute(name);
}
public Enumeration getAttributeNames()
{
return _context.getAttributeNames();
}
public Attributes getAttributes()
{
return _context.getAttributes();
}
public String getContextPath()
{
return _context.getContextPath();
}
public String getInitParameter(String name)
{
return _context.getInitParameter(name);
}
public String setInitParameter(String name, String value)
{
return _context.setInitParameter(name,value);
}
public Enumeration getInitParameterNames()
{
return _context.getInitParameterNames();
}
public Map<String, String> getInitParams()
{
return _context.getInitParams();
}
public void removeAttribute(String name)
{
_context.removeAttribute(name);
}
public void setAttribute(String name, Object value)
{
_context.setAttribute(name,value);
}
public void setContextPath(String contextPath)
{
_context.setContextPath(contextPath);
}
public Resource getBaseResource()
{
return _context.getBaseResource();
}
public String getResourceBase()
{
return _context.getResourceBase();
}
public void setResourceBase(String resourceBase)
{
_context.setResourceBase(resourceBase);
}
private final ServletHandler _handler;
public ServletTester()
{
this("/",ServletContextHandler.SECURITY|ServletContextHandler.SESSIONS);
}
public ServletTester(String ctxPath)
{
this(ctxPath,ServletContextHandler.SECURITY|ServletContextHandler.SESSIONS);
}
public ServletTester(String contextPath,int options)
{
_context=new ServletContextHandler(_server,contextPath,options);
_handler=_context.getServletHandler();
_server.setConnectors(new Connector[]{_connector});
addBean(_server);
}
public ServletContextHandler getContext()
{
return _context;
}
public String getResponses(String request) throws Exception
{
return _connector.getResponses(request);
}
public ByteBuffer getResponses(ByteBuffer request) throws Exception
{
return _connector.getResponses(request);
}
/* ------------------------------------------------------------ */
/** Create a port based connector.
* This methods adds a port connector to the server
* @return A URL to access the server via the connector.
* @throws Exception
*/
public String createConnector(boolean localhost) throws Exception
{
SelectChannelConnector connector = new SelectChannelConnector();
if (localhost)
connector.setHost("127.0.0.1");
_server.addConnector(connector);
if (_server.isStarted())
connector.start();
else
connector.open();
return "http://"+(localhost?"127.0.0.1":
InetAddress.getLocalHost().getHostAddress()
)+":"+connector.getLocalPort();
}
public LocalHttpConnector createLocalConnector()
{
LocalHttpConnector connector = new LocalHttpConnector();
_server.addConnector(connector);
return connector;
}
}

View File

@ -74,11 +74,6 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
@ -89,11 +84,5 @@
<artifactId>javax.servlet</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>test-jetty-servlet</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -13,15 +13,11 @@
package org.eclipse.jetty.servlets;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.AbstractHttpConnection;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/* ------------------------------------------------------------ */
/** Closeable DoS Filter.
@ -31,18 +27,10 @@ import org.eclipse.jetty.util.log.Logger;
public class CloseableDoSFilter extends DoSFilter
{
private static final Logger LOG = Log.getLogger(CloseableDoSFilter.class);
@Override
protected void closeConnection(HttpServletRequest request, HttpServletResponse response, Thread thread)
{
try
{
Request base_request=(request instanceof Request)?(Request)request:AbstractHttpConnection.getCurrentConnection().getRequest();
base_request.getConnection().getEndPoint().close();
}
catch(IOException e)
{
LOG.warn(e);
}
Request base_request=(request instanceof Request)?(Request)request:HttpChannel.getCurrentHttpChannel().getRequest();
base_request.getHttpChannel().getConnection().getEndPoint().close();
}
}

View File

@ -32,7 +32,7 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationListener;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.eclipse.jetty.http.HttpMethods;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.gzip.GzipResponseWrapper;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -108,6 +108,7 @@ public class GzipFilter extends UserAgentFilter
/**
* @see org.eclipse.jetty.servlets.UserAgentFilter#destroy()
*/
@Override
public void destroy()
{
}
@ -116,6 +117,7 @@ public class GzipFilter extends UserAgentFilter
/**
* @see org.eclipse.jetty.servlets.UserAgentFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
@ -124,7 +126,7 @@ public class GzipFilter extends UserAgentFilter
String ae = request.getHeader("accept-encoding");
if (ae != null && ae.indexOf("gzip")>=0 && !response.containsHeader("Content-Encoding")
&& !HttpMethods.HEAD.equalsIgnoreCase(request.getMethod()))
&& !HttpMethod.HEAD.is(request.getMethod()))
{
if (_excluded!=null)
{

View File

@ -16,7 +16,7 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.testing.ServletTester;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.AfterClass;
@ -37,15 +37,14 @@ public abstract class AbstractDoSFilterTest
public static void startServer(Class<? extends Filter> filter) throws Exception
{
_tester = new ServletTester();
HttpURI uri = new HttpURI(_tester.createChannelConnector(true));
_tester = new ServletTester("/ctx");
HttpURI uri = new HttpURI(_tester.createConnector(true));
_host = uri.getHost();
_port = uri.getPort();
_tester.setContextPath("/ctx");
_tester.addServlet(TestServlet.class, "/*");
_tester.getContext().addServlet(TestServlet.class, "/*");
_dosFilter = _tester.addFilter(filter, "/dos/*", EnumSet.allOf(DispatcherType.class));
_dosFilter = _tester.getContext().addFilter(filter, "/dos/*", EnumSet.allOf(DispatcherType.class));
_dosFilter.setInitParameter("maxRequestsPerSec", "4");
_dosFilter.setInitParameter("delayMs", "200");
_dosFilter.setInitParameter("throttledRequests", "1");
@ -54,7 +53,7 @@ public abstract class AbstractDoSFilterTest
_dosFilter.setInitParameter("remotePort", "false");
_dosFilter.setInitParameter("insertHeaders", "true");
_timeoutFilter = _tester.addFilter(filter, "/timeout/*", EnumSet.allOf(DispatcherType.class));
_timeoutFilter = _tester.getContext().addFilter(filter, "/timeout/*", EnumSet.allOf(DispatcherType.class));
_timeoutFilter.setInitParameter("maxRequestsPerSec", "4");
_timeoutFilter.setInitParameter("delayMs", "200");
_timeoutFilter.setInitParameter("throttledRequests", "1");

View File

@ -12,9 +12,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.testing.ServletTester;
import org.eclipse.jetty.servlet.ServletTester;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;

View File

@ -22,15 +22,16 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.zip.GZIPInputStream;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.testing.HttpTester;
import org.eclipse.jetty.testing.ServletTester;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.toolchain.test.TestingDir;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.Before;
@ -69,11 +70,10 @@ public class IncludableGzipFilterTest
IO.copy(testIn,testOut);
testOut.close();
tester=new ServletTester();
tester.setContextPath("/context");
tester.setResourceBase(testdir.getDir().getCanonicalPath());
tester.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class, "/");
FilterHolder holder = tester.addFilter(IncludableGzipFilter.class,"/*",null);
tester=new ServletTester("/context");
tester.getContext().setResourceBase(testdir.getDir().getCanonicalPath());
tester.getContext().addServlet(org.eclipse.jetty.servlet.DefaultServlet.class, "/");
FilterHolder holder = tester.getContext().addFilter(IncludableGzipFilter.class,"/*",null);
holder.setInitParameter("mimeTypes","text/plain");
tester.start();
}
@ -89,22 +89,18 @@ public class IncludableGzipFilterTest
public void testGzipFilter() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
ByteBuffer request=BufferUtil.toBuffer(
"GET /context/file.txt HTTP/1.0\r\n"+
"Host: tester\r\n"+
"Accept-Encoding: gzip\r\n"+
"\r\n");
request.setMethod("GET");
request.setVersion("HTTP/1.0");
request.setHeader("Host","tester");
request.setHeader("accept-encoding","gzip");
request.setURI("/context/file.txt");
ByteArrayBuffer reqsBuff = new ByteArrayBuffer(request.generate().getBytes());
ByteArrayBuffer respBuff = tester.getResponses(reqsBuff);
response.parse(respBuff.asArray());
assertTrue(response.getMethod()==null);
assertTrue(response.getHeader("Content-Encoding").equalsIgnoreCase("gzip"));
HttpTester.Response response=HttpTester.parseResponse(tester.getResponses(request));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
assertEquals("gzip",response.get("Content-Encoding"));
InputStream testIn = new GZIPInputStream(new ByteArrayInputStream(response.getContentBytes()));
ByteArrayOutputStream testOut = new ByteArrayOutputStream();

View File

@ -34,8 +34,8 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.testing.HttpTester;
import org.eclipse.jetty.testing.ServletTester;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.Before;
@ -56,12 +56,11 @@ public class MultipartFilterTest
_dir.deleteOnExit();
assertTrue(_dir.isDirectory());
tester=new ServletTester();
tester.setContextPath("/context");
tester.setResourceBase(_dir.getCanonicalPath());
tester.addServlet(DumpServlet.class, "/");
tester.setAttribute("javax.servlet.context.tempdir", _dir);
FilterHolder multipartFilter = tester.addFilter(MultiPartFilter.class,"/*", EnumSet.of(DispatcherType.REQUEST));
tester=new ServletTester("/context");
tester.getContext().setResourceBase(_dir.getCanonicalPath());
tester.getContext().addServlet(DumpServlet.class, "/");
tester.getContext().setAttribute("javax.servlet.context.tempdir", _dir);
FilterHolder multipartFilter = tester.getContext().addFilter(MultiPartFilter.class,"/*", EnumSet.of(DispatcherType.REQUEST));
multipartFilter.setInitParameter("deleteFiles", "true");
tester.start();
}
@ -76,8 +75,8 @@ public class MultipartFilterTest
public void testBadPost() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test GET
request.setMethod("POST");
@ -98,8 +97,7 @@ public class MultipartFilterTest
request.setContent(content);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
@ -108,8 +106,8 @@ public class MultipartFilterTest
public void testPost() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test GET
request.setMethod("POST");
@ -129,8 +127,7 @@ public class MultipartFilterTest
request.setContent(content);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
assertTrue(response.getContent().indexOf("brown cow")>=0);
}
@ -140,8 +137,8 @@ public class MultipartFilterTest
public void testEncodedPost() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test GET
request.setMethod("POST");
@ -161,8 +158,7 @@ public class MultipartFilterTest
request.setContent(content);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
assertTrue(response.getContent().indexOf("brown cow")>=0);
}
@ -173,8 +169,8 @@ public class MultipartFilterTest
@Test
public void testPostWithContentTransferEncodingBase64() throws Exception {
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test GET
request.setMethod("POST");
@ -195,8 +191,7 @@ public class MultipartFilterTest
request.setContent(content);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
assertTrue(response.getContent().indexOf("brown cow")>=0);
}
@ -207,8 +202,8 @@ public class MultipartFilterTest
@Test
public void testPostWithContentTransferEncodingQuotedPrintable() throws Exception {
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test GET
request.setMethod("POST");
@ -232,8 +227,7 @@ public class MultipartFilterTest
request.setContent(content);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
assertTrue(response.getContent().indexOf("brown cow")>=0);
}

View File

@ -30,8 +30,9 @@ import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.testing.HttpTester;
import org.eclipse.jetty.testing.ServletTester;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.Before;
@ -51,8 +52,7 @@ public class PutFilterTest
_dir.deleteOnExit();
assertTrue(_dir.isDirectory());
tester=new ServletTester();
tester.setContextPath("/context");
tester=new ServletTester("/context");
tester.setResourceBase(_dir.getCanonicalPath());
tester.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class, "/");
FilterHolder holder = tester.addFilter(PutFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST));
@ -74,16 +74,15 @@ public class PutFilterTest
public void testHandlePut() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test GET
request.setMethod("GET");
request.setVersion("HTTP/1.0");
request.setHeader("Host","tester");
request.setURI("/context/file.txt");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_NOT_FOUND,response.getStatus());
// test PUT0
@ -92,8 +91,7 @@ public class PutFilterTest
request.setHeader("Content-Type","text/plain");
String data0="Now is the time for all good men to come to the aid of the party";
request.setContent(data0);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_CREATED,response.getStatus());
File file=new File(_dir,"file.txt");
@ -105,8 +103,7 @@ public class PutFilterTest
request.setVersion("HTTP/1.0");
request.setHeader("Host","tester");
request.setURI("/context/file.txt");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
assertEquals(data0,response.getContent());
@ -116,8 +113,7 @@ public class PutFilterTest
request.setHeader("Content-Type","text/plain");
String data1="How Now BROWN COW!!!!";
request.setContent(data1);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
file=new File(_dir,"file.txt");
@ -130,8 +126,8 @@ public class PutFilterTest
request.setHeader("Content-Type","text/plain");
String data2="Blah blah blah Blah blah";
request.setContent(data2);
String to_send = request.generate();
URL url = new URL(tester.createSocketConnector(true));
String to_send = BufferUtil.toString(request.generate());
URL url = new URL(tester.createConnector(true));
Socket socket=new Socket(url.getHost(),url.getPort());
OutputStream out = socket.getOutputStream();
int l = to_send.length();
@ -153,10 +149,9 @@ public class PutFilterTest
request.setVersion("HTTP/1.0");
request.setHeader("Host","tester");
request.setURI("/context/file.txt");
response.parse(tester.getResponses(request.generate()));
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
}
while(response.getStatus()==200);
assertTrue(response.getMethod()==null);
assertEquals(HttpServletResponse.SC_NOT_FOUND,response.getStatus());
out.write(to_send.substring(l-5).getBytes());
@ -167,8 +162,7 @@ public class PutFilterTest
request.setVersion("HTTP/1.0");
request.setHeader("Host","tester");
request.setURI("/context/file.txt");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
assertEquals(data2,response.getContent());
}
@ -177,8 +171,8 @@ public class PutFilterTest
public void testHandleDelete() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test PUT1
request.setMethod("PUT");
@ -188,8 +182,7 @@ public class PutFilterTest
request.setHeader("Content-Type","text/plain");
String data1="How Now BROWN COW!!!!";
request.setContent(data1);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_CREATED,response.getStatus());
File file=new File(_dir,"file.txt");
@ -200,16 +193,14 @@ public class PutFilterTest
request.setMethod("DELETE");
request.setURI("/context/file.txt");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_NO_CONTENT,response.getStatus());
assertTrue(!file.exists());
request.setMethod("DELETE");
request.setURI("/context/file.txt");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_FORBIDDEN,response.getStatus());
}
@ -217,8 +208,8 @@ public class PutFilterTest
public void testHandleMove() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test PUT1
request.setMethod("PUT");
@ -228,8 +219,9 @@ public class PutFilterTest
request.setHeader("Content-Type","text/plain");
String data1="How Now BROWN COW!!!!";
request.setContent(data1);
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
System.err.println(request);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_CREATED,response.getStatus());
File file=new File(_dir,"file.txt");
@ -241,8 +233,7 @@ public class PutFilterTest
request.setMethod("MOVE");
request.setURI("/context/file.txt");
request.setHeader("new-uri","/context/blah.txt");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_NO_CONTENT,response.getStatus());
assertTrue(!file.exists());
@ -255,20 +246,19 @@ public class PutFilterTest
public void testHandleOptions() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
HttpTester.Response response;
// test PUT1
request.setMethod("OPTIONS");
request.setVersion("HTTP/1.0");
request.setHeader("Host","tester");
request.put("Host","tester");
request.setURI("/context/file.txt");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
Set<String> options = new HashSet<String>();
options.addAll(Arrays.asList(response.getHeader("Allow").split(" *, *")));
options.addAll(Arrays.asList(response.get("Allow").split(" *, *")));
assertTrue(options.contains("GET"));
assertTrue(options.contains("POST"));

View File

@ -28,11 +28,12 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.LocalHttpConnector;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.testing.HttpTester;
import org.eclipse.jetty.testing.ServletTester;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.junit.After;
@ -44,7 +45,7 @@ public class QoSFilterTest
private static final Logger LOG = Log.getLogger(QoSFilterTest.class);
private ServletTester _tester;
private LocalConnector[] _connectors;
private LocalHttpConnector[] _connectors;
private CountDownLatch _doneRequests;
private final int NUM_CONNECTIONS = 8;
private final int NUM_LOOPS = 6;
@ -59,7 +60,7 @@ public class QoSFilterTest
TestServlet.__maxSleepers=0;
TestServlet.__sleepers=0;
_connectors = new LocalConnector[NUM_CONNECTIONS];
_connectors = new LocalHttpConnector[NUM_CONNECTIONS];
for(int i = 0; i < _connectors.length; ++i)
_connectors[i] = _tester.createLocalConnector();
@ -134,7 +135,7 @@ public class QoSFilterTest
{
for (int i=0;i<NUM_LOOPS;i++)
{
HttpTester request = new HttpTester();
HttpTester.Request request = HttpTester.newRequest();
request.setMethod("GET");
request.setHeader("host", "tester");
@ -142,7 +143,7 @@ public class QoSFilterTest
request.setHeader("num", _num+"");
try
{
String responseString = _tester.getResponses(request.generate(), _connectors[_num]);
String responseString = _connectors[_num].getResponses(BufferUtil.toString(request.generate()));
if(responseString.indexOf("HTTP")!=-1)
{
_doneRequests.countDown();
@ -168,7 +169,7 @@ public class QoSFilterTest
URL url=null;
try
{
String addr = _tester.createSocketConnector(true);
String addr = _tester.createConnector(true);
for (int i=0;i<NUM_LOOPS;i++)
{
url=new URL(addr+"/context/test?priority="+(_num%QoSFilter.__DEFAULT_MAX_PRIORITY)+"&n="+_num+"&l="+i);

View File

@ -18,12 +18,11 @@ import javax.servlet.DispatcherType;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlets.GzipFilter;
import org.eclipse.jetty.testing.HttpTester;
import org.eclipse.jetty.testing.ServletTester;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.TestingDir;

View File

@ -87,13 +87,10 @@ public class WebSocketFrame implements Frame
private OpCode opcode = null;
private boolean masked = false;
private byte mask[];
/**
* The payload data.
* <p>
* It is assumed to always be in FLUSH mode (ready to read) in this object.
*/
private ByteBuffer data;
private boolean continuation = false;
private int continuationIndex = 0;
/**
@ -113,33 +110,6 @@ public class WebSocketFrame implements Frame
this.opcode = opcode;
}
/**
* Copy constructor for the websocket frame.
* <p>
* Note: the underlying payload is merely a {@link ByteBuffer#slice()} of the input frame.
*
* @param copy
* the websocket to copy.
*/
public WebSocketFrame(WebSocketFrame copy)
{
fin = copy.rsv1;
rsv1 = copy.rsv2;
rsv2 = copy.rsv2;
rsv3 = copy.rsv3;
opcode = copy.opcode;
masked = copy.masked;
mask = null;
if (copy.mask != null)
{
mask = new byte[copy.mask.length];
System.arraycopy(copy.mask,0,mask,0,mask.length);
}
data = copy.data.slice();
continuationIndex = copy.continuationIndex;
continuation = copy.continuation;
}
public void assertValid()
{
if (opcode.isControlFrame())
@ -371,6 +341,7 @@ public class WebSocketFrame implements Frame
BufferUtil.clearToFill(data);
data.put(buf,0,len);
BufferUtil.flipToFlush(data,0);
BufferUtil.flipToFill(data);
return this;
}
@ -399,7 +370,7 @@ public class WebSocketFrame implements Frame
data = ByteBuffer.allocate(len);
BufferUtil.clearToFill(data);
data.put(buf,0,len);
BufferUtil.flipToFlush(data,0);
BufferUtil.flipToFill(data);
return this;
}

View File

@ -355,6 +355,7 @@
<module>jetty-deploy</module>
<module>jetty-websocket</module>
<module>jetty-servlets</module>
<module>test-continuation</module>
<module>test-jetty-webapp</module>
@ -362,7 +363,6 @@
<!--
<module>jetty-jaspi</module>
<module>jetty-client</module>
<module>jetty-servlets</module>
<module>jetty-ajp</module>
<module>jetty-jndi</module>
<module>jetty-annotations</module>

View File

@ -1,23 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-project</artifactId>
<version>9.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>test-jetty-servlet</artifactId>
<packaging>jar</packaging>
<name>Test :: Jetty Servlet Tester</name>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,128 +0,0 @@
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.webapp.WebAppContext;
import org.xml.sax.SAXException;
/**
* Repro a jetty problem.
*
* @author hughw
*
*/
public class Jetty400Repro extends HttpServlet{
private static final long serialVersionUID = 1L;
private static final int port = 8080;
private static final String host = "localhost";
private static final String uri = "/flub/servlet/";
/**
* Jetty 7.0.1 returns 400 on the second POST, when you send both Connection: Keep-Alive and
* Expect: 100-Continue headers in the request.
* @param args
*/
public static void main(String[] args) throws Exception{
initJetty();
Thread.sleep(1000);
Socket sock = new Socket(host, port);
sock.setSoTimeout(500);
String body= "<flibs xmlns='http://www.flub.org/schemas/131'><flib uid='12321'><name>foo flib</name> </flib></flibs>";
//body= "XXX"; // => 501
int len = body.getBytes("US-ASCII").length;
String msg = "POST " + uri + " HTTP/1.1\r\n" +
"Content-Type: application/xml\r\n" +
"Host: 10.0.2.2:8080\r\n" +
"Content-Length: " + len + "\r\n" +
"Expect: 100-continue\r\n" +
"Connection: Keep-Alive\r\n" +
"\r\n" +
body;
sock.getOutputStream().write(msg.getBytes("US-ASCII"));
String response1 = readResponse(sock);
int status1 = Integer.parseInt(response1.substring(9, 12));
assert 401 == status1;
sock.getOutputStream().write(msg.getBytes("US-ASCII"));
String response2 = readResponse(sock);
System.out.println(response2.substring(0, 100));
int status2 = Integer.parseInt(response2.substring(9, 12));
System.out.println(status2);
assert 401 == status2;
}
private static String readResponse(Socket sock) throws IOException {
byte [] response = new byte [4000];
int n = 0;
for (int i=0; i< response.length && response[n] >= 0; i++){
try {
response[n++] = (byte)sock.getInputStream().read();
} catch (SocketTimeoutException e) {
break;
}
}
String sResult = new String(response);
return sResult;
}
private static void initJetty() throws SAXException, IOException, MalformedURLException, Exception {
Server jetty = new Server(8080);
// configure your web application
WebAppContext appContext = new WebAppContext();
appContext.setContextPath("/flub");
appContext.addServlet(Jetty400Repro.class, "/servlet/");
appContext.setResourceBase(".");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { appContext, new DefaultHandler() });
jetty.setHandler(handlers);
jetty.start();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getInputStream();
resp.sendError(401);
}
}

View File

@ -1,585 +0,0 @@
// ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.testing;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.http.Cookie;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.HttpVersions;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.io.SimpleBuffers;
import org.eclipse.jetty.io.View;
import org.eclipse.jetty.io.bio.StringEndPoint;
import org.eclipse.jetty.util.ByteArrayOutputStream2;
/* ------------------------------------------------------------ */
/** Test support class.
* Assist with parsing and generating HTTP requests and responses.
*
* <pre>
* HttpTester tester = new HttpTester();
*
* tester.parse(
* "GET /uri HTTP/1.1\r\n"+
* "Host: fakehost\r\n"+
* "Content-Length: 10\r\n" +
* "\r\n");
*
* System.err.println(tester.getMethod());
* System.err.println(tester.getURI());
* System.err.println(tester.getVersion());
* System.err.println(tester.getHeader("Host"));
* System.err.println(tester.getContent());
* </pre>
*
*
* @see org.eclipse.jetty.testing.ServletTester
*/
public class HttpTester
{
protected HttpFields _fields=new HttpFields();
protected String _method;
protected String _uri;
protected String _version;
protected int _status;
protected String _reason;
protected ByteArrayOutputStream2 _parsedContent;
protected byte[] _genContent;
private String _charset, _defaultCharset;
private Buffer _contentType;
public HttpTester()
{
this("UTF-8");
}
public HttpTester(String charset)
{
_defaultCharset = charset;
}
public void reset()
{
_fields.clear();
_method=null;
_uri=null;
_version=null;
_status=0;
_reason=null;
_parsedContent=null;
_genContent=null;
}
private String getString(Buffer buffer)
{
return getString(buffer.asArray());
}
private String getString(byte[] b)
{
if(_charset==null)
return new String(b);
try
{
return new String(b, _charset);
}
catch(Exception e)
{
return new String(b);
}
}
private byte[] getByteArray(String str)
{
if(_charset==null)
return str.getBytes();
try
{
return str.getBytes(_charset);
}
catch(Exception e)
{
return str.getBytes();
}
}
/* ------------------------------------------------------------ */
/**
* Parse one HTTP request or response
* @param rawHTTP Raw HTTP to parse
* @return Any unparsed data in the rawHTTP (eg pipelined requests)
* @throws IOException
*/
public String parse(String rawHTTP, boolean isHeadResponse) throws IOException
{
_charset = _defaultCharset;
ByteArrayBuffer buf = new ByteArrayBuffer(getByteArray(rawHTTP));
View view = new View(buf);
PH ph = new PH();
HttpParser parser = new HttpParser(view,ph);
parser.setHeadResponse(isHeadResponse);
parser.parse();
if (ph.isEarlyEOF())
throw new EofException();
return getString(view.asArray());
}
/* ------------------------------------------------------------ */
/**
* Parse one HTTP request or response
* @param rawHTTP Raw HTTP to parse
* @return Any unparsed data in the rawHTTP (eg pipelined requests)
* @throws IOException
*/
public String parse(String rawHTTP) throws IOException
{
return parse(rawHTTP, false);
}
/* ------------------------------------------------------------ */
/**
* Parse one HTTP request or response
* @param rawHTTP Raw HTTP to parse
* @return Any unparsed data in the rawHTTP (eg pipelined requests)
* @throws IOException
*/
public byte[] parse(byte[] rawHTTP, boolean isHeadResponse) throws IOException
{
_charset = _defaultCharset;
ByteArrayBuffer buf = new ByteArrayBuffer(rawHTTP);
View view = new View(buf);
PH ph = new PH();
HttpParser parser = new HttpParser(view,ph);
parser.setHeadResponse(isHeadResponse);
parser.parse();
if (ph.isEarlyEOF())
throw new EofException();
return view.asArray();
}
/* ------------------------------------------------------------ */
/**
* Parse one HTTP request or response
* @param rawHTTP Raw HTTP to parse
* @return Any unparsed data in the rawHTTP (eg pipelined requests)
* @throws IOException
*/
public byte[] parse(byte[] rawHTTP) throws IOException
{
return parse(rawHTTP, false);
}
/* ------------------------------------------------------------ */
public String generate() throws IOException
{
_charset = _defaultCharset;
_contentType = _fields.get(HttpHeaders.CONTENT_TYPE_BUFFER);
if(_contentType!=null)
{
String charset = MimeTypes.getCharsetFromContentType(_contentType);
if(charset!=null)
_charset = charset;
}
Buffer bb=new ByteArrayBuffer(32*1024 + (_genContent!=null?_genContent.length:0));
Buffer sb=new ByteArrayBuffer(4*1024);
StringEndPoint endp = new StringEndPoint(_charset);
HttpGenerator generator = new HttpGenerator(new SimpleBuffers(sb,bb),endp);
if (_method!=null)
{
generator.setRequest(getMethod(),getURI());
if (_version==null)
generator.setVersion(HttpVersions.HTTP_1_1_ORDINAL);
else
generator.setVersion(HttpVersions.CACHE.getOrdinal(HttpVersions.CACHE.lookup(_version)));
generator.completeHeader(_fields,false);
if (_genContent!=null)
generator.addContent(new View(new ByteArrayBuffer(_genContent)),false);
else if (_parsedContent!=null)
generator.addContent(new ByteArrayBuffer(_parsedContent.toByteArray()),false);
}
generator.complete();
generator.flushBuffer();
return endp.getOutput();
}
/* ------------------------------------------------------------ */
/**
* @return the method
*/
public String getMethod()
{
return _method;
}
/* ------------------------------------------------------------ */
/**
* @param method the method to set
*/
public void setMethod(String method)
{
_method=method;
}
/* ------------------------------------------------------------ */
/**
* @return the reason
*/
public String getReason()
{
return _reason;
}
/* ------------------------------------------------------------ */
/**
* @param reason the reason to set
*/
public void setReason(String reason)
{
_reason=reason;
}
/* ------------------------------------------------------------ */
/**
* @return the status
*/
public int getStatus()
{
return _status;
}
/* ------------------------------------------------------------ */
/**
* @param status the status to set
*/
public void setStatus(int status)
{
_status=status;
}
/* ------------------------------------------------------------ */
/**
* @return the uri
*/
public String getURI()
{
return _uri;
}
/* ------------------------------------------------------------ */
/**
* @param uri the uri to set
*/
public void setURI(String uri)
{
_uri=uri;
}
/* ------------------------------------------------------------ */
/**
* @return the version
*/
public String getVersion()
{
return _version;
}
/* ------------------------------------------------------------ */
/**
* @param version the version to set
*/
public void setVersion(String version)
{
_version=version;
}
/* ------------------------------------------------------------ */
public String getContentType()
{
return getString(_contentType);
}
/* ------------------------------------------------------------ */
public String getCharacterEncoding()
{
return _charset;
}
/* ------------------------------------------------------------ */
/**
* @param name
* @param value
* @throws IllegalArgumentException
* @see org.eclipse.jetty.http.HttpFields#add(java.lang.String, java.lang.String)
*/
public void addHeader(String name, String value) throws IllegalArgumentException
{
_fields.add(name,value);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @param date
* @see org.eclipse.jetty.http.HttpFields#addDateField(java.lang.String, long)
*/
public void addDateHeader(String name, long date)
{
_fields.addDateField(name,date);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @param value
* @see org.eclipse.jetty.http.HttpFields#addLongField(java.lang.String, long)
*/
public void addLongHeader(String name, long value)
{
_fields.addLongField(name,value);
}
/* ------------------------------------------------------------ */
/**
* @param cookie
* @see org.eclipse.jetty.http.HttpFields#addSetCookie(org.eclipse.jetty.http.HttpCookie)
*/
public void addSetCookie(Cookie cookie)
{
_fields.addSetCookie(
cookie.getName(),
cookie.getValue(),
cookie.getDomain(),
cookie.getPath(),
cookie.getMaxAge(),
cookie.getComment(),
cookie.getSecure(),
cookie.isHttpOnly(),
cookie.getVersion());
}
/* ------------------------------------------------------------ */
/**
* @param name
* @return the header value as a date
* @see org.eclipse.jetty.http.HttpFields#getDateField(java.lang.String)
*/
public long getDateHeader(String name)
{
return _fields.getDateField(name);
}
/* ------------------------------------------------------------ */
/**
* @return the header value names
* @see org.eclipse.jetty.http.HttpFields#getFieldNames()
*/
public Enumeration getHeaderNames()
{
return _fields.getFieldNames();
}
/* ------------------------------------------------------------ */
/**
* @param name
* @return the header value as a long
* @throws NumberFormatException
* @see org.eclipse.jetty.http.HttpFields#getLongField(java.lang.String)
*/
public long getLongHeader(String name) throws NumberFormatException
{
return _fields.getLongField(name);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @return the header value
* @see org.eclipse.jetty.http.HttpFields#getStringField(java.lang.String)
*/
public String getHeader(String name)
{
return _fields.getStringField(name);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @return the header values
* @see org.eclipse.jetty.http.HttpFields#getValues(java.lang.String)
*/
public Enumeration getHeaderValues(String name)
{
return _fields.getValues(name);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @param value
* @see org.eclipse.jetty.http.HttpFields#put(java.lang.String, java.lang.String)
*/
public void setHeader(String name, String value)
{
_fields.put(name,value);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @param date
* @see org.eclipse.jetty.http.HttpFields#putDateField(java.lang.String, long)
*/
public void setDateHeader(String name, long date)
{
_fields.putDateField(name,date);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @param value
* @see org.eclipse.jetty.http.HttpFields#putLongField(java.lang.String, long)
*/
public void setLongHeader(String name, long value)
{
_fields.putLongField(name,value);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @see org.eclipse.jetty.http.HttpFields#remove(java.lang.String)
*/
public void removeHeader(String name)
{
_fields.remove(name);
}
/* ------------------------------------------------------------ */
public String getContent()
{
if (_parsedContent!=null)
return getString(_parsedContent.toByteArray());
if (_genContent!=null)
return getString(_genContent);
return null;
}
/* ------------------------------------------------------------ */
public byte[] getContentBytes()
{
if (_parsedContent!=null)
return _parsedContent.toByteArray();
if (_genContent!=null)
return _genContent;
return null;
}
/* ------------------------------------------------------------ */
public void setContent(String content)
{
_parsedContent=null;
if (content!=null)
{
_genContent=getByteArray(content);
setLongHeader(HttpHeaders.CONTENT_LENGTH,_genContent.length);
}
else
{
removeHeader(HttpHeaders.CONTENT_LENGTH);
_genContent=null;
}
}
/* ------------------------------------------------------------ */
private class PH extends HttpParser.EventHandler
{
private volatile boolean _earlyEOF;
@Override
public void startRequest(Buffer method, Buffer url, Buffer version) throws IOException
{
reset();
_method=getString(method);
_uri=getString(url);
_version=getString(version);
}
@Override
public void startResponse(Buffer version, int status, Buffer reason) throws IOException
{
reset();
_version=getString(version);
_status=status;
_reason=getString(reason);
}
@Override
public void parsedHeader(Buffer name, Buffer value) throws IOException
{
_fields.add(name,value);
}
@Override
public void headerComplete() throws IOException
{
_contentType = _fields.get(HttpHeaders.CONTENT_TYPE_BUFFER);
if(_contentType!=null)
{
String charset = MimeTypes.getCharsetFromContentType(_contentType);
if(charset!=null)
_charset = charset;
}
}
@Override
public void messageComplete(long contextLength) throws IOException
{
}
@Override
public void content(Buffer ref) throws IOException
{
if (_parsedContent==null)
_parsedContent=new ByteArrayOutputStream2();
_parsedContent.write(ref.asArray());
}
@Override
public void earlyEOF()
{
_earlyEOF = true;
}
public boolean isEarlyEOF()
{
return _earlyEOF;
}
}
}

View File

@ -1,374 +0,0 @@
// ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.testing;
import java.net.InetAddress;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.EventListener;
import javax.servlet.DispatcherType;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.Attributes;
/* ------------------------------------------------------------ */
/** Testing support for servlets and filters.
*
* Allows a programatic setup of a context with servlets and filters for
* testing. Raw HTTP requests may be sent to the context and responses received.
* To avoid handling raw HTTP see {@link org.eclipse.jetty.testing.HttpTester}.
* <pre>
* ServletTester tester=new ServletTester();
* tester.setContextPath("/context");
* tester.addServlet(TestServlet.class, "/servlet/*");
* tester.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/");
* tester.start();
* String response = tester.getResponses("GET /context/servlet/info HTTP/1.0\r\n\r\n");
* </pre>
*
* @see org.eclipse.jetty.testing.HttpTester
*
*
*/
public class ServletTester
{
Server _server = new Server();
LocalConnector _connector = new LocalConnector();
// Context _context = new Context(Context.SESSIONS|Context.SECURITY);
//jaspi why security if it is not set up?
ServletContextHandler _context = new ServletContextHandler(ServletContextHandler.SESSIONS);
public ServletTester()
{
try
{
_server.addBean(new ErrorHandler());
_server.setSendServerVersion(false);
_server.addConnector(_connector);
_server.setHandler(_context);
}
catch (Error e)
{
throw e;
}
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/* ------------------------------------------------------------ */
public void dump()
{
_server.dump();
}
/* ------------------------------------------------------------ */
public void start() throws Exception
{
_server.start();
}
/* ------------------------------------------------------------ */
public void stop() throws Exception
{
_server.stop();
}
/* ------------------------------------------------------------ */
public ServletContextHandler getContext()
{
return _context;
}
/* ------------------------------------------------------------ */
/** Get raw HTTP responses from raw HTTP requests.
* Multiple requests and responses may be handled, but only if
* persistent connections conditions apply.
* @param rawRequests String of raw HTTP requests
* @return String of raw HTTP responses
* @throws Exception
*/
public String getResponses(String rawRequests) throws Exception
{
return _connector.getResponses(rawRequests);
}
/* ------------------------------------------------------------ */
/** Get raw HTTP responses from raw HTTP requests.
* Multiple requests and responses may be handled, but only if
* persistent connections conditions apply.
* @param rawRequests String of raw HTTP requests
* @param connector The connector to handle the responses
* @return String of raw HTTP responses
* @throws Exception
*/
public String getResponses(String rawRequests, LocalConnector connector) throws Exception
{
return connector.getResponses(rawRequests);
}
/* ------------------------------------------------------------ */
/** Get raw HTTP responses from raw HTTP requests.
* Multiple requests and responses may be handled, but only if
* persistent connections conditions apply.
* @param rawRequests String of raw HTTP requests
* @return String of raw HTTP responses
* @throws Exception
*/
public ByteArrayBuffer getResponses(ByteArrayBuffer rawRequests) throws Exception
{
return _connector.getResponses(rawRequests,false);
}
/* ------------------------------------------------------------ */
/** Create a Socket connector.
* This methods adds a socket connector to the server
* @param localhost if true, only listen on local host, else listen on all interfaces.
* @return A URL to access the server via the socket connector.
* @throws Exception
*/
public String createSocketConnector(boolean localhost)
throws Exception
{
synchronized (this)
{
SocketConnector connector = new SocketConnector();
if (localhost)
connector.setHost("127.0.0.1");
_server.addConnector(connector);
if (_server.isStarted())
connector.start();
else
connector.open();
return "http://127.0.0.1:"+connector.getLocalPort();
}
}
/* ------------------------------------------------------------ */
/** Create a SelectChannel connector.
* This methods adds a select channel connector to the server
* @return A URL to access the server via the connector.
* @throws Exception
*/
public String createChannelConnector(boolean localhost)
throws Exception
{
synchronized (this)
{
SelectChannelConnector connector = new SelectChannelConnector();
if (localhost)
connector.setHost("127.0.0.1");
_server.addConnector(connector);
if (_server.isStarted())
connector.start();
else
connector.open();
return "http://"+(localhost?"127.0.0.1":
InetAddress.getLocalHost().getHostAddress()
)+":"+connector.getLocalPort();
}
}
/* ------------------------------------------------------------ */
/** Create a local connector.
* This methods adds a local connector to the server
* @return The LocalConnector object
* @throws Exception
*/
public LocalConnector createLocalConnector()
throws Exception
{
synchronized (this)
{
LocalConnector connector = new LocalConnector();
_server.addConnector(connector);
if (_server.isStarted())
connector.start();
return connector;
}
}
/* ------------------------------------------------------------ */
/**
* @param listener
* @see org.eclipse.jetty.server.handler.ContextHandler#addEventListener(java.util.EventListener)
*/
public void addEventListener(EventListener listener)
{
_context.addEventListener(listener);
}
/* ------------------------------------------------------------ */
/**
* @param filterClass
* @param pathSpec
* @param dispatches
* @return the FilterHolder
* @see org.eclipse.jetty.servlet.ServletContextHandler#addFilter(java.lang.Class, java.lang.String, int)
*/
public FilterHolder addFilter(Class filterClass, String pathSpec, EnumSet<DispatcherType> dispatches)
{
return _context.addFilter(filterClass,pathSpec,dispatches);
}
/* ------------------------------------------------------------ */
/**
* @param filterClass
* @param pathSpec
* @param dispatches
* @return the FilterHolder
* @see org.eclipse.jetty.servlet.ServletContextHandler#addFilter(java.lang.String, java.lang.String, int)
*/
public FilterHolder addFilter(String filterClass, String pathSpec, EnumSet<DispatcherType> dispatches)
{
return _context.addFilter(filterClass,pathSpec,dispatches);
}
/* ------------------------------------------------------------ */
/**
* @param servlet
* @param pathSpec
* @return the ServletHolder
* @see org.eclipse.jetty.servlet.ServletContextHandler#addServlet(java.lang.Class, java.lang.String)
*/
public ServletHolder addServlet(Class servlet, String pathSpec)
{
return _context.addServlet(servlet,pathSpec);
}
/* ------------------------------------------------------------ */
/**
* @param className
* @param pathSpec
* @return the ServletHolder
* @see org.eclipse.jetty.servlet.ServletContextHandler#addServlet(java.lang.String, java.lang.String)
*/
public ServletHolder addServlet(String className, String pathSpec)
{
return _context.addServlet(className,pathSpec);
}
/* ------------------------------------------------------------ */
/**
* @param name
* @return the Attribute object
* @see org.eclipse.jetty.servlet.ServletContextHandler#getAttribute(java.lang.String)
*/
public Object getAttribute(String name)
{
return _context.getAttribute(name);
}
/* ------------------------------------------------------------ */
/**
* @return the Attribute Names
* @see org.eclipse.jetty.servlet.ServletContextHandler#getAttributeNames()
*/
public Enumeration getAttributeNames()
{
return _context.getAttributeNames();
}
/* ------------------------------------------------------------ */
/**
* @return the attributes
* @see org.eclipse.jetty.servlet.ServletContextHandler#getAttributes()
*/
public Attributes getAttributes()
{
return _context.getAttributes();
}
/* ------------------------------------------------------------ */
/**
* @return the resource base
* @see org.eclipse.jetty.servlet.ServletContextHandler#getResourceBase()
*/
public String getResourceBase()
{
return _context.getResourceBase();
}
/* ------------------------------------------------------------ */
/**
* @param name
* @param value
* @see org.eclipse.jetty.servlet.ServletContextHandler#setAttribute(java.lang.String, java.lang.Object)
*/
public void setAttribute(String name, Object value)
{
_context.setAttribute(name,value);
}
/* ------------------------------------------------------------ */
/**
* @param classLoader
* @see org.eclipse.jetty.servlet.ServletContextHandler#setClassLoader(java.lang.ClassLoader)
*/
public void setClassLoader(ClassLoader classLoader)
{
_context.setClassLoader(classLoader);
}
/* ------------------------------------------------------------ */
/**
* @param contextPath
* @see org.eclipse.jetty.servlet.ServletContextHandler#setContextPath(java.lang.String)
*/
public void setContextPath(String contextPath)
{
_context.setContextPath(contextPath);
}
/* ------------------------------------------------------------ */
/**
* @param eventListeners
* @see org.eclipse.jetty.servlet.ServletContextHandler#setEventListeners(java.util.EventListener[])
*/
public void setEventListeners(EventListener[] eventListeners)
{
_context.setEventListeners(eventListeners);
}
/* ------------------------------------------------------------ */
/**
* @param resourceBase
* @see org.eclipse.jetty.servlet.ServletContextHandler#setResourceBase(java.lang.String)
*/
public void setResourceBase(String resourceBase)
{
_context.setResourceBase(resourceBase);
}
}

View File

@ -1,56 +0,0 @@
// ========================================================================
// Copyright (c) 2007-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.testing;
import junit.framework.TestCase;
public class HttpTesterTest extends TestCase
{
public void testCharset() throws Exception
{
HttpTester tester = new HttpTester();
tester.parse(
"POST /uri\uA74A HTTP/1.1\r\n"+
"Host: fakehost\r\n"+
"Content-Length: 12\r\n" +
"Content-Type: text/plain; charset=utf-8\r\n" +
"\r\n" +
"123456789\uA74A");
assertEquals("POST",tester.getMethod());
assertEquals("/uri\uA74A",tester.getURI());
assertEquals("HTTP/1.1",tester.getVersion());
assertEquals("fakehost",tester.getHeader("Host"));
assertEquals("text/plain; charset=utf-8",tester.getContentType());
assertEquals("utf-8",tester.getCharacterEncoding());
assertEquals("123456789\uA74A",tester.getContent());
}
public void testHead() throws Exception
{
String headResponse = "HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html\r\n"+
"Content-Length: 22\r\n"+
"\r\n";
HttpTester tester = new HttpTester();
tester.parse(headResponse, true);
assertEquals(200, tester.getStatus());
assertEquals("22", tester.getHeader("Content-Length"));
assertEquals("text/html",tester.getContentType());
System.err.println(tester.getContent());
}
}

View File

@ -1,343 +0,0 @@
package org.eclipse.jetty.testing;
// ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
import java.io.IOException;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.http.HttpException;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.util.IO;
public class ServletTest extends TestCase
{
ServletTester tester;
/* ------------------------------------------------------------ */
@Override
protected void setUp() throws Exception
{
super.setUp();
tester=new ServletTester();
tester.setContextPath("/context");
tester.addServlet(TestServlet.class, "/servlet/*");
tester.addServlet(HelloServlet.class, "/hello/*");
tester.addServlet(ExceptServlet.class, "/except/*");
tester.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/");
tester.start();
}
/* ------------------------------------------------------------ */
@Override
protected void tearDown() throws Exception
{
tester.stop();
tester=null;
super.tearDown();
}
/* ------------------------------------------------------------ */
public void testServletTesterRaw() throws Exception
{
// Raw HTTP test requests
String requests=
"GET /context/servlet/info?query=foo HTTP/1.1\r\n"+
"Host: tester\r\n"+
"\r\n"+
"GET /context/hello HTTP/1.1\r\n"+
"Host: tester\r\n"+
"\r\n";
String responses = tester.getResponses(requests);
String expected=
"HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html;charset=ISO-8859-1\r\n"+
"Content-Length: 21\r\n"+
"\r\n"+
"<h1>Test Servlet</h1>" +
"HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html;charset=ISO-8859-1\r\n"+
"Content-Length: 22\r\n"+
"\r\n"+
"<h1>Hello Servlet</h1>";
assertEquals(expected,responses);
}
/* ------------------------------------------------------------ */
public void testServletTesterClient() throws Exception
{
String base_url=tester.createSocketConnector(true);
URL url = new URL(base_url+"/context/hello/info");
String result = IO.toString(url.openStream());
assertEquals("<h1>Hello Servlet</h1>",result);
}
/* ------------------------------------------------------------ */
public void testHttpTester() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
// test GET
request.setMethod("GET");
request.setVersion("HTTP/1.0");
request.setHeader("Host","tester");
request.setURI("/context/hello/info");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
assertEquals(200,response.getStatus());
assertEquals("<h1>Hello Servlet</h1>",response.getContent());
// test GET with content
request.setMethod("POST");
request.setContent("<pre>Some Test Content</pre>");
request.setHeader("Content-Type","text/html");
response.parse(tester.getResponses(request.generate()));
assertTrue(response.getMethod()==null);
assertEquals(200,response.getStatus());
assertEquals("<h1>Hello Servlet</h1><pre>Some Test Content</pre>",response.getContent());
// test redirection
request.setMethod("GET");
request.setURI("/context");
request.setContent(null);
response.parse(tester.getResponses(request.generate()));
assertEquals(302,response.getStatus());
assertEquals("http://tester/context/",response.getHeader("location"));
// test not found
request.setURI("/context/xxxx");
response.parse(tester.getResponses(request.generate()));
assertEquals(404,response.getStatus());
}
/* ------------------------------------------------------------ */
public void testBigPost() throws Exception
{
// generated and parsed test
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
String content = "0123456789abcdef";
content+=content;
content+=content;
content+=content;
content+=content;
content+=content;
content+=content;
content+=content;
content+=content;
content+=content;
content+=content;
content+=content;
content+=content;
content+="!";
request.setMethod("POST");
request.setVersion("HTTP/1.1");
request.setURI("/context/hello/info");
request.setHeader("Host","tester");
request.setHeader("Content-Type","text/plain");
request.setContent(content);
String r=request.generate();
r = tester.getResponses(r);
response.parse(r);
assertTrue(response.getMethod()==null);
assertEquals(200,response.getStatus());
assertEquals("<h1>Hello Servlet</h1>"+content,response.getContent());
}
/* ------------------------------------------------------------ */
public void testCharset()
throws Exception
{
byte[] content_iso_8859_1="abcd=1234&AAA=xxx".getBytes("iso8859-1");
byte[] content_utf_8="abcd=1234&AAA=xxx".getBytes("utf-8");
byte[] content_utf_16="abcd=1234&AAA=xxx".getBytes("utf-16");
String request_iso_8859_1=
"POST /context/servlet/post HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: application/x-www-form-urlencoded\r\n"+
"Content-Length: "+content_iso_8859_1.length+"\r\n"+
"\r\n";
String request_utf_8=
"POST /context/servlet/post HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n"+
"Content-Length: "+content_utf_8.length+"\r\n"+
"\r\n";
String request_utf_16=
"POST /context/servlet/post HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"Content-Type: application/x-www-form-urlencoded; charset=utf-16\r\n"+
"Content-Length: "+content_utf_16.length+"\r\n"+
"Connection: close\r\n"+
"\r\n";
ByteArrayBuffer out = new ByteArrayBuffer(4096);
out.put(request_iso_8859_1.getBytes("iso8859-1"));
out.put(content_iso_8859_1);
out.put(request_utf_8.getBytes("iso8859-1"));
out.put(content_utf_8);
out.put(request_utf_16.getBytes("iso8859-1"));
out.put(content_utf_16);
ByteArrayBuffer responses = tester.getResponses(out);
String expected=
"HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html;charset=ISO-8859-1\r\n"+
"Content-Length: 21\r\n"+
"\r\n"+
"<h1>Test Servlet</h1>"+
"HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html;charset=ISO-8859-1\r\n"+
"Content-Length: 21\r\n"+
"\r\n"+
"<h1>Test Servlet</h1>"+
"HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html;charset=ISO-8859-1\r\n"+
"Connection: close\r\n"+
"\r\n"+
"<h1>Test Servlet</h1>";
assertEquals(expected,responses.toString());
}
/* ------------------------------------------------------------ */
public void testExcept() throws Exception
{
String request0=
"GET /context/except/io HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"\r\n"+
"GET /context/except/http HTTP/1.1\r\n"+
"Host: whatever\r\n"+
"\r\n";
ByteArrayBuffer out = new ByteArrayBuffer(4096);
out.put(request0.getBytes("iso8859-1"));
String responses = tester.getResponses(out).toString();
int offset = responses.indexOf("HTTP/1.1 500");
assertTrue(offset>=0);
offset = responses.indexOf("Content-Length: ",offset);
assertTrue(offset>0);
offset = responses.indexOf("<h2>HTTP ERROR 500</h2>",offset);
assertTrue(offset>0);
offset = responses.indexOf("IOException: testing",offset);
assertTrue(offset>0);
offset = responses.indexOf("</html>",offset);
assertTrue(offset>0);
offset = responses.indexOf("HTTP/1.1 499",offset);
assertTrue(offset>0);
offset = responses.indexOf("Content-Length: ",offset);
assertTrue(offset>0);
}
/* ------------------------------------------------------------ */
public static class HelloServlet extends HttpServlet
{
private static final long serialVersionUID=2779906630657190712L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.getWriter().print("<h1>Hello Servlet</h1>");
if (request.getContentLength()>0)
response.getWriter().write(IO.toString(request.getInputStream()));
}
}
public static class TestServlet extends HttpServlet
{
private static final long serialVersionUID=2779906630657190712L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
assertEquals("/context",request.getContextPath());
assertEquals("/servlet",request.getServletPath());
assertEquals("/post",request.getPathInfo());
assertEquals(2,request.getParameterMap().size());
assertEquals("1234",request.getParameter("abcd"));
assertEquals("xxx",request.getParameter("AAA"));
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print("<h1>Test Servlet</h1>");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
assertEquals("/context",request.getContextPath());
assertEquals("/servlet",request.getServletPath());
assertEquals("/info",request.getPathInfo());
assertEquals("query=foo",request.getQueryString());
assertEquals(1,request.getParameterMap().size());
assertEquals(1,request.getParameterValues("query").length);
assertEquals("foo",request.getParameter("query"));
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print("<h1>Test Servlet</h1>");
}
}
public static class ExceptServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if ("/http".equals(request.getPathInfo()))
throw new HttpException(499);
if ("/runtime".equals(request.getPathInfo()))
throw new RuntimeException("testing");
if ("/error".equals(request.getPathInfo()))
throw new Error("testing");
throw new IOException("testing");
}
}
}

View File

@ -179,12 +179,6 @@
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>test-jetty-servlet</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jmx</artifactId>