JETTY-1354 Added jetty-nested

git-svn-id: svn+ssh://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk@2941 7e9141cc-0065-0410-87d8-b60c137991c4
This commit is contained in:
Greg Wilkins 2011-03-31 07:30:08 +00:00
parent 8d5b3c5261
commit f7a0d7d134
17 changed files with 1673 additions and 7 deletions

View File

@ -19,6 +19,7 @@ jetty-7.3.2-SNAPSHOT
+ 341394 Remove 'Unavailable' JMX attributes of WebAppContext MBean
+ 341439 Blocking HttpClient does not use soTimeout for timeouts
+ JETTY-1245 Pooled Buffers implementation
+ JETTY-1354 Added jetty-nested
+ Ensure generated fragment names are unique
+ Added extra session removal test

23
jetty-nested/pom.xml Normal file
View File

@ -0,0 +1,23 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-project</artifactId>
<version>7.3.2-SNAPSHOT</version>
</parent>
<artifactId>jetty-nested</artifactId>
<name>Jetty :: Nested</name>
<packaging>war</packaging>
<build>
<plugins>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,948 @@
package org.eclipse.jetty.nested;
// ========================================================================
// Copyright (c) 1996-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.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.UnavailableException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationListener;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.log.Log;
/* ------------------------------------------------------------ */
/** Dump Servlet Request.
*
*/
public class Dump extends HttpServlet
{
boolean fixed;
/* ------------------------------------------------------------ */
@Override
public void init(ServletConfig config) throws ServletException
{
super.init(config);
if (config.getInitParameter("unavailable")!=null && !fixed)
{
fixed=true;
throw new UnavailableException("Unavailable test",Integer.parseInt(config.getInitParameter("unavailable")));
}
}
/* ------------------------------------------------------------ */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
/* ------------------------------------------------------------ */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
{
// Handle a dump of data
final String data= request.getParameter("data");
final String chars= request.getParameter("chars");
final String block= request.getParameter("block");
final String dribble= request.getParameter("dribble");
final boolean flush= request.getParameter("flush")!=null?Boolean.parseBoolean(request.getParameter("flush")):false;
if(request.getPathInfo()!=null && request.getPathInfo().toLowerCase().indexOf("script")!=-1)
{
response.sendRedirect(response.encodeRedirectURL(getServletContext().getContextPath() + "/dump/info"));
return;
}
request.setCharacterEncoding("UTF-8");
if (request.getParameter("empty")!=null)
{
response.setStatus(200);
response.flushBuffer();
return;
}
if (request.getParameter("sleep")!=null)
{
try
{
long s = Long.parseLong(request.getParameter("sleep"));
if (request.getHeader(HttpHeaders.EXPECT)!=null &&request.getHeader(HttpHeaders.EXPECT).indexOf("102")>=0)
{
Thread.sleep(s/2);
response.sendError(102);
Thread.sleep(s/2);
}
else
Thread.sleep(s);
}
catch (InterruptedException e)
{
return;
}
catch (Exception e)
{
throw new ServletException(e);
}
}
if (request.getAttribute("RESUME")==null && request.getParameter("resume")!=null)
{
request.setAttribute("RESUME",Boolean.TRUE);
final long resume=Long.parseLong(request.getParameter("resume"));
new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(resume);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
Continuation continuation = ContinuationSupport.getContinuation(request);
continuation.resume();
}
}).start();
}
if (request.getParameter("complete")!=null)
{
final long complete=Long.parseLong(request.getParameter("complete"));
new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(complete);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
try
{
response.setContentType("text/html");
response.getOutputStream().println("<h1>COMPLETED</h1>");
Continuation continuation = ContinuationSupport.getContinuation(request);
continuation.complete();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
}
if (request.getParameter("suspend")!=null && request.getAttribute("SUSPEND")!=Boolean.TRUE)
{
request.setAttribute("SUSPEND",Boolean.TRUE);
try
{
Continuation continuation = ContinuationSupport.getContinuation(request);
continuation.setTimeout(Long.parseLong(request.getParameter("suspend")));
continuation.suspend();
continuation.addContinuationListener(new ContinuationListener()
{
public void onTimeout(Continuation continuation)
{
response.addHeader("Dump","onTimeout");
try
{
dump(response,data,chars,block,dribble,flush);
continuation.complete();
}
catch (IOException e)
{
Log.ignore(e);
}
}
public void onComplete(Continuation continuation)
{
response.addHeader("Dump","onComplete");
}
});
continuation.undispatch();
}
catch(Exception e)
{
throw new ServletException(e);
}
}
request.setAttribute("Dump", this);
getServletContext().setAttribute("Dump",this);
// getServletContext().log("dump "+request.getRequestURI());
// Force a content length response
String length= request.getParameter("length");
if (length != null && length.length() > 0)
{
response.setContentLength(Integer.parseInt(length));
}
// Handle a dump of data
if (dump(response,data,chars,block,dribble,flush))
return;
// handle an exception
String info= request.getPathInfo();
if (info != null && info.endsWith("Exception"))
{
try
{
throw (Throwable) Thread.currentThread().getContextClassLoader().loadClass(info.substring(1)).newInstance();
}
catch (Throwable th)
{
throw new ServletException(th);
}
}
// test a reset
String reset= request.getParameter("reset");
if (reset != null && reset.length() > 0)
{
response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
response.setHeader("SHOULD_NOT","BE SEEN");
response.reset();
}
// handle an redirect
String redirect= request.getParameter("redirect");
if (redirect != null && redirect.length() > 0)
{
response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
response.sendRedirect(response.encodeRedirectURL(redirect));
try
{
response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
}
catch(IOException e)
{
// ignored as stream is closed.
}
return;
}
// handle an error
String error= request.getParameter("error");
if (error != null && error.length() > 0 && request.getAttribute("javax.servlet.error.status_code")==null)
{
response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
response.sendError(Integer.parseInt(error));
try
{
response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
}
catch(IllegalStateException e)
{
try
{
response.getWriter().println("NOR THIS!!");
}
catch(IOException e2){}
}
catch(IOException e){}
return;
}
// Handle a extra headers
String headers= request.getParameter("headers");
if (headers != null && headers.length() > 0)
{
long h=Long.parseLong(headers);
for (int i=0;i<h;i++)
response.addHeader("Header"+i,"Value"+i);
}
String buffer= request.getParameter("buffer");
if (buffer != null && buffer.length() > 0)
response.setBufferSize(Integer.parseInt(buffer));
String charset= request.getParameter("charset");
if (charset==null)
charset="UTF-8";
response.setCharacterEncoding(charset);
response.setContentType("text/html");
if (info != null && info.indexOf("Locale/") >= 0)
{
try
{
String locale_name= info.substring(info.indexOf("Locale/") + 7);
Field f= java.util.Locale.class.getField(locale_name);
response.setLocale((Locale)f.get(null));
}
catch (Exception e)
{
e.printStackTrace();
response.setLocale(Locale.getDefault());
}
}
String cn= request.getParameter("cookie");
String cv=request.getParameter("cookiev");
if (cn!=null && cv!=null)
{
Cookie cookie= new Cookie(cn, cv);
if (request.getParameter("version")!=null)
cookie.setVersion(Integer.parseInt(request.getParameter("version")));
cookie.setComment("Cookie from dump servlet");
response.addCookie(cookie);
}
String pi= request.getPathInfo();
if (pi != null && pi.startsWith("/ex"))
{
OutputStream out= response.getOutputStream();
out.write("</H1>This text should be reset</H1>".getBytes());
if ("/ex0".equals(pi))
throw new ServletException("test ex0", new Throwable());
else if ("/ex1".equals(pi))
throw new IOException("test ex1");
else if ("/ex2".equals(pi))
throw new UnavailableException("test ex2");
else if (pi.startsWith("/ex3/"))
throw new UnavailableException("test ex3",Integer.parseInt(pi.substring(5)));
throw new RuntimeException("test");
}
if ("true".equals(request.getParameter("close")))
response.setHeader("Connection","close");
String buffered= request.getParameter("buffered");
PrintWriter pout=null;
try
{
pout =response.getWriter();
}
catch(IllegalStateException e)
{
pout=new PrintWriter(new OutputStreamWriter(response.getOutputStream(),charset));
}
if (buffered!=null)
pout = new PrintWriter(new BufferedWriter(pout,Integer.parseInt(buffered)));
try
{
pout.write("<html>\n<body>\n");
pout.write("<h1>Dump Servlet</h1>\n");
pout.write("<table width=\"95%\">");
pout.write("<tr>\n");
pout.write("<th align=\"right\">getMethod:&nbsp;</th>");
pout.write("<td>" + notag(request.getMethod())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getContentLength:&nbsp;</th>");
pout.write("<td>"+Integer.toString(request.getContentLength())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getContentType:&nbsp;</th>");
pout.write("<td>"+notag(request.getContentType())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getRequestURI:&nbsp;</th>");
pout.write("<td>"+notag(request.getRequestURI())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getRequestURL:&nbsp;</th>");
pout.write("<td>"+notag(request.getRequestURL().toString())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getContextPath:&nbsp;</th>");
pout.write("<td>"+request.getContextPath()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getServletPath:&nbsp;</th>");
pout.write("<td>"+notag(request.getServletPath())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getPathInfo:&nbsp;</th>");
pout.write("<td>"+notag(request.getPathInfo())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getPathTranslated:&nbsp;</th>");
pout.write("<td>"+notag(request.getPathTranslated())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getQueryString:&nbsp;</th>");
pout.write("<td>"+notag(request.getQueryString())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getProtocol:&nbsp;</th>");
pout.write("<td>"+request.getProtocol()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getScheme:&nbsp;</th>");
pout.write("<td>"+request.getScheme()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getServerName:&nbsp;</th>");
pout.write("<td>"+notag(request.getServerName())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getServerPort:&nbsp;</th>");
pout.write("<td>"+Integer.toString(request.getServerPort())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getLocalName:&nbsp;</th>");
pout.write("<td>"+request.getLocalName()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getLocalAddr:&nbsp;</th>");
pout.write("<td>"+request.getLocalAddr()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getLocalPort:&nbsp;</th>");
pout.write("<td>"+Integer.toString(request.getLocalPort())+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getRemoteUser:&nbsp;</th>");
pout.write("<td>"+request.getRemoteUser()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getUserPrincipal:&nbsp;</th>");
pout.write("<td>"+request.getUserPrincipal()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getRemoteAddr:&nbsp;</th>");
pout.write("<td>"+request.getRemoteAddr()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getRemoteHost:&nbsp;</th>");
pout.write("<td>"+request.getRemoteHost()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getRemotePort:&nbsp;</th>");
pout.write("<td>"+request.getRemotePort()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getRequestedSessionId:&nbsp;</th>");
pout.write("<td>"+request.getRequestedSessionId()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">isSecure():&nbsp;</th>");
pout.write("<td>"+request.isSecure()+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">isUserInRole(admin):&nbsp;</th>");
pout.write("<td>"+request.isUserInRole("admin")+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getLocale:&nbsp;</th>");
pout.write("<td>"+request.getLocale()+"</td>");
Enumeration locales= request.getLocales();
while (locales.hasMoreElements())
{
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getLocales:&nbsp;</th>");
pout.write("<td>"+locales.nextElement()+"</td>");
}
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Other HTTP Headers:</big></th>");
Enumeration h= request.getHeaderNames();
String name;
while (h.hasMoreElements())
{
name= (String)h.nextElement();
Enumeration h2= request.getHeaders(name);
while (h2.hasMoreElements())
{
String hv= (String)h2.nextElement();
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">"+notag(name)+":&nbsp;</th>");
pout.write("<td>"+notag(hv)+"</td>");
}
}
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Parameters:</big></th>");
h= request.getParameterNames();
while (h.hasMoreElements())
{
name= (String)h.nextElement();
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">"+notag(name)+":&nbsp;</th>");
pout.write("<td>"+notag(request.getParameter(name))+"</td>");
String[] values= request.getParameterValues(name);
if (values == null)
{
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">"+notag(name)+" Values:&nbsp;</th>");
pout.write("<td>"+"NULL!"+"</td>");
}
else if (values.length > 1)
{
for (int i= 0; i < values.length; i++)
{
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">"+notag(name)+"["+i+"]:&nbsp;</th>");
pout.write("<td>"+notag(values[i])+"</td>");
}
}
}
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Cookies:</big></th>");
Cookie[] cookies = request.getCookies();
for (int i=0; cookies!=null && i<cookies.length;i++)
{
Cookie cookie = cookies[i];
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">"+notag(cookie.getName())+":&nbsp;</th>");
pout.write("<td>"+notag(cookie.getValue())+"</td>");
}
String content_type=request.getContentType();
if (content_type!=null &&
!content_type.startsWith("application/x-www-form-urlencoded") &&
!content_type.startsWith("multipart/form-data"))
{
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" valign=\"top\" colspan=\"2\"><big><br/>Content:</big></th>");
pout.write("</tr><tr>\n");
pout.write("<td><pre>");
char[] content= new char[4096];
int len;
try{
Reader in=request.getReader();
while((len=in.read(content))>=0)
pout.write(notag(new String(content,0,len)));
}
catch(IOException e)
{
pout.write(e.toString());
}
pout.write("</pre></td>");
}
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Attributes:</big></th>");
Enumeration a= request.getAttributeNames();
while (a.hasMoreElements())
{
name= (String)a.nextElement();
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>");
Object value=request.getAttribute(name);
if (value instanceof File)
{
File file = (File)value;
pout.write("<td>"+"<pre>" + file.getName()+" ("+file.length()+" "+new Date(file.lastModified())+ ")</pre>"+"</td>");
}
else
pout.write("<td>"+"<pre>" + toString(request.getAttribute(name)) + "</pre>"+"</td>");
}
request.setAttribute("org.eclipse.jetty.servlet.MultiPartFilter.files",null);
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Servlet InitParameters:</big></th>");
a= getInitParameterNames();
while (a.hasMoreElements())
{
name= (String)a.nextElement();
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">"+name+":&nbsp;</th>");
pout.write("<td>"+ toString(getInitParameter(name)) +"</td>");
}
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context InitParameters:</big></th>");
a= getServletContext().getInitParameterNames();
while (a.hasMoreElements())
{
name= (String)a.nextElement();
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>");
pout.write("<td>"+ toString(getServletContext().getInitParameter(name)) + "</td>");
}
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context Attributes:</big></th>");
a= getServletContext().getAttributeNames();
while (a.hasMoreElements())
{
name= (String)a.nextElement();
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>");
pout.write("<td>"+"<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"+"</td>");
}
String res= request.getParameter("resource");
if (res != null && res.length() > 0)
{
pout.write("</tr><tr>\n");
pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Get Resource: \""+res+"\"</big></th>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getServletContext().getContext(...):&nbsp;</th>");
ServletContext context = getServletContext().getContext(res);
pout.write("<td>"+context+"</td>");
if (context!=null)
{
String cp=context.getContextPath();
if (cp==null || "/".equals(cp))
cp="";
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getServletContext().getContext(...),getRequestDispatcher(...):&nbsp;</th>");
pout.write("<td>"+getServletContext().getContext(res).getRequestDispatcher(res.substring(cp.length()))+"</td>");
}
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">this.getClass().getResource(...):&nbsp;</th>");
pout.write("<td>"+this.getClass().getResource(res)+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">this.getClass().getClassLoader().getResource(...):&nbsp;</th>");
pout.write("<td>"+this.getClass().getClassLoader().getResource(res)+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">Thread.currentThread().getContextClassLoader().getResource(...):&nbsp;</th>");
pout.write("<td>"+Thread.currentThread().getContextClassLoader().getResource(res)+"</td>");
pout.write("</tr><tr>\n");
pout.write("<th align=\"right\">getServletContext().getResource(...):&nbsp;</th>");
try{pout.write("<td>"+getServletContext().getResource(res)+"</td>");}
catch(Exception e) {pout.write("<td>"+"" +e+"</td>");}
}
pout.write("</tr></table>\n");
/* ------------------------------------------------------------ */
pout.write("<h2>Request Wrappers</h2>\n");
ServletRequest rw=request;
int w=0;
while (rw !=null)
{
pout.write((w++)+": "+rw.getClass().getName()+"<br/>");
if (rw instanceof HttpServletRequestWrapper)
rw=((HttpServletRequestWrapper)rw).getRequest();
else if (rw instanceof ServletRequestWrapper)
rw=((ServletRequestWrapper)rw).getRequest();
else
rw=null;
}
/* ------------------------------------------------------------ */
pout.write("<h2>Response Wrappers</h2>\n");
ServletResponse rsw=response;
w=0;
while (rsw !=null)
{
pout.write((w++)+": "+rsw.getClass().getName()+"<br/>");
if (rsw instanceof HttpServletResponseWrapper)
rsw=((HttpServletResponseWrapper)rsw).getResponse();
else if (rsw instanceof ServletResponseWrapper)
rsw=((ServletResponseWrapper)rsw).getResponse();
else
rsw=null;
}
pout.write("<br/>");
pout.write("<h2>International Characters (UTF-8)</h2>");
pout.write("LATIN LETTER SMALL CAPITAL AE<br/>\n");
pout.write("Directly uni encoded(\\u1d01): \u1d01<br/>");
pout.write("HTML reference (&amp;AElig;): &AElig;<br/>");
pout.write("Decimal (&amp;#7425;): &#7425;<br/>");
pout.write("Javascript unicode (\\u1d01) : <script language='javascript'>document.write(\"\u1d01\");</script><br/>");
pout.write("<br/>");
pout.write("<h2>Form to generate GET content</h2>");
pout.write("<form method=\"GET\" action=\""+response.encodeURL(getURI(request))+"\">");
pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n");
pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\">");
pout.write("</form>");
pout.write("<br/>");
pout.write("<h2>Form to generate POST content</h2>");
pout.write("<form method=\"POST\" accept-charset=\"utf-8\" action=\""+response.encodeURL(getURI(request))+"\">");
pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n");
pout.write("Select: <select multiple name=\"Select\">\n");
pout.write("<option>ValueA</option>");
pout.write("<option>ValueB1,ValueB2</option>");
pout.write("<option>ValueC</option>");
pout.write("</select><br/>");
pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>");
pout.write("</form>");
pout.write("<br/>");
pout.write("<h2>Form to generate UPLOAD content</h2>");
pout.write("<form method=\"POST\" enctype=\"multipart/form-data\" accept-charset=\"utf-8\" action=\""+
response.encodeURL(getURI(request))+(request.getQueryString()==null?"":("?"+request.getQueryString()))+
"\">");
pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"comment\"/><br/>\n");
pout.write("File 1: <input type=\"file\" name=\"file1\" /><br/>\n");
pout.write("File 2: <input type=\"file\" name=\"file2\" /><br/>\n");
pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>");
pout.write("</form>");
pout.write("<h2>Form to set Cookie</h2>");
pout.write("<form method=\"POST\" action=\""+response.encodeURL(getURI(request))+"\">");
pout.write("cookie: <input type=\"text\" name=\"cookie\" /><br/>\n");
pout.write("value: <input type=\"text\" name=\"cookiev\" /><br/>\n");
pout.write("<input type=\"submit\" name=\"Action\" value=\"setCookie\">");
pout.write("</form>\n");
pout.write("<h2>Form to get Resource</h2>");
pout.write("<form method=\"POST\" action=\""+response.encodeURL(getURI(request))+"\">");
pout.write("resource: <input type=\"text\" name=\"resource\" /><br/>\n");
pout.write("<input type=\"submit\" name=\"Action\" value=\"getResource\">");
pout.write("</form>\n");
}
catch (Exception e)
{
getServletContext().log("dump", e);
}
String lines= request.getParameter("lines");
if (lines!=null)
{
char[] line = "<span>A line of characters. Blah blah blah blah. blooble blooble</span></br>\n".toCharArray();
for (int l=Integer.parseInt(lines);l-->0;)
{
pout.write("<span>"+l+" </span>");
pout.write(line);
}
}
pout.write("</body>\n</html>\n");
pout.close();
if (pi != null)
{
if ("/ex4".equals(pi))
throw new ServletException("test ex4", new Throwable());
if ("/ex5".equals(pi))
throw new IOException("test ex5");
if ("/ex6".equals(pi))
throw new UnavailableException("test ex6");
}
}
/* ------------------------------------------------------------ */
@Override
public String getServletInfo()
{
return "Dump Servlet";
}
/* ------------------------------------------------------------ */
@Override
public synchronized void destroy()
{
}
/* ------------------------------------------------------------ */
private String getURI(HttpServletRequest request)
{
String uri= (String)request.getAttribute("javax.servlet.forward.request_uri");
if (uri == null)
uri= request.getRequestURI();
return uri;
}
/* ------------------------------------------------------------ */
private static String toString(Object o)
{
if (o == null)
return null;
try
{
if (o.getClass().isArray())
{
StringBuffer sb = new StringBuffer();
if (!o.getClass().getComponentType().isPrimitive())
{
Object[] array= (Object[])o;
for (int i= 0; i < array.length; i++)
{
if (i > 0)
sb.append("\n");
sb.append(array.getClass().getComponentType().getName());
sb.append("[");
sb.append(i);
sb.append("]=");
sb.append(toString(array[i]));
}
return sb.toString();
}
else
{
int length = Array.getLength(o);
for (int i=0;i<length;i++)
{
if (i > 0)
sb.append("\n");
sb.append(o.getClass().getComponentType().getName());
sb.append("[");
sb.append(i);
sb.append("]=");
sb.append(toString(Array.get(o, i)));
}
return sb.toString();
}
}
else
return o.toString();
}
catch (Exception e)
{
return e.toString();
}
}
private boolean dump(HttpServletResponse response, String data, String chars, String block, String dribble, boolean flush) throws IOException
{
if (data != null && data.length() > 0)
{
long d=Long.parseLong(data);
int b=(block!=null&&block.length()>0)?Integer.parseInt(block):50;
byte[] buf=new byte[b];
for (int i=0;i<b;i++)
{
buf[i]=(byte)('0'+(i%10));
if (i%10==9)
buf[i]=(byte)'\n';
}
buf[0]='o';
OutputStream out=response.getOutputStream();
response.setContentType("text/plain");
while (d > 0)
{
if (b==1)
{
out.write(d%80==0?'\n':'.');
d--;
}
else if (d>=b)
{
out.write(buf);
d=d-b;
}
else
{
out.write(buf,0,(int)d);
d=0;
}
if (dribble!=null)
{
out.flush();
try
{
Thread.sleep(Long.parseLong(dribble));
}
catch (Exception e)
{
e.printStackTrace();
break;
}
}
}
if (flush)
out.flush();
return true;
}
// Handle a dump of data
if (chars != null && chars.length() > 0)
{
long d=Long.parseLong(chars);
int b=(block!=null&&block.length()>0)?Integer.parseInt(block):50;
char[] buf=new char[b];
for (int i=0;i<b;i++)
{
buf[i]=(char)('0'+(i%10));
if (i%10==9)
buf[i]='\n';
}
buf[0]='o';
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
while (d > 0 && !out.checkError())
{
if (b==1)
{
out.write(d%80==0?'\n':'.');
d--;
}
else if (d>=b)
{
out.write(buf);
d=d-b;
}
else
{
out.write(buf,0,(int)d);
d=0;
}
}
return true;
}
return false;
}
private String notag(String s)
{
if (s==null)
return "null";
s=StringUtil.replace(s,"&","&amp;");
s=StringUtil.replace(s,"<","&lt;");
s=StringUtil.replace(s,">","&gt;");
return s;
}
}

View File

@ -0,0 +1,84 @@
package org.eclipse.jetty.nested;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConnection;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.log.Log;
public class NestedConnection extends HttpConnection
{
protected NestedConnection(final NestedConnector connector, final NestedEndPoint endp, final HttpServletRequest request, HttpServletResponse response,String nestedIn)
throws IOException
{
super(connector,
endp,
connector.getServer(),
new NestedParser(request),
new NestedGenerator(connector.getResponseBuffers(),endp,response,nestedIn),
new NestedRequest());
((NestedRequest)_request).setConnection(this);
// Set the request line
_request.setScheme(request.getScheme());
_request.setMethod(request.getMethod());
String uri=request.getQueryString()==null?request.getRequestURI():(request.getRequestURI()+"?"+request.getQueryString());
_request.setUri(new HttpURI(uri));
_request.setPathInfo(request.getRequestURI());
_request.setQueryString(request.getQueryString());
_request.setProtocol(request.getProtocol());
// Set the headers
HttpFields fields = getRequestFields();
for (Enumeration<String> e=request.getHeaderNames();e.hasMoreElements();)
{
String header=e.nextElement();
String value=request.getHeader(header);
fields.add(header,value);
}
_request.setCookies(request.getCookies());
// System.err.println(_request.getMethod()+" "+_request.getUri()+" "+_request.getProtocol());
// System.err.println(fields.toString());
}
public void handle2() throws IOException, ServletException
{
setCurrentConnection(this);
try
{
getServer().handle(this);
completeResponse();
_generator.flushBuffer();
_endp.flush();
}
finally
{
setCurrentConnection(null);
}
}
/* (non-Javadoc)
* @see org.eclipse.jetty.server.HttpConnection#getInputStream()
*/
@Override
public ServletInputStream getInputStream() throws IOException
{
return ((NestedEndPoint)_endp).getServletInputStream();
}
}

View File

@ -0,0 +1,37 @@
package org.eclipse.jetty.nested;
import java.io.IOException;
import org.eclipse.jetty.server.AbstractConnector;
public class NestedConnector extends AbstractConnector
{
public NestedConnector()
{
setAcceptors(0);
}
public void open() throws IOException
{
}
public void close() throws IOException
{
}
public int getLocalPort()
{
return -1;
}
public Object getConnection()
{
return null;
}
@Override
protected void accept(int acceptorID) throws IOException, InterruptedException
{
throw new IllegalStateException();
}
}

View File

@ -0,0 +1,27 @@
package org.eclipse.jetty.nested;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.bio.StreamEndPoint;
public class NestedEndPoint extends StreamEndPoint
{
public NestedEndPoint(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
super(request.getInputStream(),response.getOutputStream());
}
public ServletInputStream getServletInputStream()
{
return (ServletInputStream)getInputStream();
}
}

View File

@ -0,0 +1,244 @@
package org.eclipse.jetty.nested;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.AbstractGenerator;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.http.HttpVersions;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.Buffers;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.log.Log;
public class NestedGenerator extends AbstractGenerator
{
final HttpServletResponse _response;
final String _nestedIn;
public NestedGenerator(Buffers buffers, EndPoint io, HttpServletResponse response, String nestedIn)
{
super(buffers,io);
_response=response;
_nestedIn=nestedIn;
}
public void addContent(Buffer content, boolean last) throws IOException
{
Log.debug("addContent {} {}",content.length(),last);
if (_noContent)
{
content.clear();
return;
}
if (content.isImmutable())
throw new IllegalArgumentException("immutable");
if (_last || _state == STATE_END)
{
Log.debug("Ignoring extra content {}", content);
content.clear();
return;
}
_last = last;
if(!_endp.isOpen())
{
_state = STATE_END;
return;
}
// Handle any unfinished business?
if (_content != null && _content.length() > 0)
{
flushBuffer();
if (_content != null && _content.length() > 0)
throw new IllegalStateException("FULL");
}
_content = content;
_contentWritten += content.length();
// Handle the _content
if (_head)
{
content.clear();
_content = null;
}
else
{
// Yes - so we better check we have a buffer
initContent();
// Copy _content to buffer;
int len = 0;
len = _buffer.put(_content);
// make sure there is space for a trailing null
if (len > 0 && _buffer.space() == 0)
{
len--;
_buffer.setPutIndex(_buffer.putIndex() - 1);
}
_content.skip(len);
if (_content.length() == 0)
_content = null;
}
}
public boolean addContent(byte b) throws IOException
{
Log.debug("addContent 1");
if (_noContent)
return false;
if (_last || _state == STATE_END)
throw new IllegalStateException("Closed");
if(!_endp.isOpen())
{
_state = STATE_END;
return false;
}
// Handle any unfinished business?
if (_content != null && _content.length() > 0)
{
flushBuffer();
if (_content != null && _content.length() > 0)
throw new IllegalStateException("FULL");
}
_contentWritten++;
// Handle the _content
if (_head)
return false;
// we better check we have a buffer
initContent();
// Copy _content to buffer;
_buffer.put(b);
return _buffer.space() <= 1;
}
/* ------------------------------------------------------------ */
private void initContent() throws IOException
{
if (_buffer == null)
{
Log.debug("initContent");
_buffer = _buffers.getBuffer();
}
}
/* ------------------------------------------------------------ */
@Override
public boolean isRequest()
{
return false;
}
/* ------------------------------------------------------------ */
@Override
public boolean isResponse()
{
return true;
}
/* ------------------------------------------------------------ */
@Override
public int prepareUncheckedAddContent() throws IOException
{
initContent();
return _buffer.space();
}
/* ------------------------------------------------------------ */
@Override
public void completeHeader(HttpFields fields, boolean allContentAdded) throws IOException
{
Log.debug("completeHeader: {}",fields);
if (_state != STATE_HEADER)
return;
if (_last && !allContentAdded)
throw new IllegalStateException("last?");
_last = _last | allContentAdded;
if (_persistent==null)
_persistent=(_version > HttpVersions.HTTP_1_0_ORDINAL);
if (_reason == null)
_response.setStatus(_status);
else
_response.setStatus(_status,_reason.toString());
if (_status == 100 || _status == 204 || _status == 304)
{
_noContent = true;
_content = null;
}
boolean has_server = false;
if (fields != null)
{
// Add headers
int s=fields.size();
for (int f=0;f<s;f++)
{
HttpFields.Field field = fields.getField(f);
if (field==null)
continue;
_response.setHeader(field.getName(),field.getValue());
}
}
if (!has_server && _status > 100 && getSendServerVersion())
_response.setHeader(HttpHeaders.SERVER,"Jetty("+Server.getVersion()+",nested in "+_nestedIn+")");
_state = STATE_CONTENT;
}
/* ------------------------------------------------------------ */
@Override
public long flushBuffer() throws IOException
{
if (_state == STATE_HEADER)
throw new IllegalStateException("State==HEADER");
if (_content != null && _content.length() < _buffer.space() && _state != STATE_FLUSHING)
{
initContent();
_buffer.put(_content);
_content.clear();
_content = null;
}
if (_buffer==null)
return 0;
int size=_buffer.length();
int len = _buffer==null?0:_endp.flush(_buffer);
Log.debug("flushBuffer {} of {}",len,size);
if (len>0)
_buffer.skip(len);
return len;
}
}

View File

@ -0,0 +1,128 @@
package org.eclipse.jetty.nested;
import java.io.File;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.LocalConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.xml.XmlConfiguration;
/**
* Nested Jetty Servlet.
* <p>
* This servlet runs Jetty as a nested server inside another servlet container. The requests received by
* this servlet are routed via a {@link NestedConnector} to the nested jetty servlet and handled by jetty contexts,
* handlers, webapps and/or servlets.
* <p>
* The servlet can be configured with the following init parameters:<ul>
* <li>debug - if true then jetty debugging is turned on</li>
* <li>webapp - set to the resource path of the webapplication to deploy
* <li>jetty.xml - set the the resource path of a jetty xml file used to configure the server
* </ul>
*
*/
public class NestedJettyServlet implements Servlet
{
private Server _server;
private ServletConfig _config;
private ServletContext _context;
private NestedConnector _connector;
public void init(ServletConfig config) throws ServletException
{
ClassLoader orig = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader(NestedJettyServlet.class.getClassLoader());
_config=config;
_context=config.getServletContext();
Log.getLog().setDebugEnabled(Boolean.parseBoolean(_config.getInitParameter("debug")));
String jetty_xml=config.getInitParameter("jetty.xml");
if (jetty_xml!=null)
{
XmlConfiguration xml_config = new XmlConfiguration(_context.getResourceAsStream(jetty_xml));
_server=(Server)xml_config.configure();
}
if (_server==null)
_server=new Server();
if (_server.getConnectors().length==0)
{
_connector=new NestedConnector();
_server.addConnector(_connector);
}
else
_connector=(NestedConnector)_server.getConnectors()[0];
WebAppContext webapp = new WebAppContext();
webapp.setContextPath(_context.getContextPath());
webapp.setTempDirectory(new File((File)_context.getAttribute("javax.servlet.context.tempdir"),"jetty"));
String docroot=config.getInitParameter("webapp");
String realpath=_context.getRealPath(docroot);
if (realpath!=null)
webapp.setWar(realpath);
else
webapp.setWar(_context.getResource(docroot).toString());
_server.setHandler(webapp);
_server.start();
_context.log("Started Jetty/"+_server.getVersion()+" for "+webapp.getWar()+" nested in "+_context.getServerInfo());
}
catch(Exception e)
{
throw new ServletException(e);
}
finally
{
Thread.currentThread().setContextClassLoader(orig);
}
}
public ServletConfig getServletConfig()
{
return _config;
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
NestedConnection connection=new NestedConnection(_connector,new NestedEndPoint(request,response),request,response,_context.getServerInfo());
connection.handle2();
}
public String getServletInfo()
{
return this.toString();
}
public void destroy()
{
try
{
_server.stop();
}
catch(Exception e)
{
_context.log("stopping",e);
}
}
}

View File

@ -0,0 +1,47 @@
package org.eclipse.jetty.nested;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.http.Parser;
public class NestedParser implements Parser
{
public NestedParser(HttpServletRequest request)
{
// TODO Auto-generated constructor stub
}
public void reset(boolean returnBuffers)
{
// TODO Auto-generated method stub
}
public boolean isComplete()
{
// TODO Auto-generated method stub
return false;
}
public int parseAvailable() throws IOException
{
// TODO Auto-generated method stub
return 0;
}
public boolean isMoreInBuffer() throws IOException
{
// TODO Auto-generated method stub
return false;
}
public boolean isIdle()
{
// TODO Auto-generated method stub
return false;
}
}

View File

@ -0,0 +1,16 @@
package org.eclipse.jetty.nested;
import org.eclipse.jetty.server.Request;
public class NestedRequest extends Request
{
public NestedRequest()
{
}
void setConnection(NestedConnection connection)
{
super.setConnection(connection);
}
}

View File

@ -0,0 +1,31 @@
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<!-- =============================================================== -->
<!-- Configure the Nested Jetty Server -->
<!-- =============================================================== -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<!-- =========================================================== -->
<!-- Set connectors -->
<!-- =========================================================== -->
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.nested.NestedConnector">
<Set name="statsOn">false</Set>
<Set name="confidentialPort">8443</Set>
</New>
</Arg>
</Call>
<!-- =========================================================== -->
<!-- extra options -->
<!-- =========================================================== -->
<Set name="stopAtShutdown">true</Set>
<Set name="sendServerVersion">true</Set>
<Set name="sendDateHeader">true</Set>
<Set name="gracefulShutdown">1000</Set>
<Set name="dumpAfterStart">true</Set>
<Set name="dumpBeforeStop">false</Set>
</Configure>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Nested WebApp</display-name>
<servlet>
<servlet-name>jetty</servlet-name>
<servlet-class>org.eclipse.jetty.nested.NestedJettyServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>webapp</param-name>
<param-value>/nested</param-value>
</init-param>
<init-param>
<param-name>jetty.xml</param-name>
<param-value>/WEB-INF/jetty.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jetty</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -0,0 +1 @@
<h1>WRONG WEBAPP</h1>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Nested WebApp</display-name>
<servlet>
<servlet-name>dump</servlet-name>
<servlet-class>org.eclipse.jetty.nested.Dump</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dump</servlet-name>
<url-pattern>/dump/*</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -0,0 +1,23 @@
<html><head>
<%@ page import="java.util.Enumeration" %>
</head><body>
<h1>JSP Dump</h1>
<table border="1">
<tr><th>Request URI:</th><td><%= request.getRequestURI() %></td></tr>
<tr><th>ServletPath:</th><td><%= request.getServletPath() %></td></tr>
<tr><th>PathInfo:</th><td><%= request.getPathInfo() %></td></tr>
<%
Enumeration e =request.getParameterNames();
while(e.hasMoreElements())
{
String name = (String)e.nextElement();
%>
<tr>
<th>getParameter("<%= name %>")</th>
<td><%= request.getParameter(name) %></td></tr>
<% } %>
</table>
</body></html>

View File

@ -0,0 +1,7 @@
<h1>Nested Jetty</h1>
<ul>
<li><a href="dump/info">Servlet Dump</a></li>
<li><a href="dump.jsp">JSP Dump</a></li>
</ul>

View File

@ -307,17 +307,11 @@
<module>jetty-rewrite</module>
<module>jetty-policy</module>
<module>jetty-start</module>
<!-- Moved to profile 'osgi' below (default active)
<module>jetty-osgi</module>
-->
<module>jetty-nested</module>
<module>test-continuation</module>
<module>test-continuation-jetty6</module>
<module>test-jetty-servlet</module>
<module>test-jetty-webapp</module>
<!-- Moved to profile 'aggregates' below (default active)
<module>jetty-aggregate</module>
<module>jetty-distribution</module>
-->
<module>example-jetty-embedded</module>
<module>tests</module>
</modules>