Debian Codegraph @

jetty-ee10/jetty-ee10-demos/jetty-ee10-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 public class Dump extends HttpServlet
60 {
61 /**
62 * Zero Width Space, to allow text to be wrapped at designated spots
63 */
64 private static final String ZWSP = "​";
65
66 private final ScheduledExecutorService _scheduler = Executors.newSingleThreadScheduledExecutor();
67 private boolean fixed;
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 fixed = true;
77 throw new UnavailableException("Unavailable test", Integer.parseInt(config.getInitParameter("unavailable")));
78 }
79 }
80
81 @Override
82 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
83 {
84 doGet(request, response);
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 @Override
106 public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
107 {
108 if (request.getRemoteUser() == null)
109 {
110 try
111 {
112 request.login("user", "password");
113 }
114 catch (ServletException e)
115 {
116 getServletContext().log("Login fail", e);
117 }
118 }
119
120 // Handle a dump of data
121 final String data = request.getParameter("data");
122 final String chars = request.getParameter("chars");
123 final String block = request.getParameter("block");
124 final String dribble = request.getParameter("dribble");
125 final boolean flush = request.getParameter("flush") != null && Boolean.parseBoolean(request.getParameter("flush"));
126
127 if (request.getPathInfo() != null && request.getPathInfo().toLowerCase(Locale.ENGLISH).contains("script"))
128 {
129 response.sendRedirect(response.encodeRedirectURL(getServletContext().getContextPath() + "/dump/info"));
130 return;
131 }
132
133 request.setCharacterEncoding("UTF-8");
134
135 if (request.getParameter("busy") != null)
136 {
137 long end = System.currentTimeMillis() + Long.parseLong(request.getParameter("busy"));
138 while (System.currentTimeMillis() < end)
139 {
140 Thread.onSpinWait();
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").contains("102"))
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)
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)
206 {
207 response.addHeader("Dump", "onStartAsync");
208 }
209
210 @Override
211 public void onError(AsyncEvent event)
212 {
213 response.addHeader("Dump", "onError");
214 }
215
216 @Override
217 public void onComplete(AsyncEvent event)
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.isEmpty())
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.isEmpty())
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.isEmpty())
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.isEmpty() && 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.isEmpty())
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.isEmpty())
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.contains("Locale/"))
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;
410 try
411 {
412 pout = response.getWriter();
413 }
414 catch (IllegalStateException e)
415 {
416 pout = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), charset));
417 }
418 if (buffered != null)
419 pout = new PrintWriter(new BufferedWriter(pout, Integer.parseInt(buffered)));
420
421 try
422 {
423 pout.write("<html>\n<body>\n");
424 pout.write("<h1>Dump Servlet</h1>\n");
425 pout.write("<table width=\"95%\">");
426 pout.write("<tr>\n");
427 pout.write("<th align=\"right\">getContentLength:&nbsp;</th>");
428 pout.write("<td>" + 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\">getContextPath:&nbsp;</th>");
434 pout.write("<td>" + request.getContextPath() + "</td>");
435 pout.write("</tr><tr>\n");
436 pout.write("<th align=\"right\">getDispatcherType:&nbsp;</th>");
437 pout.write("<td>" + request.getDispatcherType() + "</td>");
438 pout.write("</tr><tr>\n");
439 pout.write("<th align=\"right\">getLocale:&nbsp;</th>");
440 pout.write("<td>" + request.getLocale() + "</td>");
441 pout.write("</tr><tr>\n");
442 pout.write("<th align=\"right\">getLocalName:&nbsp;</th>");
443 pout.write("<td>" + request.getLocalName() + "</td>");
444 pout.write("</tr><tr>\n");
445 pout.write("<th align=\"right\">getLocalAddr:&nbsp;</th>");
446 pout.write("<td>" + request.getLocalAddr() + "</td>");
447 pout.write("</tr><tr>\n");
448 pout.write("<th align=\"right\">getLocalPort:&nbsp;</th>");
449 pout.write("<td>" + request.getLocalPort() + "</td>");
450 pout.write("</tr><tr>\n");
451 pout.write("<th align=\"right\">getMethod:&nbsp;</th>");
452 pout.write("<td>" + notag(request.getMethod()) + "</td>");
453 pout.write("</tr><tr>\n");
454 pout.write("<th align=\"right\">getPathInfo:&nbsp;</th>");
455 pout.write("<td>" + notag(request.getPathInfo()) + "</td>");
456 pout.write("</tr><tr>\n");
457 pout.write("<th align=\"right\">getPathTranslated:&nbsp;</th>");
458 pout.write("<td>" + notag(request.getPathTranslated()) + "</td>");
459 pout.write("</tr><tr>\n");
460 pout.write("<th align=\"right\">getProtocol:&nbsp;</th>");
461 pout.write("<td>" + request.getProtocol() + "</td>");
462 pout.write("</tr><tr>\n");
463 pout.write("<th align=\"right\">getQueryString:&nbsp;</th>");
464 pout.write("<td>" + notag(request.getQueryString()) + "</td>");
465 pout.write("</tr><tr>\n");
466 pout.write("<th align=\"right\">getRemoteAddr:&nbsp;</th>");
467 pout.write("<td>" + request.getRemoteAddr() + "</td>");
468 pout.write("</tr><tr>\n");
469 pout.write("<th align=\"right\">getRemoteHost:&nbsp;</th>");
470 pout.write("<td>" + request.getRemoteHost() + "</td>");
471 pout.write("</tr><tr>\n");
472 pout.write("<th align=\"right\">getRemotePort:&nbsp;</th>");
473 pout.write("<td>" + request.getRemotePort() + "</td>");
474 pout.write("</tr><tr>\n");
475 pout.write("<th align=\"right\">getRemoteUser:&nbsp;</th>");
476 pout.write("<td>" + request.getRemoteUser() + "</td>");
477 pout.write("</tr><tr>\n");
478 pout.write("<th align=\"right\">getRequestedSessionId:&nbsp;</th>");
479 pout.write("<td>" + request.getRequestedSessionId() + "</td>");
480 pout.write("</tr><tr>\n");
481 pout.write("<th align=\"right\">getRequestURI:&nbsp;</th>");
482 pout.write("<td>" + notag(request.getRequestURI()) + "</td>");
483 pout.write("</tr><tr>\n");
484 pout.write("<th align=\"right\">getRequestURL:&nbsp;</th>");
485 pout.write("<td>" + notag(request.getRequestURL().toString()) + "</td>");
486 pout.write("</tr><tr>\n");
487 pout.write("<th align=\"right\">getScheme:&nbsp;</th>");
488 pout.write("<td>" + request.getScheme() + "</td>");
489 pout.write("</tr><tr>\n");
490 pout.write("<th align=\"right\">getServerName:&nbsp;</th>");
491 pout.write("<td>" + notag(request.getServerName()) + "</td>");
492 pout.write("</tr><tr>\n");
493 pout.write("<th align=\"right\">getServletPath:&nbsp;</th>");
494 pout.write("<td>" + notag(request.getServletPath()) + "</td>");
495 pout.write("</tr><tr>\n");
496 pout.write("<th align=\"right\">getServerPort:&nbsp;</th>");
497 pout.write("<td>" + request.getServerPort() + "</td>");
498 pout.write("</tr><tr>\n");
499 pout.write("<th align=\"right\">getUserPrincipal:&nbsp;</th>");
500 pout.write("<td>" + request.getUserPrincipal() + "</td>");
501 pout.write("</tr><tr>\n");
502 pout.write("<th align=\"right\">isAsyncStarted():&nbsp;</th>");
503 pout.write("<td>" + request.isAsyncStarted() + "</td>");
504 pout.write("</tr><tr>\n");
505 pout.write("<th align=\"right\">isAsyncSupported():&nbsp;</th>");
506 pout.write("<td>" + request.isAsyncSupported() + "</td>");
507 pout.write("</tr><tr>\n");
508 pout.write("<th align=\"right\">isSecure():&nbsp;</th>");
509 pout.write("<td>" + request.isSecure() + "</td>");
510 pout.write("</tr><tr>\n");
511 pout.write("<th align=\"right\">isUserInRole(admin):&nbsp;</th>");
512 pout.write("<td>" + request.isUserInRole("admin") + "</td>");
513 pout.write("</tr><tr>\n");
514 pout.write("<th align=\"right\">encodeRedirectURL(/foo?bar):&nbsp;</th>");
515 pout.write("<td>" + response.encodeRedirectURL("/foo?bar") + "</td>");
516
517 Enumeration<Locale> locales = request.getLocales();
518 while (locales.hasMoreElements())
519 {
520 pout.write("</tr><tr>\n");
521 pout.write("<th align=\"right\">getLocales:&nbsp;</th>");
522 pout.write("<td>" + locales.nextElement() + "</td>");
523 }
524 pout.write("</tr><tr>\n");
525
526 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Other HTTP Headers:</big></th>");
527 Enumeration<String> h = request.getHeaderNames();
528 String name;
529 while (h.hasMoreElements())
530 {
531 name = h.nextElement();
532
533 Enumeration<String> h2 = request.getHeaders(name);
534 while (h2.hasMoreElements())
535 {
536 String hv = h2.nextElement();
537 pout.write("</tr><tr>\n");
538 pout.write("<th align=\"right\">" + notag(name) + ":&nbsp;</th>");
539 pout.write("<td>" + notag(hv) + "</td>");
540 }
541 }
542
543 pout.write("</tr><tr>\n");
544 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Parameters:</big></th>");
545 h = request.getParameterNames();
546 while (h.hasMoreElements())
547 {
548 name = h.nextElement();
549 pout.write("</tr><tr>\n");
550 pout.write("<th align=\"right\">" + notag(name) + ":&nbsp;</th>");
551 pout.write("<td>" + notag(request.getParameter(name)) + "</td>");
552 String[] values = request.getParameterValues(name);
553 if (values == null)
554 {
555 pout.write("</tr><tr>\n");
556 pout.write("<th align=\"right\">" + notag(name) + " Values:&nbsp;</th>");
557 pout.write("<td>" + "NULL!" + "</td>");
558 }
559 else if (values.length > 1)
560 {
561 for (int i = 0; i < values.length; i++)
562 {
563 pout.write("</tr><tr>\n");
564 pout.write("<th align=\"right\">" + notag(name) + "[" + i + "]:&nbsp;</th>");
565 pout.write("<td>" + notag(values[i]) + "</td>");
566 }
567 }
568 }
569
570 try
571 {
572 Collection<Part> parts = request.getParts();
573 if (parts != null && !parts.isEmpty())
574 {
575 pout.write("</tr><tr>\n");
576 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Parts:</big></th>");
577 for (Part p : parts)
578 {
579 pout.write("</tr><tr>\n");
580 pout.write("<th align=\"right\">" + notag(p.getName()) + ":&nbsp;</th>");
581 pout.write("<td>" + p + "</td>");
582 }
583 }
584 }
585 catch (ServletException e)
586 {
587 pout.write("</tr><tr>\n");
588 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>No Parts!</big></th>");
589 }
590
591 pout.write("</tr><tr>\n");
592 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Cookies:</big></th>");
593 Cookie[] cookies = request.getCookies();
594 for (int i = 0; cookies != null && i < cookies.length; i++)
595 {
596 Cookie cookie = cookies[i];
597
598 pout.write("</tr><tr>\n");
599 pout.write("<th align=\"right\">" + notag(cookie.getName()) + ":&nbsp;</th>");
600 pout.write("<td>" + notag(cookie.getValue()) + "</td>");
601 }
602
603 String contentType = request.getContentType();
604 if (contentType != null &&
605 !contentType.startsWith("application/x-www-form-urlencoded") &&
606 !contentType.startsWith("multipart/form-data"))
607 {
608 pout.write("</tr><tr>\n");
609 pout.write("<th align=\"left\" valign=\"top\" colspan=\"2\"><big><br/>Content:</big></th>");
610 pout.write("</tr><tr>\n");
611 pout.write("<td><pre>");
612 char[] content = new char[4096];
613 int len;
614 try
615 {
616 Reader in = request.getReader();
617
618 while ((len = in.read(content)) >= 0)
619 {
620 pout.write(notag(new String(content, 0, len)));
621 }
622 }
623 catch (IOException e)
624 {
625 pout.write(e.toString());
626 }
627
628 pout.write("</pre></td>");
629 }
630
631 pout.write("</tr><tr>\n");
632 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Attributes:</big></th>");
633 Enumeration<String> a = request.getAttributeNames();
634 while (a.hasMoreElements())
635 {
636 name = a.nextElement();
637 pout.write("</tr><tr>\n");
638 pout.write("<th align=\"right\" valign=\"top\">" + name.replace(".", ZWSP + ".") + ":&nbsp;</th>");
639 Object value = request.getAttribute(name);
640 if (value instanceof File file)
641 {
642 pout.write("<td>" + "<pre>" + file.getName() + " (" + file.length() + " " + new Date(file.lastModified()) + ")</pre>" + "</td>");
643 }
644 else
645 pout.write("<td>" + "<pre>" + toString(request.getAttribute(name)) + "</pre>" + "</td>");
646 }
647 request.setAttribute("org.eclipse.jetty.ee10.servlet.MultiPartFilter.files", null);
648
649 pout.write("</tr><tr>\n");
650 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Servlet InitParameters:</big></th>");
651 a = getInitParameterNames();
652 while (a.hasMoreElements())
653 {
654 name = a.nextElement();
655 pout.write("</tr><tr>\n");
656 pout.write("<th align=\"right\">" + name + ":&nbsp;</th>");
657 pout.write("<td>" + toString(getInitParameter(name)) + "</td>");
658 }
659
660 pout.write("</tr><tr>\n");
661 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context InitParameters:</big></th>");
662 a = getServletContext().getInitParameterNames();
663 while (a.hasMoreElements())
664 {
665 name = a.nextElement();
666 pout.write("</tr><tr>\n");
667 pout.write("<th align=\"right\" valign=\"top\">" + name.replace(".", ZWSP + ".") + ":&nbsp;</th>");
668 pout.write("<td>" + toString(getServletContext().getInitParameter(name)) + "</td>");
669 }
670
671 pout.write("</tr><tr>\n");
672 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context Attributes:</big></th>");
673 a = getServletContext().getAttributeNames();
674 while (a.hasMoreElements())
675 {
676 name = a.nextElement();
677 pout.write("</tr><tr>\n");
678 pout.write("<th align=\"right\" valign=\"top\">" + name.replace(".", ZWSP + ".") + ":&nbsp;</th>");
679 pout.write("<td>" + "<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>" + "</td>");
680 }
681
682 String res = request.getParameter("resource");
683 if (res != null && !res.isEmpty())
684 {
685 pout.write("</tr><tr>\n");
686 pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Get Resource: \"" + res + "\"</big></th>");
687
688 pout.write("</tr><tr>\n");
689 pout.write("<th align=\"right\">getServletContext().getResource(...):&nbsp;</th>");
690 try
691 {
692 pout.write("<td>" + getServletContext().getResource(res) + "</td>");
693 }
694 catch (Exception e)
695 {
696 pout.write("<td>" + e + "</td>");
697 }
698
699 pout.write("</tr><tr>\n");
700 pout.write("<th align=\"right\">getServletContext().getResourcePaths(...):&nbsp;</th>");
701 try
702 {
703 pout.write("<td>" + getServletContext().getResourcePaths(res) + "</td>");
704 }
705 catch (Exception e)
706 {
707 pout.write("<td>" + e + "</td>");
708 }
709
710 pout.write("</tr><tr>\n");
711 pout.write("<th align=\"right\">getServletContext().getRealPath(...):&nbsp;</th>");
712 try
713 {
714 pout.write("<td>" + getServletContext().getRealPath(res) + "</td>");
715 }
716 catch (Exception e)
717 {
718 pout.write("<td>" + e + "</td>");
719 }
720
721 pout.write("</tr><tr>\n");
722 pout.write("<th align=\"right\">getServletContext().getContext(...):&nbsp;</th>");
723
724 ServletContext context = getServletContext().getContext(res);
725 pout.write("<td>" + context + "</td>");
726
727 if (context != null)
728 {
729 pout.write("</tr><tr>\n");
730 pout.write("<th align=\"right\">getServletContext().getContext(...).getResource(...):&nbsp;</th>");
731 try
732 {
733 pout.write("<td>" + context.getResource(res) + "</td>");
734 }
735 catch (Exception e)
736 {
737 pout.write("<td>" + e + "</td>");
738 }
739
740 pout.write("</tr><tr>\n");
741 pout.write("<th align=\"right\">getServletContext().getContext(...).getResourcePaths(...):&nbsp;</th>");
742 try
743 {
744 pout.write("<td>" + context.getResourcePaths(res) + "</td>");
745 }
746 catch (Exception e)
747 {
748 pout.write("<td>" + e + "</td>");
749 }
750
751 String cp = context.getContextPath();
752 if (cp == null || "/".equals(cp))
753 cp = "";
754 pout.write("</tr><tr>\n");
755 pout.write("<th align=\"right\">getServletContext().getContext(...).getRequestDispatcher(...):&nbsp;</th>");
756 pout.write("<td>" + context.getRequestDispatcher(res.substring(cp.length())) + "</td>");
757
758 pout.write("</tr><tr>\n");
759 pout.write("<th align=\"right\">getServletContext().getContext(...).getRealPath(...):&nbsp;</th>");
760 pout.write("<td>" + context.getRealPath(res.substring(cp.length())) + "</td>");
761 }
762
763 pout.write("</tr><tr>\n");
764 pout.write("<th align=\"right\">this.getClass().getResource(...):&nbsp;</th>");
765 pout.write("<td>" + this.getClass().getResource(res) + "</td>");
766
767 pout.write("</tr><tr>\n");
768 pout.write("<th align=\"right\">this.getClass().getClassLoader().getResource(...):&nbsp;</th>");
769 pout.write("<td>" + this.getClass().getClassLoader().getResource(res) + "</td>");
770
771 pout.write("</tr><tr>\n");
772 pout.write("<th align=\"right\">Thread.currentThread().getContextClassLoader().getResource(...):&nbsp;</th>");
773 pout.write("<td>" + Thread.currentThread().getContextClassLoader().getResource(res) + "</td>");
774 pout.write("</tr><tr>\n");
775 pout.write("<th align=\"right\">Thread.currentThread().getContextClassLoader().getResources(...):&nbsp;</th>");
776 Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(res);
777 if (urls == null)
778 pout.write("<td>null</td>");
779 else
780 pout.write("<td>" + Collections.list(urls) + "</td>");
781 }
782
783 pout.write("</tr></table>\n");
784
785 pout.write("<h2>Request Wrappers</h2>\n");
786 ServletRequest rw = request;
787 int w = 0;
788 while (rw != null)
789 {
790 pout.write((w++) + ": " + rw.getClass().getName() + "<br/>");
791 if (rw instanceof HttpServletRequestWrapper)
792 rw = ((HttpServletRequestWrapper)rw).getRequest();
793 else if (rw instanceof ServletRequestWrapper)
794 rw = ((ServletRequestWrapper)rw).getRequest();
795 else
796 rw = null;
797 }
798
799 pout.write("<h2>Response Wrappers</h2>\n");
800 ServletResponse rsw = response;
801 w = 0;
802 while (rsw != null)
803 {
804 pout.write((w++) + ": " + rsw.getClass().getName() + "<br/>");
805 if (rsw instanceof HttpServletResponseWrapper)
806 rsw = ((HttpServletResponseWrapper)rsw).getResponse();
807 else if (rsw instanceof ServletResponseWrapper)
808 rsw = ((ServletResponseWrapper)rsw).getResponse();
809 else
810 rsw = null;
811 }
812
813 pout.write("<br/>");
814 pout.write("<h2>International Characters (UTF-8)</h2>");
815 pout.write("LATIN LETTER SMALL CAPITAL AE<br/>\n");
816 pout.write("Directly uni encoded(\\u1d01): \u1d01<br/>"); // uni encoded
817 pout.write("HTML reference (&amp;AElig;): &AElig;<br/>");
818 pout.write("Decimal (&amp;#7425;): &#7425;<br/>");
819 pout.write("Javascript unicode (\\u1d01) : <script language='javascript'>document.write(\"\u1d01\");</script><br/>"); // uni encoded
820 pout.write("<br/>");
821 pout.write("<h2>Form to generate GET content</h2>");
822 pout.write("<form method=\"GET\" action=\"" + response.encodeURL(getURI(request)) + "\">");
823 pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n");
824 pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\">");
825 pout.write("</form>");
826
827 pout.write("<br/>");
828
829 pout.write("<h2>Form to generate POST content</h2>");
830 pout.write("<form method=\"POST\" accept-charset=\"utf-8\" action=\"" + response.encodeURL(getURI(request)) + "\">");
831 pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n");
832 pout.write("Select: <select multiple name=\"Select\">\n");
833 pout.write("<option>ValueA</option>");
834 pout.write("<option>ValueB1,ValueB2</option>");
835 pout.write("<option>ValueC</option>");
836 pout.write("</select><br/>");
837 pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>");
838 pout.write("</form>");
839 pout.write("<br/>");
840
841 pout.write("<h2>Form to generate UPLOAD content</h2>");
842 pout.write("<form method=\"POST\" enctype=\"multipart/form-data\" accept-charset=\"utf-8\" action=\"" +
843 response.encodeURL(getURI(request)) + (request.getQueryString() == null ? "" : ("?" + request.getQueryString())) +
844 "\">");
845 pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"comment\"/><br/>\n");
846 pout.write("File 1: <input type=\"file\" name=\"file1\" /><br/>\n");
847 pout.write("File 2: <input type=\"file\" name=\"file2\" /><br/>\n");
848 pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>");
849 pout.write("</form>");
850
851 pout.write("<h2>Form to set Cookie</h2>");
852 pout.write("<form method=\"POST\" action=\"" + response.encodeURL(getURI(request)) + "\">");
853 pout.write("cookie: <input type=\"text\" name=\"cookie\" /><br/>\n");
854 pout.write("value: <input type=\"text\" name=\"cookiev\" /><br/>\n");
855 pout.write("<input type=\"submit\" name=\"Action\" value=\"setCookie\">");
856 pout.write("</form>\n");
857
858 pout.write("<h2>Form to get Resource</h2>");
859 pout.write("<form method=\"POST\" action=\"" + response.encodeURL(getURI(request)) + "\">");
860 pout.write("resource: <input type=\"text\" name=\"resource\" /><br/>\n");
861 pout.write("<input type=\"submit\" name=\"Action\" value=\"getResource\">");
862 pout.write("</form>\n");
863 }
864 catch (Exception e)
865 {
866 getServletContext().log("dump " + e);
867 }
868
869 String lines = request.getParameter("lines");
870 if (lines != null)
871 {
872 char[] line = "<span>A line of characters. Blah blah blah blah. blooble blooble</span></br>\n".toCharArray();
873 for (int l = Integer.parseInt(lines); l-- > 0; )
874 {
875 pout.write("<span>" + l + " </span>");
876 pout.write(line);
877 }
878 }
879
880 pout.write("</body>\n</html>\n");
881
882 pout.close();
883
884 if (pi != null)
885 {
886 switch (pi)
887 {
888 case "/ex4" -> throw new ServletException("test ex4", new Throwable());
889 case "/ex5" -> throw new IOException("test ex5");
890 case "/ex6" -> throw new UnavailableException("test ex6");
891 }
892 }
893 }
894
895 @Override
896 public String getServletInfo()
897 {
898 return "Dump Servlet";
899 }
900
901 @Override
902 public void destroy()
903 {
904 _scheduler.shutdownNow();
905 }
906
907 private String getURI(HttpServletRequest request)
908 {
909 String uri = (String)request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
910 if (uri == null)
911 uri = request.getRequestURI();
912 return uri;
913 }
914
915 private static String toString(Object o)
916 {
917 if (o == null)
918 return null;
919
920 try
921 {
922 if (o.getClass().isArray())
923 {
924 StringBuilder sb = new StringBuilder();
925 if (!o.getClass().getComponentType().isPrimitive())
926 {
927 Object[] array = (Object[])o;
928 for (int i = 0; i < array.length; i++)
929 {
930 if (i > 0)
931 sb.append("\n");
932 sb.append(array.getClass().getComponentType().getName());
933 sb.append("[");
934 sb.append(i);
935 sb.append("]=");
936 sb.append(toString(array[i]));
937 }
938 return sb.toString();
939 }
940 else
941 {
942 int length = Array.getLength(o);
943 for (int i = 0; i < length; i++)
944 {
945 if (i > 0)
946 sb.append("\n");
947 sb.append(o.getClass().getComponentType().getName());
948 sb.append("[");
949 sb.append(i);
950 sb.append("]=");
951 sb.append(toString(Array.get(o, i)));
952 }
953 return sb.toString();
954 }
955 }
956 else
957 return o.toString();
958 }
959 catch (Exception e)
960 {
961 return e.toString();
962 }
963 }
964
965 private boolean dump(HttpServletResponse response, String data, String chars, String block, String dribble, boolean flush) throws IOException
966 {
967 int len = (block != null && !block.isEmpty()) ? Integer.parseInt(block) : 50;
968 if (data != null && !data.isEmpty())
969 {
970 byte[] buf = new byte[len];
971 for (int i = 0; i < len; i++)
972 {
973
974 buf[i] = (byte)('0' + (i % 10));
975 if (i % 10 == 9)
976 buf[i] = (byte)'\n';
977 }
978 buf[0] = 'o';
979 OutputStream out = response.getOutputStream();
980 response.setContentType("text/plain");
981 long d = Long.parseLong(data);
982 while (d > 0)
983 {
984 if (len == 1)
985 {
986 out.write(d % 80 == 0 ? '\n' : '.');
987 d--;
988 }
989 else if (d >= len)
990 {
991 out.write(buf);
992 d = d - len;
993 }
994 else
995 {
996 out.write(buf, 0, (int)d);
997 d = 0;
998 }
999
1000 if (dribble != null)
1001 {
1002 out.flush();
1003 try
1004 {
1005 Thread.sleep(Long.parseLong(dribble));
1006 }
1007 catch (Exception e)
1008 {
1009 e.printStackTrace();
1010 break;
1011 }
1012 }
1013 }
1014
1015 if (flush)
1016 out.flush();
1017
1018 return true;
1019 }
1020
1021 // Handle a dump of data
1022 if (chars != null && !chars.isEmpty())
1023 {
1024 char[] buf = new char[len];
1025 for (int i = 0; i < len; i++)
1026 {
1027 buf[i] = (char)('0' + (i % 10));
1028 if (i % 10 == 9)
1029 buf[i] = '\n';
1030 }
1031 buf[0] = 'o';
1032 response.setContentType("text/plain");
1033 PrintWriter out = response.getWriter();
1034 long d = Long.parseLong(chars);
1035 while (d > 0 && !out.checkError())
1036 {
1037 if (len == 1)
1038 {
1039 out.write(d % 80 == 0 ? '\n' : '.');
1040 d--;
1041 }
1042 else if (d >= len)
1043 {
1044 out.write(buf);
1045 d = d - len;
1046 }
1047 else
1048 {
1049 out.write(buf, 0, (int)d);
1050 d = 0;
1051 }
1052 }
1053 return true;
1054 }
1055 return false;
1056 }
1057
1058 private String notag(String s)
1059 {
1060 if (s == null)
1061 return "null";
1062 s = s.replace("&", "&amp;");
1063 s = s.replace("<", "&lt;");
1064 s = s.replace(">", "&gt;");
1065 return s;
1066 }
1067 }