298236 Additional unit tests for jetty-client

git-svn-id: svn+ssh://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk@1412 7e9141cc-0065-0410-87d8-b60c137991c4
This commit is contained in:
Greg Wilkins 2010-03-26 17:04:26 +00:00
parent 9e04c27078
commit 889e7eb728
10 changed files with 890 additions and 31 deletions

View File

@ -1,8 +1,9 @@
jetty-7.0.2.SNAPSHOT
+ 306783 - NPE in StdErrLog when Throwable is null
+ 306840 - Suppress content-length in requests with no content
+ 306880 - Support for UPGRADE in HttpClient
+ 306884 - Suspend with timeout <=0 never expires
+ 298236 Additional unit tests for jetty-client
+ 306783 NPE in StdErrLog when Throwable is null
+ 306840 Suppress content-length in requests with no content
+ 306880 Support for UPGRADE in HttpClient
+ 306884 Suspend with timeout <=0 never expires
jetty-7.0.2.RC0
+ JSON parses NaN as null

View File

@ -13,6 +13,7 @@
package org.eclipse.jetty.client;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@ -68,6 +69,7 @@ public class ContentExchangeTest
private Realm _realm;
private String _protocol;
private String _baseUrl;
private String _requestContent;
public void setUp()
throws Exception
@ -164,6 +166,26 @@ public class ContentExchangeTest
assertEquals(HttpStatus.OK_200,responseStatus);
}
public void testPost() throws Exception
{
startClient(_realm);
ContentExchange postExchange = new ContentExchange();
postExchange.setURL(getBaseUrl() + "test");
postExchange.setMethod(HttpMethods.POST);
postExchange.setRequestContent(new ByteArrayBuffer(_content.getBytes()));
_client.send(postExchange);
int state = postExchange.waitForDone();
int responseStatus = postExchange.getResponseStatus();
stopClient();
assertEquals(HttpStatus.OK_200,responseStatus);
assertEquals(_content,_requestContent);
}
protected void configureServer(Server server)
throws Exception
{
@ -172,7 +194,7 @@ public class ContentExchangeTest
SelectChannelConnector connector = new SelectChannelConnector();
server.addConnector(connector);
Handler handler = new PutHandler(getBasePath());
Handler handler = new TestHandler(getBasePath());
ServletContextHandler root = new ServletContextHandler();
root.setContextPath("/");
@ -263,10 +285,10 @@ public class ContentExchangeTest
}
}
protected static class PutHandler extends AbstractHandler {
protected class TestHandler extends AbstractHandler {
private final String resourcePath;
public PutHandler(String repositoryPath) {
public TestHandler(String repositoryPath) {
this.resourcePath = repositoryPath;
}
@ -274,29 +296,51 @@ public class ContentExchangeTest
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
if (baseRequest.isHandled() || !baseRequest.getMethod().equals("PUT")) {
if (baseRequest.isHandled())
{
return;
}
baseRequest.setHandled(true);
OutputStream out = null;
File file = new File(resourcePath, URLDecoder.decode(request.getPathInfo()));
file.getParentFile().mkdirs();
file.deleteOnExit();
if (baseRequest.getMethod().equals("PUT"))
{
baseRequest.setHandled(true);
FileOutputStream out = new FileOutputStream(file);
ServletInputStream in = request.getInputStream();
try
{
copyStream( in, out );
}
finally
{
in.close();
out.close();
File file = new File(resourcePath, URLDecoder.decode(request.getPathInfo()));
file.getParentFile().mkdirs();
file.deleteOnExit();
out = new FileOutputStream(file);
response.setStatus(HttpServletResponse.SC_CREATED);
}
if (baseRequest.getMethod().equals("POST"))
{
baseRequest.setHandled(true);
out = new ByteArrayOutputStream();
response.setStatus(HttpServletResponse.SC_OK);
}
if (out != null)
{
ServletInputStream in = request.getInputStream();
try
{
copyStream( in, out );
}
finally
{
in.close();
out.close();
}
if (!(out instanceof FileOutputStream))
_requestContent = out.toString();
}
response.setStatus(HttpServletResponse.SC_CREATED);
}
}
}

View File

@ -89,11 +89,39 @@ public class ErrorStatusTest
doGetFail(HttpStatus.INTERNAL_SERVER_ERROR_500);
}
public void testPostBadRequest()
throws Exception
{
doPostFail(HttpStatus.BAD_REQUEST_400);
}
public void testPostUnauthorized()
throws Exception
{
doPostFail(HttpStatus.UNAUTHORIZED_401);
}
public void testPostForbidden()
throws Exception
{
doPostFail(HttpStatus.FORBIDDEN_403);
}
public void testPostNotFound()
throws Exception
{
doPostFail(HttpStatus.NOT_FOUND_404);
}
public void testPostServerError()
throws Exception
{
doPostFail(HttpStatus.INTERNAL_SERVER_ERROR_500);
}
protected void doPutFail(int status)
throws Exception
{
// System.err.println(getName());
startClient(getRealm());
ContentExchange putExchange = new ContentExchange();
@ -115,8 +143,6 @@ public class ErrorStatusTest
protected void doGetFail(int status)
throws Exception
{
// System.err.println(getName());
startClient(getRealm());
ContentExchange getExchange = new ContentExchange();
@ -138,6 +164,27 @@ public class ErrorStatusTest
assertEquals(status, responseStatus);
}
protected void doPostFail(int status)
throws Exception
{
startClient(getRealm());
ContentExchange postExchange = new ContentExchange();
postExchange.setURL(getBaseUrl() + "test");
postExchange.setMethod(HttpMethods.POST);
postExchange.setRequestHeader("X-Response-Status",Integer.toString(status));
postExchange.setRequestContent(new ByteArrayBuffer(getContent().getBytes()));
getClient().send(postExchange);
int state = postExchange.waitForDone();
int responseStatus = postExchange.getResponseStatus();
stopClient();
assertEquals(status, responseStatus);
}
protected void configureServer(Server server)
throws Exception
{
@ -154,10 +201,10 @@ public class ErrorStatusTest
root.addServlet( servletHolder, "/*" );
Handler status = new StatusHandler();
Handler puthdl = new PutHandler(getBasePath());
Handler test = new TestHandler(getBasePath());
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[]{status, puthdl, root});
handlers.setHandlers(new Handler[]{status, test, root});
server.setHandler( handlers );
}

View File

@ -0,0 +1,147 @@
// ========================================================================
// Copyright (c) 2009-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.client;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.eclipse.jetty.http.HttpMethods;
import org.eclipse.jetty.http.HttpStatus;
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.server.nio.SelectChannelConnector;
public class HttpHeadersTest extends TestCase
{
private static String _content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis felis nunc. "
+ "Quisque suscipit mauris et ante auctor ornare rhoncus lacus aliquet. Pellentesque "
+ "habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. "
+ "Vestibulum sit amet felis augue, vel convallis dolor. Cras accumsan vehicula diam "
+ "at faucibus. Etiam in urna turpis, sed congue mi. Morbi et lorem eros. Donec vulputate "
+ "velit in risus suscipit lobortis. Aliquam id urna orci, nec sollicitudin ipsum. "
+ "Cras a orci turpis. Donec suscipit vulputate cursus. Mauris nunc tellus, fermentum "
+ "eu auctor ut, mollis at diam. Quisque porttitor ultrices metus, vitae tincidunt massa "
+ "sollicitudin a. Vivamus porttitor libero eget purus hendrerit cursus. Integer aliquam "
+ "consequat mauris quis luctus. Cras enim nibh, dignissim eu faucibus ac, mollis nec neque. "
+ "Aliquam purus mauris, consectetur nec convallis lacinia, porta sed ante. Suspendisse "
+ "et cursus magna. Donec orci enim, molestie a lobortis eu, imperdiet vitae neque.";
private File _docRoot;
private Server _server;
private Connector _connector;
private TestHeaderHandler _handler;
private int _port;
public void setUp() throws Exception
{
_docRoot = new File("target/test-output/docroot/");
_docRoot.mkdirs();
_docRoot.deleteOnExit();
startServer();
}
public void tearDown() throws Exception
{
stopServer();
}
public void testHttpHeaders() throws Exception
{
HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
client.start();
String requestUrl = "http://localhost:" + _port + "/header";
ContentExchange exchange = new ContentExchange();
exchange.setURL(requestUrl);
exchange.setMethod(HttpMethods.GET);
exchange.addRequestHeader("User-Agent","Jetty-Client/7.0");
client.send(exchange);
int state = exchange.waitForDone();
String content = "";
int responseStatus = exchange.getResponseStatus();
if (responseStatus == HttpStatus.OK_200)
{
content = exchange.getResponseContent();
}
assertEquals(HttpStatus.OK_200,responseStatus);
assertEquals(_content,content);
assertEquals("Jetty-Client/7.0",_handler.headers.get("User-Agent"));
}
protected void startServer() throws Exception
{
_server = new Server(0);
_connector = new SelectChannelConnector();
_server.addConnector(_connector);
_handler = new TestHeaderHandler();
_server.setHandler(_handler);
_server.start();
_port = _connector.getLocalPort();
}
protected void stopServer() throws Exception
{
if (_server != null)
{
_server.stop();
_server = null;
}
}
private static class TestHeaderHandler extends AbstractHandler
{
protected Map<String, String> headers;
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
if (baseRequest.isHandled())
return;
headers = new HashMap<String, String>();
for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();)
{
String name = (String)e.nextElement();
headers.put(name,request.getHeader(name));
}
response.setContentType("text/plain");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print(_content);
baseRequest.setHandled(true);
}
}
}

View File

@ -90,7 +90,7 @@ public class SecuredContentExchangeTest
servletHolder.setInitParameter( "gzip", "true" );
root.addServlet( servletHolder, "/*" );
Handler handler = new PutHandler(getBasePath());
Handler handler = new TestHandler(getBasePath());
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[]{handler, root});

View File

@ -0,0 +1,166 @@
// ========================================================================
// Copyright (c) 2009-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.client;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jetty.client.ContentExchangeTest.TestHandler;
import org.eclipse.jetty.client.security.Realm;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.security.Constraint;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class SecuredErrorStatusTest
extends ErrorStatusTest
{
private Realm _testRealm;
private Realm _dummyRealm;
public void testPutUnauthorized()
throws Exception
{
setRealm(null);
doPutFail(HttpStatus.UNAUTHORIZED_401);
setRealm(_testRealm);
}
public void testPutWrongPassword()
throws Exception
{
setRealm(_dummyRealm);
doPutFail(HttpStatus.UNAUTHORIZED_401);
setRealm(_testRealm);
}
public void testGetUnauthorized()
throws Exception
{
setRealm(null);
doGetFail(HttpStatus.UNAUTHORIZED_401);
setRealm(_testRealm);
}
public void testGetWrongPassword()
throws Exception
{
setRealm(_dummyRealm);
doGetFail(HttpStatus.UNAUTHORIZED_401);
setRealm(_testRealm);
}
protected void configureServer(Server server)
throws Exception
{
setProtocol("http");
_testRealm = new Realm()
{
public String getId()
{
return "MyRealm";
}
public String getPrincipal()
{
return "jetty";
}
public String getCredentials()
{
return "jetty";
}
};
_dummyRealm = new Realm()
{
public String getId()
{
return "MyRealm";
}
public String getPrincipal()
{
return "jetty";
}
public String getCredentials()
{
return "dummy";
}
};
setRealm(_testRealm);
SelectChannelConnector connector = new SelectChannelConnector();
server.addConnector(connector);
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
Set<String> knownRoles = new HashSet<String>();
knownRoles.add("user");
knownRoles.add("admin");
security.setConstraintMappings(new ConstraintMapping[] {mapping}, knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);
ServletContextHandler root = new ServletContextHandler();
root.setContextPath("/");
root.setResourceBase(getBasePath());
ServletHolder servletHolder = new ServletHolder( new DefaultServlet() );
servletHolder.setInitParameter( "gzip", "true" );
root.addServlet( servletHolder, "/*" );
Handler status = new StatusHandler();
Handler test = new TestHandler(getBasePath());
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[]{status, test, root});
security.setHandler(handlers);
}
}

