List of usage examples for javax.servlet.http HttpServletResponse setBufferSize
public void setBufferSize(int size);
From source file:org.melati.admin.Admin.java
private String proxy(Melati melati, ServletTemplateContext context) { if (melati.getSession().getAttribute("generatedByMelatiClass") == null) throw new AnticipatedException("Only available from within an Admin generated page"); String method = melati.getRequest().getMethod(); String url = melati.getRequest().getQueryString(); HttpServletResponse response = melati.getResponse(); HttpMethod httpMethod = null;/*from w w w. j a v a 2 s.c o m*/ try { HttpClient client = new HttpClient(); if (method.equals("GET")) httpMethod = new GetMethod(url); else if (method.equals("POST")) httpMethod = new PostMethod(url); else if (method.equals("PUT")) httpMethod = new PutMethod(url); else if (method.equals("HEAD")) httpMethod = new HeadMethod(url); else throw new RuntimeException("Unexpected method '" + method + "'"); try { httpMethod.setFollowRedirects(true); client.executeMethod(httpMethod); for (Header h : httpMethod.getResponseHeaders()) { response.setHeader(h.getName(), h.getValue()); } response.setStatus(httpMethod.getStatusCode()); response.setHeader("Cache-Control", "no-cache"); byte[] outputBytes = httpMethod.getResponseBody(); if (outputBytes != null) { response.setBufferSize(outputBytes.length); response.getWriter().write(new String(outputBytes)); response.getWriter().flush(); } } catch (Exception e) { throw new MelatiIOException(e); } } finally { if (httpMethod != null) httpMethod.releaseConnection(); } return null; }
From source file:com.geminimobile.web.SearchController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException arg3) throws Exception { SearchCommand cmd = (SearchCommand) command; ModelAndView mav = new ModelAndView(getSuccessView()); CDRDataAccess cdrAccess = new CDRDataAccess(); Date toDate = SearchCommand.m_sdf.parse(cmd.getToDate()); long maxTimestamp = toDate.getTime(); Date fromDate = SearchCommand.m_sdf.parse(cmd.getFromDate()); long minTimestamp = fromDate.getTime(); String msisdn = cmd.getMsisdn(); String action = cmd.getAction(); Vector<CDREntry> cdrs;//from w ww . j av a2 s . c o m if (action.compareToIgnoreCase("downloadcsv") == 0) { if (msisdn != null && msisdn.length() > 0) { cdrs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(), 100000); // 100,000 entries max } else { cdrs = cdrAccess.getCDRsByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(), MAX_ENTRIES_PER_PAGE); } StringBuffer sb = new StringBuffer(); // Write column headers sb.append("Date/Time,Market,Type,MSISDN,MO IP address,MT IP Address,Sender Domain,Recipient Domain\n"); for (CDREntry entry : cdrs) { sb.append(entry.getDisplayTimestamp() + "," + entry.getMarket() + "," + entry.getType() + "," + entry.getMsisdn() + "," + entry.getMoIPAddress() + "," + entry.getMtIPAddress() + "," + entry.getSenderDomain() + "," + entry.getRecipientDomain() + "\n"); } String csvString = sb.toString(); response.setBufferSize(sb.length()); response.setContentLength(sb.length()); response.setContentType("text/plain; charset=UTF-8"); //response.setContentType( "text/csv" ); //response.setContentType("application/ms-excel"); //response.setHeader("Content-disposition", "attachment;filename=cdrResults.csv"); response.setHeader("Content-Disposition", "attachment; filename=" + "cdrResults.csv" + ";"); ServletOutputStream os = response.getOutputStream(); os.write(csvString.getBytes()); os.flush(); os.close(); return null; } else if (action.compareToIgnoreCase("graph") == 0) { cmd.setGraph(true); List<ChartSeries> chartData; if (msisdn != null && msisdn.length() > 0) { chartData = cdrAccess.getChartDataByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(), 100000); } else { chartData = cdrAccess.getChartDataByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(), 100000); } request.getSession().setAttribute("chartData", chartData); } else if (action.compareToIgnoreCase("getmore") == 0) { cdrs = (Vector<CDREntry>) request.getSession().getAttribute("currentcdrs"); int numCDRs = cdrs.size(); CDREntry lastCDR = cdrs.get(numCDRs - 1); long lastCDRTime = Long.parseLong(lastCDR.getTimestamp()); if (msisdn != null && msisdn.length() > 0) { Vector<CDREntry> moreCDRs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), lastCDRTime, maxTimestamp, cmd.getMarket(), cmd.getMessageType(), MAX_ENTRIES_PER_PAGE); cdrs.addAll(moreCDRs); } else { Vector<CDREntry> moreCDRs = cdrAccess.getCDRsByHour(lastCDRTime, maxTimestamp, cmd.getMarket(), cmd.getMessageType(), MAX_ENTRIES_PER_PAGE); cdrs.addAll(moreCDRs); } request.getSession().setAttribute("currentcdrs", cdrs); mav.addObject("cdrs", cdrs); } else { // Normal search if (msisdn != null && msisdn.length() > 0) { cdrs = cdrAccess.getCDRsByMSISDN(cmd.getMsisdn(), minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(), MAX_ENTRIES_PER_PAGE); } else { cdrs = cdrAccess.getCDRsByHour(minTimestamp, maxTimestamp, cmd.getMarket(), cmd.getMessageType(), MAX_ENTRIES_PER_PAGE); } request.getSession().setAttribute("currentcdrs", cdrs); mav.addObject("cdrs", cdrs); } mav.addObject("searchCmd", cmd); List<Option> msgOptions = getMessageOptions(); mav.addObject("msgTypes", msgOptions); List<Option> marketOptions = getMarketOptions(); mav.addObject("marketTypes", marketOptions); return mav; }
From source file:org.archive.wayback.resourcestore.locationdb.FileProxyServlet.java
public boolean handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { ResourceLocation location = parseRequest(httpRequest); if (location == null) { httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "no/invalid name"); } else {/*from w w w . ja va2s .com*/ String urls[] = locationDB.nameToUrls(location.getName()); if (urls == null || urls.length == 0) { LOGGER.warning("No locations for " + location.getName()); httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Unable to locate(" + location.getName() + ")"); } else { DataSource ds = null; for (String urlString : urls) { try { ds = locationToDataSource(urlString, location.getOffset()); if (ds != null) { break; } } catch (IOException e) { LOGGER.warning("failed proxy of " + urlString + " " + e.getLocalizedMessage()); } } if (ds == null) { LOGGER.warning("No successful locations for " + location.getName()); httpResponse.sendError(HttpServletResponse.SC_BAD_GATEWAY, "failed proxy of (" + location.getName() + ")"); } else { httpResponse.setStatus(HttpServletResponse.SC_OK); // BUGBUG: this will be broken for non compressed data... httpResponse.setContentType(ds.getContentType()); httpResponse.setBufferSize(BUF_SIZE); ds.copyTo(httpResponse.getOutputStream()); } } } return true; }
From source file:org.apache.axis.transport.http.AxisServlet.java
/** * Process a POST to the servlet by handing it off to the Axis Engine. * Here is where SOAP messages are received * @param req posted request//from w w w . ja va2 s. co m * @param res respose * @throws ServletException trouble * @throws IOException different trouble */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0; String soapAction = null; MessageContext msgContext = null; if (isDebug) { log.debug("Enter: doPost()"); } if (tlog.isDebugEnabled()) { t0 = System.currentTimeMillis(); } Message responseMsg = null; String contentType = null; try { AxisEngine engine = getEngine(); if (engine == null) { // !!! should return a SOAP fault... ServletException se = new ServletException(Messages.getMessage("noEngine00")); log.debug("No Engine!", se); throw se; } res.setBufferSize(1024 * 8); // provide performance boost. /** get message context w/ various properties set */ msgContext = createMessageContext(engine, req, res); // ? OK to move this to 'getMessageContext', // ? where it would also be picked up for 'doGet()' ? if (securityProvider != null) { if (isDebug) { log.debug("securityProvider:" + securityProvider); } msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider); } /* Get request message */ Message requestMsg = new Message(req.getInputStream(), false, req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE), req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION)); // Transfer HTTP headers to MIME headers for request message. MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders(); for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) { String headerName = (String) e.nextElement(); for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements();) { String headerValue = (String) f.nextElement(); requestMimeHeaders.addHeader(headerName, headerValue); } } if (isDebug) { log.debug("Request Message:" + requestMsg); /* Set the request(incoming) message field in the context */ /**********************************************************/ } msgContext.setRequestMessage(requestMsg); String url = HttpUtils.getRequestURL(req).toString(); msgContext.setProperty(MessageContext.TRANS_URL, url); // put character encoding of request to message context // in order to reuse it during the whole process. String requestEncoding; try { requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); if (requestEncoding != null) { msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding); } } catch (SOAPException e1) { } try { /** * Save the SOAPAction header in the MessageContext bag. * This will be used to tell the Axis Engine which service * is being invoked. This will save us the trouble of * having to parse the Request message - although we will * need to double-check later on that the SOAPAction header * does in fact match the URI in the body. */ // (is this last stmt true??? (I don't think so - Glen)) /********************************************************/ soapAction = getSoapAction(req); if (soapAction != null) { msgContext.setUseSOAPAction(true); msgContext.setSOAPActionURI(soapAction); } // Create a Session wrapper for the HTTP session. // These can/should be pooled at some point. // (Sam is Watching! :-) msgContext.setSession(new AxisHttpSession(req)); if (tlog.isDebugEnabled()) { t1 = System.currentTimeMillis(); } /* Invoke the Axis engine... */ /*****************************/ if (isDebug) { log.debug("Invoking Axis Engine."); //here we run the message by the engine } engine.invoke(msgContext); if (isDebug) { log.debug("Return from Axis Engine."); } if (tlog.isDebugEnabled()) { t2 = System.currentTimeMillis(); } responseMsg = msgContext.getResponseMessage(); // We used to throw exceptions on null response messages. // They are actually OK in certain situations (asynchronous // services), so fall through here and return an ACCEPTED // status code below. Might want to install a configurable // error check for this later. } catch (AxisFault fault) { //log and sanitize processAxisFault(fault); configureResponseFromAxisFault(res, fault); responseMsg = msgContext.getResponseMessage(); if (responseMsg == null) { responseMsg = new Message(fault); ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage() .setMessageContext(msgContext); } } catch (Exception e) { //other exceptions are internal trouble responseMsg = msgContext.getResponseMessage(); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); responseMsg = convertExceptionToAxisFault(e, responseMsg); ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext); } catch (Throwable t) { logException(t); //other exceptions are internal trouble responseMsg = msgContext.getResponseMessage(); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); responseMsg = new Message(new AxisFault(t.toString(), t)); ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext); } } catch (AxisFault fault) { processAxisFault(fault); configureResponseFromAxisFault(res, fault); responseMsg = msgContext.getResponseMessage(); if (responseMsg == null) { responseMsg = new Message(fault); ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext); } } if (tlog.isDebugEnabled()) { t3 = System.currentTimeMillis(); } /* Send response back along the wire... */ /***********************************/ if (responseMsg != null) { // Transfer MIME headers to HTTP headers for response message. MimeHeaders responseMimeHeaders = responseMsg.getMimeHeaders(); for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader responseMimeHeader = (MimeHeader) i.next(); res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue()); } // synchronize the character encoding of request and response String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); if (responseEncoding != null) { try { responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding); } catch (SOAPException e) { } } //determine content type from message response contentType = responseMsg.getContentType(msgContext.getSOAPConstants()); sendResponse(contentType, res, responseMsg); } else { // No content, so just indicate accepted res.setStatus(202); } if (isDebug) { log.debug("Response sent."); log.debug("Exit: doPost()"); } if (tlog.isDebugEnabled()) { t4 = System.currentTimeMillis(); tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post=" + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "." + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName())); } }
From source file:edu.harvard.i2b2.fhirserver.ws.FileServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get requested file by path info. String requestedFile = request.getPathInfo(); if (requestedFile.equals("/")) requestedFile = "/index.html"; logger.trace("Got request:" + requestedFile); logger.trace("basePath:" + this.basePath); logger.trace("ffp:" + basePath + requestedFile); // Check if file is actually supplied to the request URI. //if (requestedFile == null) { // Do your thing if the file is not supplied to the request URI. // Throw an exception, or send 404, or show default/warning page, or just ignore it. // response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. //return;/* w w w . j ava 2s .co m*/ //} // Decode the file name (might contain spaces and on) and prepare file object. URL url = new URL(basePath + requestedFile); logger.trace("url:" + url); File file = FileUtils.toFile(url); logger.trace("searching for file:" + file.getAbsolutePath()); // Check if file actually exists in filesystem. if (!file.exists()) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. return; } // Get content type by filename. String contentType = getServletContext().getMimeType(file.getName()); // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/text"; } // Init servlet response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setContentType(contentType); response.setHeader("Content-Length", String.valueOf(file.length())); // response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); // Prepare streams. BufferedInputStream input = null; BufferedOutputStream output = null; try { // Open streams. input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE); output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE); // Write file contents to response. byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } finally { // Gently close streams. close(output); close(input); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.student.onlineTests.StudentTestsAction.java
public ActionForward showImage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws FenixActionException { final String testCode = request.getParameter("testCode"); final String exerciseId = request.getParameter("exerciseCode"); final Integer imgCode = getRequestParameterAsInteger(request, "imgCode"); final String imgTypeString = request.getParameter("imgType"); final Integer feedbackId = getRequestParameterAsInteger(request, "feedbackCode"); final Integer itemIndex = getRequestParameterAsInteger(request, "item"); final DistributedTest distributedTest = FenixFramework.getDomainObject(testCode); if (distributedTest == null) { request.setAttribute("invalidTest", new Boolean(true)); return mapping.findForward("testError"); }//from w w w . j a v a 2s .c o m final Registration registration = getRegistration(request); if (registration == null) { request.setAttribute("invalidTest", new Boolean(true)); return mapping.findForward("testError"); } String img = null; try { img = ReadStudentTestQuestionImage.run(registration.getExternalId(), distributedTest.getExternalId(), exerciseId, imgCode, feedbackId, itemIndex); } catch (FenixServiceException e) { throw new FenixActionException(e); } byte[] imageData = BaseEncoding.base64().decode(img); try { response.reset(); response.setContentType(imgTypeString); response.setContentLength(imageData.length); response.setBufferSize(imageData.length); StringBuilder imageName = new StringBuilder(); imageName.append("image").append(exerciseId).append(imgCode); if (feedbackId != null) { imageName.append("_").append(feedbackId); } imageName.append(".") .append(imgTypeString.substring(imgTypeString.lastIndexOf("/") + 1, imgTypeString.length())); response.setHeader("Content-disposition", "attachment; filename=" + imageName.toString()); OutputStream os = response.getOutputStream(); os.write(imageData, 0, imageData.length); response.flushBuffer(); } catch (java.io.IOException e) { throw new FenixActionException(e); } return null; }
From source file:org.nema.medical.mint.server.controller.ChangeLogController.java
@RequestMapping("/changelog") public void changelogXML(@RequestParam(value = "since", required = false) final String since, @RequestParam(value = "limit", required = false) Integer limit, @RequestParam(value = "offset", required = false) Integer offset, @RequestParam(value = "consolidate", required = false, defaultValue = "true") boolean consolidate, final HttpServletResponse res) throws IOException, JiBXException { final List<org.nema.medical.mint.changelog.Change> changes = new ArrayList<org.nema.medical.mint.changelog.Change>(); // TODO read limit from a config file if (limit == null) { limit = 50;//from w ww. j a v a2 s . c o m } if (offset == null) { offset = 0; } final int firstIndex = offset * limit; final List<Change> changesFound; if (consolidate) { //only get a list of most recent changes for each study changesFound = changeDAO.findLastChanges(); } else { if (since != null) { final Date date; try { final ISO8601DateUtils dateUtil = new org.nema.medical.mint.utils.JodaDateUtils(); date = dateUtil.parseISO8601Basic(since); } catch (final DateTimeParseException e) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid date: " + since); return; } if (date.getTime() > System.currentTimeMillis()) { LOG.warn(String.format("Changelog requested with invalid future start date %s", DateFormat.getDateTimeInstance().format(date))); res.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } changesFound = changeDAO.findChanges(date, firstIndex, limit); } else { changesFound = changeDAO.findChanges(firstIndex, limit); } } if (changesFound != null) { for (final Change change : changesFound) { changes.add(new org.nema.medical.mint.changelog.Change(change.getStudyUUID(), change.getIndex(), change.getType(), change.getDateTime(), change.getRemoteHost(), change.getRemoteUser(), change.getOperation())); } } res.setBufferSize(fileResponseBufferSize); final ChangeSet changeSet = new ChangeSet(changes); final IBindingFactory bfact = BindingDirectory.getFactory("serverChangelog", ChangeSet.class); final IMarshallingContext mctx = bfact.createMarshallingContext(); mctx.setIndent(2); mctx.startDocument("UTF-8", null, res.getOutputStream()); mctx.getXmlWriter().writePI("xml-stylesheet", xmlStylesheet); mctx.marshalDocument(changeSet); mctx.endDocument(); }
From source file:org.nema.medical.mint.server.controller.ChangeLogController.java
@RequestMapping("/studies/{uuid}/changelog/{seq}") public void studiesChangeLog(@PathVariable("uuid") final String uuid, @PathVariable("seq") final String seq, final HttpServletRequest req, final HttpServletResponse res) throws IOException { final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO); if (studyStatus != Utils.StudyStatus.OK) { return;//from w w w . j a v a 2 s . c om } /* * The path variable 'seq' when '0.gpb' is on the end of the URL seems * to be only '0' for some reason. I'm not sure what the weirdness is * with '.' in the URL. The following call should return the expected * sequence (i.e., '0.gpb'). */ String tmp = req.getAttribute("org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping") .toString(); if (StringUtils.isBlank(tmp)) { tmp = seq; } if (StringUtils.isBlank(tmp)) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: Empty"); return; } final Long sequence; String ext = null; final int extPoint = tmp.indexOf('.'); if (extPoint > -1) { try { sequence = Long.valueOf(tmp.substring(0, extPoint)); ext = tmp.substring(extPoint + 1); } catch (final NumberFormatException e) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: NaN"); return; } } else { try { sequence = Long.valueOf(tmp); } catch (final NumberFormatException e) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: NaN"); return; } } if (StringUtils.isBlank(ext)) { ext = "xml"; } if (sequence < 0) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: Negative"); return; } if (sequence >= Integer.MAX_VALUE) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: Too large"); return; } res.setBufferSize(fileResponseBufferSize); try { final File file = new File(studiesRoot, uuid + "/changelog/" + sequence + "/metadata." + ext); if (file.exists() && file.canRead()) { final OutputStream out = res.getOutputStream(); res.setContentLength((int) file.length()); res.setContentType("text/xml"); Utils.streamFile(file, out, fileStreamBufferSize); } else { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid study requested: Not found"); } } catch (final IOException e) { if (!res.isCommitted()) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot provide study change log: File Read Failure"); } } }
From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {//from w ww.jav a 2 s. c om throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:org.openqa.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {//from w w w .java 2 s .c om throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }