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