List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.duroty.application.mail.actions.AttachmentAction.java
/** * DOCUMENT ME!// ww w . j av a 2 s. c o m * * @param request DOCUMENT ME! * @param response DOCUMENT ME! * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ protected void doDownload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DataInputStream in = null; ByteArrayInputStream bais = null; ServletOutputStream op = null; try { String mid = request.getParameter("mid"); String part = request.getParameter("part"); Mail filesInstance = getMailInstance(request); MailPartObj obj = filesInstance.getAttachment(mid, part); int length = 0; op = response.getOutputStream(); String mimetype = obj.getContentType(); // // Set the response and go! // // Yes, I know that the RFC says 'attachment'. Unfortunately, IE has a typo // in it somewhere, and Netscape seems to accept this typing as well. // response.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); response.setContentLength((int) obj.getSize()); response.setHeader("Content-Disposition", "attachement; filename=\"" + obj.getName() + "\""); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "max-age=0"); // // Stream to the requester. // byte[] bbuf = new byte[1024]; bais = new ByteArrayInputStream(obj.getAttachent()); in = new DataInputStream(bais); while ((in != null) && ((length = in.read(bbuf)) != -1)) { op.write(bbuf, 0, length); } } catch (Exception ex) { } finally { try { op.flush(); } catch (Exception ex) { } IOUtils.closeQuietly(bais); IOUtils.closeQuietly(in); IOUtils.closeQuietly(op); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.GenericCandidaciesDA.java
public ActionForward downloadRecomendationFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final String confirmationCode = (String) getFromRequest(request, "confirmationCode"); final GenericApplicationLetterOfRecomentation file = getDomainObject(request, "fileExternalId"); if (file != null && file.getRecomentation() != null && file.getRecomentation().getConfirmationCode() != null && ((file.getRecomentation().getGenericApplication().getGenericApplicationPeriod() .isCurrentUserAllowedToMange()) || file.getRecomentation().getConfirmationCode().equals(confirmationCode))) { response.setContentType(file.getContentType()); response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\""); response.setContentLength(file.getSize().intValue()); final DataOutputStream dos = new DataOutputStream(response.getOutputStream()); dos.write(file.getContent());//from w ww . ja va 2 s . co m dos.close(); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST)); response.getWriter().close(); } return null; }
From source file:com.duroty.application.files.actions.DownloadFileAction.java
/** * DOCUMENT ME!/*from ww w . j a v a 2 s .c o m*/ * * @param request DOCUMENT ME! * @param response DOCUMENT ME! * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ protected void doDownload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DataInputStream in = null; ByteArrayInputStream bais = null; ServletOutputStream op = null; try { String mid = request.getParameter("mid"); String part = request.getParameter("part"); Files filesInstance = getFilesInstance(request); MailPartObj obj = filesInstance.getAttachment(mid, part); int length = 0; op = response.getOutputStream(); String mimetype = obj.getContentType(); // // Set the response and go! // // Yes, I know that the RFC says 'attachment'. Unfortunately, IE has a typo // in it somewhere, and Netscape seems to accept this typing as well. // response.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); response.setContentLength((int) obj.getSize()); response.setHeader("Content-Disposition", "attachement; filename=\"" + obj.getName() + "\""); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "max-age=0"); // // Stream to the requester. // byte[] bbuf = new byte[1024]; bais = new ByteArrayInputStream(obj.getAttachent()); in = new DataInputStream(bais); while ((in != null) && ((length = in.read(bbuf)) != -1)) { op.write(bbuf, 0, length); } } catch (Exception ex) { } finally { try { op.flush(); } catch (Exception ex) { } IOUtils.closeQuietly(bais); IOUtils.closeQuietly(in); IOUtils.closeQuietly(op); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.coordinator.thesis.ManageThesisDA.java
public ActionForward downloadIdentificationSheet(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Thesis thesis = getThesis(request);/*from w w w .jav a 2 s .com*/ try { StudentThesisIdentificationDocument document = new StudentThesisIdentificationDocument(thesis); byte[] data = ReportsUtils.exportToProcessedPdfAsByteArray(document); response.setContentLength(data.length); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", String.format("attachment; filename=%s.pdf", document.getReportFileName())); response.getOutputStream().write(data); return null; } catch (JRException e) { addActionMessage("error", request, "student.thesis.generate.identification.failed"); return listThesis(mapping, actionForm, request, response); } }
From source file:com.eryansky.modules.disk.utils.DiskUtils.java
/** * //from w ww.ja v a 2 s .com * @param request * @param response * @param inputStream ? * @param displayName ?? * @throws IOException */ public static void download(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String displayName) throws IOException { response.reset(); WebUtils.setNoCacheHeader(response); String contentType = "application/x-download"; if (StringUtils.isNotBlank(displayName)) { if (displayName.endsWith(".doc")) { contentType = "application/msword"; } else if (displayName.endsWith(".docx")) { contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } else if (displayName.endsWith(".xls")) { contentType = "application/vnd.ms-excel"; } else if (displayName.endsWith(".xlsx")) { contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } else if (displayName.endsWith(".ppt")) { contentType = "application/vnd.ms-powerpoint"; } else if (displayName.endsWith(".pptx")) { contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; } else if (displayName.endsWith(".pdf")) { contentType = "application/pdf"; } else if (displayName.endsWith(".jpg") || displayName.endsWith(".jpeg")) { contentType = "image/jpeg"; } else if (displayName.endsWith(".gif")) { contentType = "image/gif"; } else if (displayName.endsWith(".bmp")) { contentType = "image/bmp"; } } response.setContentType(contentType); response.setContentLength((int) inputStream.available()); // String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1); // displayFilename = displayFilename.replace(" ", "_"); WebUtils.setDownloadableHeader(request, response, displayName); BufferedInputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new BufferedInputStream(inputStream); IOUtils.copy(is, os); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(is); } }
From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java
public void writeBodyResponseAsJson(HttpServletResponse response, org.json.JSONObject data, Map<String, String> errors) { try {/*w w w. j av a 2 s.c o m*/ org.json.JSONObject jsonResponse = new org.json.JSONObject(); org.json.JSONObject jsonErrors = new org.json.JSONObject(); if (errors == null || errors.keySet().size() == 0) { jsonResponse.put("status", "OK"); } else { jsonResponse.put("status", "FAIL"); for (String key : errors.keySet()) { jsonErrors.put(key, errors.get(key)); } } jsonResponse.put("errors", jsonErrors); jsonResponse.put("payload", data); String jsonString = jsonResponse.toString(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ServletOutputStream writer = response.getOutputStream(); byte[] utf8bytes = jsonString.getBytes("UTF-8"); writer.write(utf8bytes); response.setContentLength(utf8bytes.length); writer.flush(); } catch (Exception e) { try { String errorResponse = "{\"status\":\"FAIL\",\"payload\":\"{}\",\"errors\":{\"reason\":\"WB_UNKNOWN_ERROR\"}}"; ServletOutputStream writer = response.getOutputStream(); response.setContentType("application/json"); byte[] utf8bytes = errorResponse.getBytes("UTF-8"); response.setContentLength(utf8bytes.length); writer.write(utf8bytes); writer.flush(); } catch (IOException ioe) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:com.cloud.servlet.StaticResourceServlet.java
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final File requestedFile = getRequestedFile(req); if (!requestedFile.exists() || !requestedFile.isFile()) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return;/*from ww w . j a va 2s .c o m*/ } final String etag = getEtag(requestedFile); if (etag.equals(req.getHeader("If-None-Match"))) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // have to send data, either compressed or the original final File compressedStatic = getCompressedVersion(requestedFile); InputStream fileContent = null; try { resp.setContentType(getContentType(requestedFile.getName())); resp.setHeader("ETag", etag); resp.setStatus(HttpServletResponse.SC_OK); if (isClientCompressionSupported(req) && compressedStatic.exists()) { // gzip compressed resp.setHeader("Content-Encoding", "gzip"); resp.setContentLength((int) compressedStatic.length()); fileContent = new FileInputStream(compressedStatic); } else { // uncompressed resp.setContentLength((int) requestedFile.length()); fileContent = new FileInputStream(requestedFile); } IOUtils.copy(fileContent, resp.getOutputStream()); } finally { IOUtils.closeQuietly(fileContent); } }
From source file:de.micromata.genome.gwiki.web.StaticFileServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uri = req.getPathInfo(); String servletp = req.getServletPath(); String respath = servletp + uri; if (uri == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return;//from www. j a v a 2s .c o m } InputStream is = getServletContext().getResourceAsStream(respath); if (is == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } long nt = new Date().getTime() + TimeInMillis.DAY; String mime = MimeUtils.getMimeTypeFromFile(respath); if (StringUtils.equals(mime, "application/x-shockwave-flash")) { resp.setHeader("Cache-Control", "cache, must-revalidate"); resp.setHeader("Pragma", "public"); } resp.setDateHeader("Expires", nt); resp.setHeader("Cache-Control", "max-age=86400, public"); if (mime != null) { resp.setContentType(mime); } byte[] data = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); resp.setContentLength(data.length); IOUtils.write(data, resp.getOutputStream()); }
From source file:com.spring.tutorial.controllers.DefaultController.java
@RequestMapping(value = "/my-drive/dropbox/downloads/**", method = RequestMethod.GET) public String getDropboxFile(HttpServletRequest request, HttpServletResponse response) throws IOException, DbxException { config = new DbxRequestConfig("JavaTutorial/1.0", Locale.getDefault().toString()); DbxClient client = new DbxClient(config, (String) request.getSession().getAttribute("dropbox_token")); String path = request.getServletPath() .substring(request.getServletPath().indexOf("/my-drive/dropbox/downloads/") + 27); ServletOutputStream outputStream = response.getOutputStream(); try {//from w w w . j ava 2 s . co m DbxEntry.File downloadedFile = client.getFile(path, null, outputStream); String mimeType = "application/octet-stream"; response.setContentType(mimeType); response.setContentLength((int) downloadedFile.numBytes); String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadedFile.name); } finally { outputStream.close(); } return ""; }
From source file:org.fao.fenix.maps.web.rest.MapsRESTService.java
private void handleException(HttpServletResponse response, String message) throws IOException { String output = Wrapper.wrapAsHTML(message).toString(); response.setContentLength(output.length()); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(output);/*from w w w. jav a2 s . co m*/ out.close(); out.flush(); }