View Javadoc

1   // ========================================================================
2   // Copyright (c) 1996-2009 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   // The Eclipse Public License is available at 
8   // http://www.eclipse.org/legal/epl-v10.html
9   // The Apache License v2.0 is available at
10  // http://www.opensource.org/licenses/apache2.0.php
11  // You may elect to redistribute this code under either of these licenses. 
12  // ========================================================================
13  
14  package com.acme;
15  import java.io.BufferedWriter;
16  import java.io.File;
17  import java.io.IOException;
18  import java.io.InputStream;
19  import java.io.OutputStream;
20  import java.io.OutputStreamWriter;
21  import java.io.PrintWriter;
22  import java.io.Reader;
23  import java.lang.reflect.Array;
24  import java.lang.reflect.Field;
25  import java.util.Date;
26  import java.util.Enumeration;
27  import java.util.Locale;
28  
29  import javax.servlet.ServletConfig;
30  import javax.servlet.ServletContext;
31  import javax.servlet.ServletException;
32  import javax.servlet.ServletRequest;
33  import javax.servlet.ServletRequestWrapper;
34  import javax.servlet.ServletResponse;
35  import javax.servlet.ServletResponseWrapper;
36  import javax.servlet.UnavailableException;
37  import javax.servlet.http.Cookie;
38  import javax.servlet.http.HttpServlet;
39  import javax.servlet.http.HttpServletRequest;
40  import javax.servlet.http.HttpServletRequestWrapper;
41  import javax.servlet.http.HttpServletResponse;
42  import javax.servlet.http.HttpServletResponseWrapper;
43  
44  import org.eclipse.jetty.continuation.Continuation;
45  import org.eclipse.jetty.continuation.ContinuationListener;
46  import org.eclipse.jetty.continuation.ContinuationSupport;
47  import org.eclipse.jetty.http.HttpHeaders;
48  import org.eclipse.jetty.util.IO;
49  import org.eclipse.jetty.util.StringUtil;
50  import org.eclipse.jetty.util.log.Log;
51  
52  
53  
54  /* ------------------------------------------------------------ */
55  /** Dump Servlet Request.
56   * 
57   */
58  public class Dump extends HttpServlet
59  {
60      boolean fixed;
61      
62      /* ------------------------------------------------------------ */
63      @Override
64      public void init(ServletConfig config) throws ServletException
65      {
66      	super.init(config);
67      	
68      	if (config.getInitParameter("unavailable")!=null && !fixed)
69      	{
70      	    
71      	    fixed=true;
72      	    throw new UnavailableException("Unavailable test",Integer.parseInt(config.getInitParameter("unavailable")));
73      	}
74      }
75  
76      /* ------------------------------------------------------------ */
77      @Override
78      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
79      {
80          doGet(request, response);
81      }
82  
83      /* ------------------------------------------------------------ */
84      @Override
85      public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
86      {
87          byte[] buffer = new byte[8192];
88          int len=request.getContentLength();
89          int c=0;
90          InputStream in=request.getInputStream();
91          while (c<len)
92          {
93              int l = in.read(buffer);
94              if (l<0)
95                  break;
96              c+=l;
97          }
98          request.setAttribute("PUT",c+"bytes");
99          doGet(request, response);
100     }
101 
102     /* ------------------------------------------------------------ */
103     @Override
104     public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
105     {
106         // Handle a dump of data
107         final String data= request.getParameter("data");
108         final String chars= request.getParameter("chars");
109         final String block= request.getParameter("block");
110         final String dribble= request.getParameter("dribble");
111         final boolean flush= request.getParameter("flush")!=null?Boolean.parseBoolean(request.getParameter("flush")):false;
112 
113         
114         if(request.getPathInfo()!=null && request.getPathInfo().toLowerCase().indexOf("script")!=-1)
115         {
116             response.sendRedirect(response.encodeRedirectURL(getServletContext().getContextPath() + "/dump/info"));
117             return;
118         }
119             
120         request.setCharacterEncoding("UTF-8");
121         
122         if (request.getParameter("empty")!=null)
123         {
124             response.setStatus(200);
125             response.flushBuffer();
126             return;
127         }
128         
129         if (request.getParameter("sleep")!=null)
130         {
131             try
132             {
133                 long s = Long.parseLong(request.getParameter("sleep"));
134                 if (request.getHeader(HttpHeaders.EXPECT)!=null &&request.getHeader(HttpHeaders.EXPECT).indexOf("102")>=0)
135                 {
136                     Thread.sleep(s/2);
137                     response.sendError(102);
138                     Thread.sleep(s/2);
139                 }
140                 else
141                     Thread.sleep(s);
142             }
143             catch (InterruptedException e)
144             {
145                 return;
146             }
147             catch (Exception e)
148             {
149                 throw new ServletException(e);
150             }
151         }
152 
153         if (request.getAttribute("RESUME")==null && request.getParameter("resume")!=null)
154         {
155             request.setAttribute("RESUME",Boolean.TRUE);
156 
157             final long resume=Long.parseLong(request.getParameter("resume"));
158             new Thread(new Runnable()
159             {
160                 public void run()
161                 {
162                     try
163                     {
164                         Thread.sleep(resume);
165                     }
166                     catch (InterruptedException e)
167                     {
168                         e.printStackTrace();
169                     }
170                     Continuation continuation = ContinuationSupport.getContinuation(request);
171                     continuation.resume();
172                 }
173                 
174             }).start();
175         }
176 
177         if (request.getParameter("complete")!=null)
178         {
179             final long complete=Long.parseLong(request.getParameter("complete"));
180             new Thread(new Runnable()
181             {
182                 public void run()
183                 {
184                     try
185                     {
186                         Thread.sleep(complete);
187                     }
188                     catch (InterruptedException e)
189                     {
190                         e.printStackTrace();
191                     }
192                     try
193                     {
194                         response.setContentType("text/html");
195                         response.getOutputStream().println("<h1>COMPLETED</h1>"); 
196                         Continuation continuation = ContinuationSupport.getContinuation(request);
197                         continuation.complete();
198                     }
199                     catch (IOException e)
200                     {
201                         e.printStackTrace();
202                     }
203                 }
204 
205             }).start();
206         }
207         
208         if (request.getParameter("suspend")!=null && request.getAttribute("SUSPEND")!=Boolean.TRUE)
209         {
210             request.setAttribute("SUSPEND",Boolean.TRUE);
211             try
212             {
213                 Continuation continuation = ContinuationSupport.getContinuation(request);
214                 continuation.setTimeout(Long.parseLong(request.getParameter("suspend")));
215                 continuation.suspend();
216                 
217                 continuation.addContinuationListener(new ContinuationListener()
218                 {   
219                     public void onTimeout(Continuation continuation)
220                     {
221                         response.addHeader("Dump","onTimeout");
222                         try
223                         {
224                             if (!dump(response,data,chars,block,dribble,flush))
225                             {
226                                 response.setContentType("text/plain");
227                                 response.getOutputStream().println("EXPIRED");
228                             }
229                             continuation.complete();
230                         }
231                         catch (IOException e)
232                         {
233                             Log.ignore(e);
234                         }
235                     }
236                     
237                     public void onComplete(Continuation continuation)
238                     {
239                         response.addHeader("Dump","onComplete");
240                     }
241                 });
242                 
243                 continuation.undispatch();
244             }
245             catch(Exception e)
246             {
247                 throw new ServletException(e);
248             }
249         }        
250             
251         request.setAttribute("Dump", this);
252         getServletContext().setAttribute("Dump",this);
253         // getServletContext().log("dump "+request.getRequestURI());
254 
255         // Force a content length response
256         String length= request.getParameter("length");
257         if (length != null && length.length() > 0)
258         {
259             response.setContentLength(Integer.parseInt(length));
260         }
261 
262         // Handle a dump of data
263         if (dump(response,data,chars,block,dribble,flush))
264             return;
265         
266         // handle an exception
267         String info= request.getPathInfo();
268         if (info != null && info.endsWith("Exception"))
269         {
270             try
271             {
272                 throw (Throwable) Thread.currentThread().getContextClassLoader().loadClass(info.substring(1)).newInstance();
273             }
274             catch (Throwable th)
275             {
276                 throw new ServletException(th);
277             }
278         }
279 
280         // test a reset
281         String reset= request.getParameter("reset");
282         if (reset != null && reset.length() > 0)
283         {
284             response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
285             response.setHeader("SHOULD_NOT","BE SEEN");
286             response.reset();
287         }
288         
289         
290         // handle an redirect
291         String redirect= request.getParameter("redirect");
292         if (redirect != null && redirect.length() > 0)
293         {
294             response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
295             response.sendRedirect(response.encodeRedirectURL(redirect));
296             try
297             {
298                 response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
299             }
300             catch(IOException e)
301             {
302                 // ignored as stream is closed.
303             }
304             return;
305         }
306 
307         // handle an error
308         String error= request.getParameter("error");
309         if (error != null && error.length() > 0 && request.getAttribute("javax.servlet.error.status_code")==null)
310         {
311             response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
312             response.sendError(Integer.parseInt(error));
313             try
314             {
315                 response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
316             }
317             catch(IllegalStateException e)
318             {
319                 try
320                 {
321                     response.getWriter().println("NOR THIS!!"); 
322                 }
323                 catch(IOException e2){}
324             }
325             catch(IOException e){}
326             return;
327         }
328 
329         // Handle a extra headers 
330         String headers= request.getParameter("headers");
331         if (headers != null && headers.length() > 0)
332         {
333             long h=Long.parseLong(headers);
334             for (int i=0;i<h;i++)
335                 response.addHeader("Header"+i,"Value"+i);
336         }
337 
338         String buffer= request.getParameter("buffer");
339         if (buffer != null && buffer.length() > 0)
340             response.setBufferSize(Integer.parseInt(buffer));
341 
342         String charset= request.getParameter("charset");
343         if (charset==null)
344             charset="UTF-8";
345         response.setCharacterEncoding(charset);
346         response.setContentType("text/html");
347 
348         if (info != null && info.indexOf("Locale/") >= 0)
349         {
350             try
351             {
352                 String locale_name= info.substring(info.indexOf("Locale/") + 7);
353                 Field f= java.util.Locale.class.getField(locale_name);
354                 response.setLocale((Locale)f.get(null));
355             }
356             catch (Exception e)
357             {
358                 e.printStackTrace();
359                 response.setLocale(Locale.getDefault());
360             }
361         }
362 
363         String cn= request.getParameter("cookie");
364         String cv=request.getParameter("cookiev");
365         if (cn!=null && cv!=null)
366         {
367             Cookie cookie= new Cookie(cn, cv);
368             if (request.getParameter("version")!=null)
369                 cookie.setVersion(Integer.parseInt(request.getParameter("version")));
370             cookie.setComment("Cookie from dump servlet");
371             response.addCookie(cookie);
372         }
373 
374         String pi= request.getPathInfo();
375         if (pi != null && pi.startsWith("/ex"))
376         {
377             OutputStream out= response.getOutputStream();
378             out.write("</H1>This text should be reset</H1>".getBytes());
379             if ("/ex0".equals(pi))
380                 throw new ServletException("test ex0", new Throwable());
381             else if ("/ex1".equals(pi))
382                 throw new IOException("test ex1");
383             else if ("/ex2".equals(pi))
384                 throw new UnavailableException("test ex2");
385             else if (pi.startsWith("/ex3/"))
386                 throw new UnavailableException("test ex3",Integer.parseInt(pi.substring(5)));
387             throw new RuntimeException("test");
388         }
389 
390         if ("true".equals(request.getParameter("close")))
391             response.setHeader("Connection","close");
392 
393         String buffered= request.getParameter("buffered");
394         
395         PrintWriter pout=null;
396         
397         try
398         {
399             pout =response.getWriter();
400         }
401         catch(IllegalStateException e)
402         {
403             pout=new PrintWriter(new OutputStreamWriter(response.getOutputStream(),charset));
404         }
405         if (buffered!=null)
406             pout = new PrintWriter(new BufferedWriter(pout,Integer.parseInt(buffered)));
407         
408         try
409         {
410             pout.write("<html>\n<body>\n");
411             pout.write("<h1>Dump Servlet</h1>\n");
412             pout.write("<table width=\"95%\">");
413             pout.write("<tr>\n");
414             pout.write("<th align=\"right\">getMethod:&nbsp;</th>");
415             pout.write("<td>" + notag(request.getMethod())+"</td>");
416             pout.write("</tr><tr>\n");
417             pout.write("<th align=\"right\">getContentLength:&nbsp;</th>");
418             pout.write("<td>"+Integer.toString(request.getContentLength())+"</td>");
419             pout.write("</tr><tr>\n");
420             pout.write("<th align=\"right\">getContentType:&nbsp;</th>");
421             pout.write("<td>"+notag(request.getContentType())+"</td>");
422             pout.write("</tr><tr>\n");
423             pout.write("<th align=\"right\">getRequestURI:&nbsp;</th>");
424             pout.write("<td>"+notag(request.getRequestURI())+"</td>");
425             pout.write("</tr><tr>\n");
426             pout.write("<th align=\"right\">getRequestURL:&nbsp;</th>");
427             pout.write("<td>"+notag(request.getRequestURL().toString())+"</td>");
428             pout.write("</tr><tr>\n");
429             pout.write("<th align=\"right\">getContextPath:&nbsp;</th>");
430             pout.write("<td>"+request.getContextPath()+"</td>");
431             pout.write("</tr><tr>\n");
432             pout.write("<th align=\"right\">getServletPath:&nbsp;</th>");
433             pout.write("<td>"+notag(request.getServletPath())+"</td>");
434             pout.write("</tr><tr>\n");
435             pout.write("<th align=\"right\">getPathInfo:&nbsp;</th>");
436             pout.write("<td>"+notag(request.getPathInfo())+"</td>");
437             pout.write("</tr><tr>\n");
438             pout.write("<th align=\"right\">getPathTranslated:&nbsp;</th>");
439             pout.write("<td>"+notag(request.getPathTranslated())+"</td>");
440             pout.write("</tr><tr>\n");
441             pout.write("<th align=\"right\">getQueryString:&nbsp;</th>");
442             pout.write("<td>"+notag(request.getQueryString())+"</td>");
443             pout.write("</tr><tr>\n");
444             
445             pout.write("<th align=\"right\">getProtocol:&nbsp;</th>");
446             pout.write("<td>"+request.getProtocol()+"</td>");
447             pout.write("</tr><tr>\n");
448             pout.write("<th align=\"right\">getScheme:&nbsp;</th>");
449             pout.write("<td>"+request.getScheme()+"</td>");
450             pout.write("</tr><tr>\n");
451             pout.write("<th align=\"right\">getServerName:&nbsp;</th>");
452             pout.write("<td>"+notag(request.getServerName())+"</td>");
453             pout.write("</tr><tr>\n");
454             pout.write("<th align=\"right\">getServerPort:&nbsp;</th>");
455             pout.write("<td>"+Integer.toString(request.getServerPort())+"</td>");
456             pout.write("</tr><tr>\n");
457             pout.write("<th align=\"right\">getLocalName:&nbsp;</th>");
458             pout.write("<td>"+request.getLocalName()+"</td>");
459             pout.write("</tr><tr>\n");
460             pout.write("<th align=\"right\">getLocalAddr:&nbsp;</th>");
461             pout.write("<td>"+request.getLocalAddr()+"</td>");
462             pout.write("</tr><tr>\n");
463             pout.write("<th align=\"right\">getLocalPort:&nbsp;</th>");
464             pout.write("<td>"+Integer.toString(request.getLocalPort())+"</td>");
465             pout.write("</tr><tr>\n");
466             pout.write("<th align=\"right\">getRemoteUser:&nbsp;</th>");
467             pout.write("<td>"+request.getRemoteUser()+"</td>");
468             pout.write("</tr><tr>\n");
469             pout.write("<th align=\"right\">getUserPrincipal:&nbsp;</th>");
470             pout.write("<td>"+request.getUserPrincipal()+"</td>");
471             pout.write("</tr><tr>\n");
472             pout.write("<th align=\"right\">getRemoteAddr:&nbsp;</th>");
473             pout.write("<td>"+request.getRemoteAddr()+"</td>");
474             pout.write("</tr><tr>\n");
475             pout.write("<th align=\"right\">getRemoteHost:&nbsp;</th>");
476             pout.write("<td>"+request.getRemoteHost()+"</td>");
477             pout.write("</tr><tr>\n");
478             pout.write("<th align=\"right\">getRemotePort:&nbsp;</th>");
479             pout.write("<td>"+request.getRemotePort()+"</td>");
480             pout.write("</tr><tr>\n");
481             pout.write("<th align=\"right\">getRequestedSessionId:&nbsp;</th>");
482             pout.write("<td>"+request.getRequestedSessionId()+"</td>");
483             pout.write("</tr><tr>\n");
484             pout.write("<th align=\"right\">isSecure():&nbsp;</th>");
485             pout.write("<td>"+request.isSecure()+"</td>");
486 
487             pout.write("</tr><tr>\n");
488             pout.write("<th align=\"right\">isUserInRole(admin):&nbsp;</th>");
489             pout.write("<td>"+request.isUserInRole("admin")+"</td>");
490 
491             pout.write("</tr><tr>\n");
492             pout.write("<th align=\"right\">getLocale:&nbsp;</th>");
493             pout.write("<td>"+request.getLocale()+"</td>");
494             
495             Enumeration locales= request.getLocales();
496             while (locales.hasMoreElements())
497             {
498                 pout.write("</tr><tr>\n");
499                 pout.write("<th align=\"right\">getLocales:&nbsp;</th>");
500                 pout.write("<td>"+locales.nextElement()+"</td>");
501             }
502             pout.write("</tr><tr>\n");
503             
504             pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Other HTTP Headers:</big></th>");
505             Enumeration h= request.getHeaderNames();
506             String name;
507             while (h.hasMoreElements())
508             {
509                 name= (String)h.nextElement();
510 
511                 Enumeration h2= request.getHeaders(name);
512                 while (h2.hasMoreElements())
513                 {
514                     String hv= (String)h2.nextElement();
515                     pout.write("</tr><tr>\n");
516                     pout.write("<th align=\"right\">"+notag(name)+":&nbsp;</th>");
517                     pout.write("<td>"+notag(hv)+"</td>");
518                 }
519             }
520 
521             pout.write("</tr><tr>\n");
522             pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Parameters:</big></th>");
523             h= request.getParameterNames();
524             while (h.hasMoreElements())
525             {
526                 name= (String)h.nextElement();
527                 pout.write("</tr><tr>\n");
528                 pout.write("<th align=\"right\">"+notag(name)+":&nbsp;</th>");
529                 pout.write("<td>"+notag(request.getParameter(name))+"</td>");
530                 String[] values= request.getParameterValues(name);
531                 if (values == null)
532                 {
533                     pout.write("</tr><tr>\n");
534                     pout.write("<th align=\"right\">"+notag(name)+" Values:&nbsp;</th>");
535                     pout.write("<td>"+"NULL!"+"</td>");
536                 }
537                 else if (values.length > 1)
538                 {
539                     for (int i= 0; i < values.length; i++)
540                     {
541                         pout.write("</tr><tr>\n");
542                         pout.write("<th align=\"right\">"+notag(name)+"["+i+"]:&nbsp;</th>");
543                         pout.write("<td>"+notag(values[i])+"</td>");
544                     }
545                 }
546             }
547 
548             pout.write("</tr><tr>\n");
549             pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Cookies:</big></th>");
550             Cookie[] cookies = request.getCookies();
551             for (int i=0; cookies!=null && i<cookies.length;i++)
552             {
553                 Cookie cookie = cookies[i];
554 
555                 pout.write("</tr><tr>\n");
556                 pout.write("<th align=\"right\">"+notag(cookie.getName())+":&nbsp;</th>");
557                 pout.write("<td>"+notag(cookie.getValue())+"</td>");
558             }
559             
560             String content_type=request.getContentType();
561             if (content_type!=null &&
562                 !content_type.startsWith("application/x-www-form-urlencoded") &&
563                 !content_type.startsWith("multipart/form-data"))
564             {
565                 pout.write("</tr><tr>\n");
566                 pout.write("<th align=\"left\" valign=\"top\" colspan=\"2\"><big><br/>Content:</big></th>");
567                 pout.write("</tr><tr>\n");
568                 pout.write("<td><pre>");
569                 char[] content= new char[4096];
570                 int len;
571                 try{
572                     Reader in=request.getReader();
573                     
574                     while((len=in.read(content))>=0)
575                         pout.write(notag(new String(content,0,len)));
576                 }
577                 catch(IOException e)
578                 {
579                     pout.write(e.toString());
580                 }
581                 
582                 pout.write("</pre></td>");
583             }
584             
585             pout.write("</tr><tr>\n");
586             pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Attributes:</big></th>");
587             Enumeration a= request.getAttributeNames();
588             while (a.hasMoreElements())
589             {
590                 name= (String)a.nextElement();
591                 pout.write("</tr><tr>\n");
592                 pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>");
593                 Object value=request.getAttribute(name);
594                 if (value instanceof File)
595                 {
596                     File file = (File)value;
597                     pout.write("<td>"+"<pre>" + file.getName()+" ("+file.length()+" "+new Date(file.lastModified())+ ")</pre>"+"</td>");
598                 }
599                 else
600                     pout.write("<td>"+"<pre>" + toString(request.getAttribute(name)) + "</pre>"+"</td>");
601             }
602             request.setAttribute("org.eclipse.jetty.servlet.MultiPartFilter.files",null);
603 
604             
605             pout.write("</tr><tr>\n");
606             pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Servlet InitParameters:</big></th>");
607             a= getInitParameterNames();
608             while (a.hasMoreElements())
609             {
610                 name= (String)a.nextElement();
611                 pout.write("</tr><tr>\n");
612                 pout.write("<th align=\"right\">"+name+":&nbsp;</th>");
613                 pout.write("<td>"+ toString(getInitParameter(name)) +"</td>");
614             }
615 
616             pout.write("</tr><tr>\n");
617             pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context InitParameters:</big></th>");
618             a= getServletContext().getInitParameterNames();
619             while (a.hasMoreElements())
620             {
621                 name= (String)a.nextElement();
622                 pout.write("</tr><tr>\n");
623                 pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>");
624                 pout.write("<td>"+ toString(getServletContext().getInitParameter(name)) + "</td>");
625             }
626 
627             pout.write("</tr><tr>\n");
628             pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context Attributes:</big></th>");
629             a= getServletContext().getAttributeNames();
630             while (a.hasMoreElements())
631             {
632                 name= (String)a.nextElement();
633                 pout.write("</tr><tr>\n");
634                 pout.write("<th align=\"right\" valign=\"top\">"+name.replace("."," .")+":&nbsp;</th>");
635                 pout.write("<td>"+"<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"+"</td>");
636             }
637 
638             String res= request.getParameter("resource");
639             if (res != null && res.length() > 0)
640             {
641                 pout.write("</tr><tr>\n");
642                 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Get Resource: \""+res+"\"</big></th>");
643 
644                 pout.write("</tr><tr>\n");
645                 pout.write("<th align=\"right\">getServletContext().getResource(...):&nbsp;</th>");
646                 try{pout.write("<td>"+getServletContext().getResource(res)+"</td>");}
647                 catch(Exception e) {pout.write("<td>"+"" +e+"</td>");}
648                 
649                 pout.write("</tr><tr>\n");
650                 pout.write("<th align=\"right\">getServletContext().getResourcePaths(...):&nbsp;</th>");
651                 try{pout.write("<td>"+getServletContext().getResourcePaths(res)+"</td>");}
652                 catch(Exception e) {pout.write("<td>"+"" +e+"</td>");}
653                 
654                 pout.write("</tr><tr>\n");
655                 pout.write("<th align=\"right\">getServletContext().getContext(...):&nbsp;</th>");
656                 
657                 ServletContext context = getServletContext().getContext(res);
658                 pout.write("<td>"+context+"</td>");
659                 
660                 if (context!=null)
661                 {
662                     pout.write("</tr><tr>\n");
663                     pout.write("<th align=\"right\">getServletContext().getContext(...).getResource(...):&nbsp;</th>");
664                     try{pout.write("<td>"+context.getResource(res)+"</td>");}
665                     catch(Exception e) {pout.write("<td>"+"" +e+"</td>");}
666                     
667                     pout.write("</tr><tr>\n");
668                     pout.write("<th align=\"right\">getServletContext().getContext(...).getResourcePaths(...):&nbsp;</th>");
669                     try{pout.write("<td>"+context.getResourcePaths(res)+"</td>");}
670                     catch(Exception e) {pout.write("<td>"+"" +e+"</td>");}
671                     
672                     String cp=context.getContextPath();
673                     if (cp==null || "/".equals(cp))
674                         cp="";
675                     pout.write("</tr><tr>\n");
676                     pout.write("<th align=\"right\">getServletContext().getContext(...),getRequestDispatcher(...):&nbsp;</th>");
677                     pout.write("<td>"+getServletContext().getContext(res).getRequestDispatcher(res.substring(cp.length()))+"</td>");
678                 }
679 
680                 pout.write("</tr><tr>\n");
681                 pout.write("<th align=\"right\">this.getClass().getResource(...):&nbsp;</th>");
682                 pout.write("<td>"+this.getClass().getResource(res)+"</td>");
683 
684                 pout.write("</tr><tr>\n");
685                 pout.write("<th align=\"right\">this.getClass().getClassLoader().getResource(...):&nbsp;</th>");
686                 pout.write("<td>"+this.getClass().getClassLoader().getResource(res)+"</td>");
687 
688                 pout.write("</tr><tr>\n");
689                 pout.write("<th align=\"right\">Thread.currentThread().getContextClassLoader().getResource(...):&nbsp;</th>");
690                 pout.write("<td>"+Thread.currentThread().getContextClassLoader().getResource(res)+"</td>");
691 
692             }
693             
694             pout.write("</tr></table>\n");
695 
696             /* ------------------------------------------------------------ */
697             pout.write("<h2>Request Wrappers</h2>\n");
698             ServletRequest rw=request;
699             int w=0;
700             while (rw !=null)
701             {
702                 pout.write((w++)+": "+rw.getClass().getName()+"<br/>");
703                 if (rw instanceof HttpServletRequestWrapper)
704                     rw=((HttpServletRequestWrapper)rw).getRequest();
705                 else if (rw instanceof ServletRequestWrapper)
706                     rw=((ServletRequestWrapper)rw).getRequest();
707                 else
708                     rw=null;
709             }
710 
711             /* ------------------------------------------------------------ */
712             pout.write("<h2>Response Wrappers</h2>\n");
713             ServletResponse rsw=response;
714             w=0;
715             while (rsw !=null)
716             {
717                 pout.write((w++)+": "+rsw.getClass().getName()+"<br/>");
718                 if (rsw instanceof HttpServletResponseWrapper)
719                     rsw=((HttpServletResponseWrapper)rsw).getResponse();
720                 else if (rsw instanceof ServletResponseWrapper)
721                     rsw=((ServletResponseWrapper)rsw).getResponse();
722                 else
723                     rsw=null;
724             }
725             
726             pout.write("<br/>");
727             pout.write("<h2>International Characters (UTF-8)</h2>");
728             pout.write("LATIN LETTER SMALL CAPITAL AE<br/>\n");
729             pout.write("Directly uni encoded(\\u1d01): \u1d01<br/>");
730             pout.write("HTML reference (&amp;AElig;): &AElig;<br/>");
731             pout.write("Decimal (&amp;#7425;): &#7425;<br/>");
732             pout.write("Javascript unicode (\\u1d01) : <script language='javascript'>document.write(\"\u1d01\");</script><br/>");
733             pout.write("<br/>");
734             pout.write("<h2>Form to generate GET content</h2>");
735             pout.write("<form method=\"GET\" action=\""+response.encodeURL(getURI(request))+"\">");
736             pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n");
737             pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\">");
738             pout.write("</form>");
739 
740             pout.write("<br/>");
741             
742             pout.write("<h2>Form to generate POST content</h2>");
743             pout.write("<form method=\"POST\" accept-charset=\"utf-8\" action=\""+response.encodeURL(getURI(request))+"\">");
744             pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n");
745             pout.write("Select: <select multiple name=\"Select\">\n");
746             pout.write("<option>ValueA</option>");
747             pout.write("<option>ValueB1,ValueB2</option>");
748             pout.write("<option>ValueC</option>");
749             pout.write("</select><br/>");
750             pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>");
751             pout.write("</form>");
752             pout.write("<br/>");
753             
754             pout.write("<h2>Form to generate UPLOAD content</h2>");
755             pout.write("<form method=\"POST\" enctype=\"multipart/form-data\" accept-charset=\"utf-8\" action=\""+
756                     response.encodeURL(getURI(request))+(request.getQueryString()==null?"":("?"+request.getQueryString()))+
757                     "\">");
758             pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"comment\"/><br/>\n");
759             pout.write("File 1: <input type=\"file\" name=\"file1\" /><br/>\n");
760             pout.write("File 2: <input type=\"file\" name=\"file2\" /><br/>\n");
761             pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>");
762             pout.write("</form>");
763 
764             pout.write("<h2>Form to set Cookie</h2>");
765             pout.write("<form method=\"POST\" action=\""+response.encodeURL(getURI(request))+"\">");
766             pout.write("cookie: <input type=\"text\" name=\"cookie\" /><br/>\n");
767             pout.write("value: <input type=\"text\" name=\"cookiev\" /><br/>\n");
768             pout.write("<input type=\"submit\" name=\"Action\" value=\"setCookie\">");
769             pout.write("</form>\n");
770             
771             pout.write("<h2>Form to get Resource</h2>");
772             pout.write("<form method=\"POST\" action=\""+response.encodeURL(getURI(request))+"\">");
773             pout.write("resource: <input type=\"text\" name=\"resource\" /><br/>\n");
774             pout.write("<input type=\"submit\" name=\"Action\" value=\"getResource\">");
775             pout.write("</form>\n");
776         }
777         catch (Exception e)
778         {
779             getServletContext().log("dump", e);
780         }
781         
782         String lines= request.getParameter("lines");
783         if (lines!=null)
784         {
785             char[] line = "<span>A line of characters. Blah blah blah blah.  blooble blooble</span></br>\n".toCharArray();
786             for (int l=Integer.parseInt(lines);l-->0;)
787             {
788                 pout.write("<span>"+l+" </span>");
789                 pout.write(line);
790             }
791         }
792         
793         pout.write("</body>\n</html>\n");
794         
795         pout.close();
796 
797         if (pi != null)
798         {
799             if ("/ex4".equals(pi))
800                 throw new ServletException("test ex4", new Throwable());
801             if ("/ex5".equals(pi))
802                 throw new IOException("test ex5");
803             if ("/ex6".equals(pi))
804                 throw new UnavailableException("test ex6");
805         }
806 
807 
808     }
809 
810 
811     /* ------------------------------------------------------------ */
812     @Override
813     public String getServletInfo()
814     {
815         return "Dump Servlet";
816     }
817 
818     /* ------------------------------------------------------------ */
819     @Override
820     public synchronized void destroy()
821     {
822     }
823 
824     /* ------------------------------------------------------------ */
825     private String getURI(HttpServletRequest request)
826     {
827         String uri= (String)request.getAttribute("javax.servlet.forward.request_uri");
828         if (uri == null)
829             uri= request.getRequestURI();
830         return uri;
831     }
832 
833     /* ------------------------------------------------------------ */
834     private static String toString(Object o)
835     {
836         if (o == null)
837             return null;
838 
839         try
840         {
841             if (o.getClass().isArray())
842             {
843                 StringBuffer sb = new StringBuffer();
844                 if (!o.getClass().getComponentType().isPrimitive())
845                 {
846                     Object[] array= (Object[])o;
847                     for (int i= 0; i < array.length; i++)
848                     {
849                         if (i > 0)
850                             sb.append("\n");
851                         sb.append(array.getClass().getComponentType().getName());
852                         sb.append("[");
853                         sb.append(i);
854                         sb.append("]=");
855                         sb.append(toString(array[i]));
856                     }
857                     return sb.toString();
858                 }
859                 else
860                 { 
861                     int length = Array.getLength(o);
862                     for (int i=0;i<length;i++)
863                     {
864                         if (i > 0)
865                             sb.append("\n");
866                         sb.append(o.getClass().getComponentType().getName()); 
867                         sb.append("[");
868                         sb.append(i);
869                         sb.append("]=");
870                         sb.append(toString(Array.get(o, i)));
871                     }
872                     return sb.toString();
873                 }
874             }
875             else
876                 return o.toString();
877         }
878         catch (Exception e)
879         {
880             return e.toString();
881         }
882     }
883 
884     private boolean dump(HttpServletResponse response, String data, String chars, String block, String dribble, boolean flush) throws IOException
885     {
886         if (data != null && data.length() > 0)
887         {
888             long d=Long.parseLong(data);
889             int b=(block!=null&&block.length()>0)?Integer.parseInt(block):50;
890             byte[] buf=new byte[b];
891             for (int i=0;i<b;i++)
892             {
893                 
894                 buf[i]=(byte)('0'+(i%10));
895                 if (i%10==9)
896                     buf[i]=(byte)'\n';
897             }
898             buf[0]='o';
899             OutputStream out=response.getOutputStream();
900             response.setContentType("text/plain");
901             while (d > 0)
902             {
903                 if (b==1)
904                 {
905                     out.write(d%80==0?'\n':'.');
906                     d--;
907                 }
908                 else if (d>=b)
909                 {
910                     out.write(buf);
911                     d=d-b;
912                 }
913                 else
914                 {
915                     out.write(buf,0,(int)d);
916                     d=0;
917                 }
918                 
919                 if (dribble!=null)
920                 {
921                     out.flush();
922                     try
923                     {
924                         Thread.sleep(Long.parseLong(dribble));
925                     }
926                     catch (Exception e)
927                     {
928                         e.printStackTrace();
929                         break;
930                     }
931                 }
932                 
933             }
934             
935             if (flush)
936                 out.flush();
937             
938             return true;
939         }
940 
941         // Handle a dump of data
942         if (chars != null && chars.length() > 0)
943         {
944             long d=Long.parseLong(chars);
945             int b=(block!=null&&block.length()>0)?Integer.parseInt(block):50;
946             char[] buf=new char[b];
947             for (int i=0;i<b;i++)
948             {
949                 buf[i]=(char)('0'+(i%10));
950                 if (i%10==9)
951                     buf[i]='\n';
952             }
953             buf[0]='o';
954             response.setContentType("text/plain");
955             PrintWriter out=response.getWriter();
956             while (d > 0 && !out.checkError())
957             {
958                 if (b==1)
959                 {
960                     out.write(d%80==0?'\n':'.');
961                     d--;
962                 }
963                 else if (d>=b)
964                 {
965                     out.write(buf);
966                     d=d-b;
967                 }
968                 else
969                 {
970                     out.write(buf,0,(int)d);
971                     d=0;
972                 }
973             }
974             return true;
975         }    
976         return false;
977     }
978     
979     private String notag(String s)
980     {
981         if (s==null)
982             return "null";
983         s=StringUtil.replace(s,"&","&amp;");
984         s=StringUtil.replace(s,"<","&lt;");
985         s=StringUtil.replace(s,">","&gt;");
986         return s;
987     }
988 }