View File

@ -0,0 +1,55 @@
// ========================================================================
// Copyright (c) 2009-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.client;
import java.io.File;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class SslContentExchangeTest
extends ContentExchangeTest
{
protected void configureServer(Server server)
throws Exception
{
setProtocol("https");
SslSelectChannelConnector connector = new SslSelectChannelConnector();
String keystore = new File("src/test/resources/keystore").getAbsolutePath();
connector.setKeystore(keystore);
connector.setPassword("storepwd");
connector.setKeyPassword("keypwd");
server.addConnector(connector);
Handler handler = new TestHandler(getBasePath());
ServletContextHandler root = new ServletContextHandler();
root.setContextPath("/");
root.setResourceBase(getBasePath());
ServletHolder servletHolder = new ServletHolder( new DefaultServlet() );
servletHolder.setInitParameter( "gzip", "true" );
root.addServlet( servletHolder, "/*" );
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[]{handler, root});
server.setHandler( handlers );
}
}

View File

@ -0,0 +1,104 @@
// ========================================================================
// Copyright (c) 2009-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.client;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jetty.client.security.Realm;
import org.eclipse.jetty.http.security.Constraint;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class SslSecuredContentExchangeTest
extends ContentExchangeTest
{
protected void configureServer(Server server)
throws Exception
{
setProtocol("https");
setRealm(new Realm()
{
public String getId()
{
return "MyRealm";
}
public String getPrincipal()
{
return "jetty";
}
public String getCredentials()
{
return "jetty";
}
});
SslSelectChannelConnector connector = new SslSelectChannelConnector();
String keystore = new File("src/test/resources/keystore").getAbsolutePath();
connector.setKeystore(keystore);
connector.setPassword("storepwd");
connector.setKeyPassword("keypwd");
server.addConnector(connector);
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
Set<String> knownRoles = new HashSet<String>();
knownRoles.add("user");
knownRoles.add("admin");
security.setConstraintMappings(new ConstraintMapping[] {mapping}, knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);
ServletContextHandler root = new ServletContextHandler();
root.setContextPath("/");
root.setResourceBase(getBasePath());
ServletHolder servletHolder = new ServletHolder( new DefaultServlet() );
servletHolder.setInitParameter( "gzip", "true" );
root.addServlet( servletHolder, "/*" );
Handler handler = new TestHandler(getBasePath());
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[]{handler, root});
security.setHandler(handlers);
}
}

