List of usage examples for javax.servlet.http HttpServletResponse reset
public void reset();
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;//from w ww .ja va2 s.c o 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 . ja v a2 s . 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.sakaiproject.sdata.tool.JCRHandler.java
@Override public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w. ja v a 2s . c o m snoopRequest(request); ResourceDefinition rp = resourceDefinitionFactory.getSpec(request); String mimeType = ContentTypes.getContentType(rp.getRepositoryPath(), request.getContentType()); String charEncoding = null; if (mimeType.startsWith("text")) { charEncoding = request.getCharacterEncoding(); } Node n = jcrNodeFactory.getNode(rp.getRepositoryPath()); boolean created = false; if (n == null) { n = jcrNodeFactory.createFile(rp.getRepositoryPath(), mimeType); created = true; if (n == null) { throw new RuntimeException( "Failed to create node at " + rp.getRepositoryPath() + " type " + JCRConstants.NT_FILE); } } else { NodeType nt = n.getPrimaryNodeType(); if (!JCRConstants.NT_FILE.equals(nt.getName())) { response.reset(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content Can only be put to a file, resource type is " + nt.getName()); return; } } GregorianCalendar gc = new GregorianCalendar(); long lastMod = request.getDateHeader(LAST_MODIFIED); if (lastMod > 0) { gc.setTimeInMillis(lastMod); } else { gc.setTime(new Date()); } InputStream in = request.getInputStream(); saveStream(n, in, mimeType, charEncoding, gc); in.close(); if (created) { response.setStatus(HttpServletResponse.SC_CREATED); } else { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } } catch (UnauthorizedException ape) { // catch any Unauthorized exceptions and send a 401 response.reset(); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage()); } catch (PermissionDeniedException pde) { // catch any permission denied exceptions, and send a 403 response.reset(); response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage()); } catch (SDataException e) { sendError(request, response, e); LOG.error("Failed To service Request " + e.getMessage()); } catch (Exception e) { sendError(request, response, e); snoopRequest(request); LOG.error("Failed TO service Request ", e); } }
From source file:com.highcharts.export.controller.ExportController.java
@RequestMapping(method = RequestMethod.POST) public void exporter(@RequestParam(value = "svg", required = false) String svg, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "filename", required = false) String filename, @RequestParam(value = "width", required = false) String width, @RequestParam(value = "scale", required = false) String scale, @RequestParam(value = "options", required = false) String options, @RequestParam(value = "constr", required = false) String constructor, @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException, InterruptedException, SVGConverterException, NoSuchElementException, PoolException, TimeoutException { long start1 = System.currentTimeMillis(); MimeType mime = getMime(type); filename = getFilename(filename);//from ww w .j a va 2s .c om Float parsedWidth = widthToFloat(width); Float parsedScale = scaleToFloat(scale); options = sanitize(options); String input; boolean convertSvg = false; if (options != null) { // create a svg file out of the options input = options; callback = sanitize(callback); } else { // assume SVG conversion if (svg == null) { throw new ServletException("The manadatory svg POST parameter is undefined."); } else { svg = sanitize(svg); if (svg == null) { throw new ServletException("The manadatory svg POST parameter is undefined."); } convertSvg = true; input = svg; } } ByteArrayOutputStream stream = null; if (convertSvg && mime.equals(MimeType.SVG)) { // send this to the client, without converting. stream = new ByteArrayOutputStream(); stream.write(input.getBytes()); } else { //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale); stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale); } if (stream == null) { throw new ServletException("Error while converting"); } logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1)); response.reset(); response.setCharacterEncoding("utf-8"); response.setContentLength(stream.size()); response.setStatus(HttpStatus.OK.value()); response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "." + mime.name().toLowerCase() + "\""); IOUtils.write(stream.toByteArray(), response.getOutputStream()); response.flushBuffer(); }
From source file:org.apache.openmeetings.servlet.outputhandler.BackupExport.java
public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, ServletContext servletCtx) throws ServletException, IOException { String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; }/*from w ww . j av a2 s. co m*/ log.debug("sid: " + sid); Long users_id = sessiondataDao.checkSession(sid); Long user_level = userManager.getUserLevelByID(users_id); log.debug("users_id: " + users_id); log.debug("user_level: " + user_level); if (authLevelUtil.checkAdminLevel(user_level)) { // if (true) { String includeFileOption = httpServletRequest.getParameter("includeFileOption"); boolean includeFiles = includeFileOption == null || "yes".equals(includeFileOption); String moduleName = httpServletRequest.getParameter("moduleName"); if (moduleName == null) { moduleName = "moduleName"; } log.debug("moduleName: " + moduleName); if (moduleName.equals("backup")) { /* * ##################### Create Base Folder structure */ File working_dir = OmFileHelper.getUploadBackupDir(); String dateString = "backup_" + CalendarPatterns.getTimeForStreamId(new Date()); File backup_dir = new File(working_dir, dateString); String requestedFile = dateString + ".zip"; File backupFile = new File(backup_dir, requestedFile); try { performExport(backupFile, backup_dir, includeFiles); httpServletResponse.reset(); httpServletResponse.resetBuffer(); httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + requestedFile + "\""); httpServletResponse.setHeader("Content-Length", "" + backupFile.length()); OutputStream out = httpServletResponse.getOutputStream(); OmFileHelper.copyFile(backupFile, out); out.flush(); out.close(); } catch (Exception er) { log.error("Error exporting: ", er); } if (backupFile.exists()) { // log.debug("DELETE :1: "+backupFile.getCanonicalPath()); backupFile.delete(); } FileHelper.removeRec(backup_dir); } } else { log.debug("ERROR LangExport: not authorized FileDownload " + (new Date())); } }
From source file:org.kitodo.services.ProcessService.java
/** * Download docket.//from ww w. ja v a 2 s .co m * * @param process object * @return empty string? */ public String downloadDocket(Process process) { if (myLogger.isDebugEnabled()) { myLogger.debug("generate docket for process " + process.getId()); } String rootPath = ConfigMain.getParameter("xsltFolder"); SafeFile xsltFile = new SafeFile(rootPath, "docket.xsl"); if (process.getDocket() != null) { xsltFile = new SafeFile(rootPath, process.getDocket().getFile()); if (!xsltFile.exists()) { Helper.setFehlerMeldung("docketMissing"); return ""; } } FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); String fileName = process.getTitle() + ".pdf"; ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType(fileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); // write run note to servlet output stream try { ServletOutputStream out = response.getOutputStream(); ExportDocket ern = new ExportDocket(); ern.startExport(process, out, xsltFile.getAbsolutePath()); out.flush(); facesContext.responseComplete(); } catch (Exception e) { Helper.setFehlerMeldung("Exception while exporting run note.", e.getMessage()); response.reset(); } } return ""; }
From source file:org.apache.roller.weblogger.ui.rendering.servlets.RSDServlet.java
/** * Handle GET requests for weblog pages. */// ww w. j a v a2 s . c o m public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); Weblog weblog = null; WeblogRequest weblogRequest = null; try { weblogRequest = new WeblogRequest(request); // now make sure the specified weblog really exists weblog = weblogRequest.getWeblog(); if (weblog == null) { throw new WebloggerException("Unable to lookup weblog: " + weblogRequest.getWeblogHandle()); } } catch (Exception e) { // invalid rsd request format or weblog doesn't exist log.debug("error creating weblog request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Respond with 304 Not Modified if it is not modified. long lastModified = System.currentTimeMillis(); if (weblog.getLastModified() != null) { lastModified = weblog.getLastModified().getTime(); } if (ModDateHeaderUtil.respondIfNotModified(request, response, lastModified)) { return; } // set last-modified date ModDateHeaderUtil.setLastModifiedHeader(response, lastModified); // set the content type response.setContentType("application/rsd+xml; charset=utf-8"); // populate the model HashMap model = new HashMap(); model.put("website", weblog); model.put("absBaseURL", WebloggerRuntimeConfig.getAbsoluteContextURL()); // lookup Renderer we are going to use Renderer renderer = null; try { log.debug("Looking up renderer"); Template template = new StaticTemplate("rsd.vm", "velocity"); renderer = RendererManager.getRenderer(template, DeviceType.standard); } catch (Exception e) { // nobody wants to render my content :( log.error("Couldn't find renderer for rsd template", e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // render content CachedContent rendererOutput = new CachedContent(4096); try { log.debug("Doing rendering"); renderer.render(model, rendererOutput.getCachedWriter()); // flush rendered output and close rendererOutput.flush(); rendererOutput.close(); } catch (Exception e) { // bummer, error during rendering log.error("Error during rendering for rsd template", e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // post rendering process // flush rendered content to response log.debug("Flushing response output"); response.setContentLength(rendererOutput.getContent().length); response.getOutputStream().write(rendererOutput.getContent()); log.debug("Exiting"); }
From source file:org.sakaiproject.sdata.tool.JCRHandler.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getRemoteUser() == null) { LOG.info("No User, denied "); response.sendError(401);/*w ww .j av a 2s. c o m*/ } else { snoopRequest(request); try { ResourceDefinition rp = resourceDefinitionFactory.getSpec(request); boolean isMultipart = ServletFileUpload.isMultipartContent(request); // multiparts are always streamed uploads if (isMultipart) { doMumtipartUpload(request, response, rp); } else { Node n = jcrNodeFactory.getNode(rp.getRepositoryPath()); SDataFunction m = resourceFunctionFactory.get(rp.getFunctionDefinition()); if (m != null) { m.call(this, request, response, n, rp); } else { LOG.info("NOP Post performed"); throw new SDataException(HttpServletResponse.SC_NOT_FOUND, "Method not found "); } } } catch (UnauthorizedException ape) { // catch any Unauthorized exceptions and send a 401 LOG.info(ape); response.reset(); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage()); } catch (PermissionDeniedException pde) { // catch any permission denied exceptions, and send a 403 LOG.info(pde); response.reset(); response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage()); } catch (SDataException sde) { LOG.info(sde); sendError(request, response, sde); } catch (RepositoryException rex) { LOG.info(rex); sendError(request, response, rex); } catch (JCRNodeFactoryServiceException jfe) { LOG.info(jfe); sendError(request, response, jfe); } } }
From source file:Highcharts.ExportController.java
@RequestMapping(method = RequestMethod.POST) public void exporter(@RequestParam(value = "svg", required = false) String svg, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "filename", required = false) String filename, @RequestParam(value = "width", required = false) String width, @RequestParam(value = "scale", required = false) String scale, @RequestParam(value = "options", required = false) String options, @RequestParam(value = "constr", required = false) String constructor, @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException, InterruptedException, SVGConverterException, NoSuchElementException, PoolException, TimeoutException { long start1 = System.currentTimeMillis(); MimeType mime = getMime(type); filename = getFilename(filename); Float parsedWidth = widthToFloat(width); Float parsedScale = scaleToFloat(scale); options = sanitize(options);//w w w .j av a2s .c o m String input; boolean convertSvg = false; if (options != null) { // create a svg file out of the options input = options; callback = sanitize(callback); } else { // assume SVG conversion if (svg == null) { throw new ServletException("The manadatory svg POST parameter is undefined."); } else { svg = sanitize(svg); if (svg == null) { throw new ServletException("The manadatory svg POST parameter is undefined."); } convertSvg = true; input = svg; } } ByteArrayOutputStream stream = null; if (convertSvg && mime.equals(MimeType.SVG)) { // send this to the client, without converting. stream = new ByteArrayOutputStream(); stream.write(input.getBytes()); } else { //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale); stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale); } if (stream == null) { throw new ServletException("Error while converting"); } logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1)); response.reset(); response.setCharacterEncoding("utf-8"); response.setContentLength(stream.size()); response.setStatus(HttpStatus.OK.value()); response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "." + mime.name().toLowerCase() + "\""); IOUtils.write(stream.toByteArray(), response.getOutputStream()); response.flushBuffer(); }
From source file:com.hihsoft.baseclass.web.controller.javahihBaseController.java
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws ControllerException { String fileId = getParam(request, "fileId"); if (StringHelpers.isNull(fileId)) return;//from ww w . j a va2s . c o m try { TsysUpload upload = baseService.getBean(TsysUpload.class, fileId); String failPage = "<html><font size='3'>?.<a href='#' onclick='javascript:window.close()'></a></font></html>"; if (upload == null) { renderHtml(response, failPage); return; } String path = upload.getFileUrl(); // path File file = new File(path); if (!file.exists()) { renderHtml(response, failPage); return; } // ??? String filename = upload.getSecondName(); // ???? String name = upload.getFileName(); String ext = name.substring(name.lastIndexOf(".")); // ?? InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // response response.reset(); // responseHeader response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1") + ext); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { log.error(ex); } }