Debian Codegraph @

jetty-ee9/jetty-ee9-demos/jetty-ee9-demo-jetty-webapp/src/main/java/org/example/Dump.java

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