View File

@ -0,0 +1,166 @@
// ========================================================================
// Copyright (c) 2009-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.client;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jetty.client.ContentExchangeTest.TestHandler;
import org.eclipse.jetty.client.security.Realm;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.security.Constraint;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class SslSecuredErrorStatusTest
extends ErrorStatusTest
{
private Realm _testRealm;
private Realm _dummyRealm;
public void testPutUnauthorized()
throws Exception
{
setRealm(null);
doPutFail(HttpStatus.UNAUTHORIZED_401);
setRealm(_testRealm);
}
public void testPutWrongPassword()
throws Exception
{
setRealm(_dummyRealm);
doPutFail(HttpStatus.UNAUTHORIZED_401);
setRealm(_testRealm);
}
public void testGetUnauthorized()
throws Exception
{
setRealm(null);
doGetFail(HttpStatus.UNAUTHORIZED_401);
setRealm(_testRealm);
}
public void testGetWrongPassword()
throws Exception
{
setRealm(_dummyRealm);
doGetFail(HttpStatus.UNAUTHORIZED_401);
setRealm(_testRealm);
}
protected void configureServer(Server server)
throws Exception
{
setProtocol("http");
_testRealm = new Realm()
{
public String getId()
{
return "MyRealm";
}
public String getPrincipal()
{
return "jetty";
}
public String getCredentials()
{
return "jetty";
}
};
_dummyRealm = new Realm()
{
public String getId()
{
return "MyRealm";
}
public String getPrincipal()
{
return "jetty";
}
public String getCredentials()
{
return "dummy";
}
};
setRealm(_testRealm);
SelectChannelConnector connector = new SelectChannelConnector();
server.addConnector(connector);
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
Set<String> knownRoles = new HashSet<String>();
knownRoles.add("user");
knownRoles.add("admin");
security.setConstraintMappings(new ConstraintMapping[] {mapping}, knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);
ServletContextHandler root = new ServletContextHandler();
root.setContextPath("/");
root.setResourceBase(getBasePath());
ServletHolder servletHolder = new ServletHolder( new DefaultServlet() );
servletHolder.setInitParameter( "gzip", "true" );
root.addServlet( servletHolder, "/*" );
Handler status = new StatusHandler();
Handler test = new TestHandler(getBasePath());
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[]{status, test, root});
security.setHandler(handlers);
}
}

View File

@ -0,0 +1,129 @@
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.util.resource.FileResource;
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);
}
}