List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.stimulus.archiva.presentation.DownloadMessageBean.java
@Override protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = request.getParameter("name"); //String fileName = ((MessageBean)form).getOriginalMessageFileName(); logger.debug("download original email {fileName='" + fileName + "'}"); String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) { String codedfilename = URLEncoder.encode(fileName, "UTF8"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { String codedfilename = MimeUtility.encodeText(fileName, "UTF8", "B"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename); } else {/*from w ww .ja v a2 s .c o m*/ response.setHeader("Content-Disposition", "attachment;filename=" + fileName); } String contentType = "message/rfc822"; //String filePath = ((MessageBean)form).getOriginalMessageFilePath(); String filePath = Config.getFileSystem().getViewPath() + File.separatorChar + fileName; File file = new File(filePath); response.setContentLength((int) file.length()); Config.getFileSystem().getTempFiles().markForDeletion(file); return new FileStreamInfo(contentType, file); }
From source file:com.npower.dl.SoftwareDownloadServlet.java
public void doDownloadDescriptor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestUrl = request.getRequestURL().toString(); String requestUri = request.getRequestURI(); log.info("Download Service: Download Descriptor: url: " + requestUrl); log.info("Download Service: Download Descriptor: uri: " + requestUri); String packageID = parserPackageID(requestUri); log.info("Software Download Service: Request package ID: " + packageID); DownloadDescriptor descriptor = new SoftwareDownloadDescriptor(); descriptor.setDownloadID(packageID); try {/* w ww . ja v a2s . com*/ String serverURL = DownloadFactory.getServerURL(requestUrl); String baseURL = serverURL + request.getContextPath(); descriptor.setDownloadURI(baseURL + "/download/software/"); descriptor.setInstallNotifyURI(baseURL + "/download/notification/"); String content = descriptor.getContent(); response.setContentType(descriptor.getContentType()); response.setContentLength(content.length()); OutputStream out = response.getOutputStream(); out.write(content.getBytes("UTF-8")); out.flush(); out.close(); log.debug("Download Descriptor Content: " + content); } catch (Exception ex) { throw new ServletException(ex); } finally { } }
From source file:com.evolveum.midpoint.gui.impl.util.ReportPeerQueryInterceptor.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!checkRequest(request, response, OPERATION_GET_REPORT)) { return;//from w ww . j ava 2s . co m } String fileName = getFileName(request); if (containsProhibitedQueryString(fileName)) { LOGGER.debug("Query parameter contains a prohibited character sequence. The parameter: {} ", fileName); response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } StringBuilder buildfilePath = new StringBuilder(EXPORT_DIR).append(fileName); String filePath = buildfilePath.toString(); File loadedFile = new File(filePath); if (!isFileAndExists(loadedFile, fileName, response, OPERATION_GET_REPORT)) { return; } FileInputStream fileInputStream = new FileInputStream(filePath); ServletContext context = getServletContext(); String mimeType = context.getMimeType(filePath); if (mimeType == null) { // MIME mapping not found mimeType = DEFAULTMIMETYPE; } response.setContentType(mimeType); response.setContentLength((int) loadedFile.length()); StringBuilder headerValue = new StringBuilder("attachment; filename=\"%s\"").append(fileName); response.setHeader("Content-Disposition", headerValue.toString()); OutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) > -1) { outputStream.write(buffer, 0, len); } IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(outputStream); LOGGER.trace("The file {} has been dispatched to the client.", fileName); }
From source file:uk.org.iay.mdq.server.ResultRawView.java
@Override public void render(final Map<String, ?> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final Result result = (Result) model.get("result"); log.debug("rendering as {}", getContentType()); if (result.isNotFound()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;// ww w .j av a 2 s . c o m } // select the representation to provide Representation rep = null; final String acceptEncoding = request.getHeader(HttpHeaders.ACCEPT_ENCODING); if (acceptEncoding != null) { if (acceptEncoding.contains("gzip")) { rep = result.getGZIPRepresentation(); } else if (acceptEncoding.contains("compress")) { rep = result.getDeflateRepresentation(); } } // default to the normal representation if (rep == null) { rep = result.getRepresentation(); } // Set response headers String contentEncoding = rep.getContentEncoding(); if (contentEncoding != null) { response.setHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding); } else { // for logging only contentEncoding = "normal"; } response.setContentType(getContentType()); response.setContentLength(rep.getBytes().length); response.setHeader(HttpHeaders.ETAG, rep.getETag()); log.debug("selected ({}) representation is {} bytes", contentEncoding, rep.getBytes().length); response.getOutputStream().write(rep.getBytes()); }
From source file:ro.fils.angularspring.controller.ProjectsController.java
@RequestMapping(method = RequestMethod.GET, value = "/downloadXML") public void downloadXML(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException, BadElementException { ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); String fullPath = appPath + "Projects.xml"; PDFCreator creator = new PDFCreator(); creator.saveAsXML(projectsDocumentRepository.findOne(ConnectionUtils.PROJECTS_COLLECTION).getContent(), fullPath);//from w w w.j a v a2 s . c o m System.out.println("appPath = " + appPath); File downloadFile = new File(fullPath); FileInputStream inputStream = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(fullPath); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } inputStream.close(); outStream.close(); }
From source file:com.spring.tutorial.controllers.DefaultController.java
@RequestMapping(value = "/files/{id}", method = RequestMethod.GET) public String getFile(@PathVariable("id") String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws IOException, Exception { String _id = request.getSession().getAttribute("id").toString(); MongoData data = new MongoData(); GridFS collection = new GridFS(data.getDB(), _id + "_files"); BasicDBObject query = new BasicDBObject(); query.put("_id", new ObjectId(id)); GridFSDBFile file = collection.findOne(query); DBCollection metaFileCollection = data.getDB().getCollection(_id + "_files_meta"); BasicDBObject metaQuery = new BasicDBObject(); metaQuery.put("file-id", new ObjectId(id)); DBObject metaFileDoc = metaFileCollection.findOne(metaQuery); MongoFile metaFile = new MongoFile(metaFileDoc); ServletOutputStream out = response.getOutputStream(); String mimeType = metaFile.getType(); response.setContentType(mimeType);/* www . j a v a 2s . c om*/ response.setContentLength((int) file.getLength()); String headerKey = "Content-Disposition"; File f = File.createTempFile(file.getFilename(), metaFile.getType().substring(metaFile.getType().indexOf("/") + 1)); String headerValue = String.format("attachment; filename=\"%s\"", file.getFilename()); response.setHeader(headerKey, headerValue); file.writeTo(f); FileInputStream inputStream = new FileInputStream(f); byte[] buffer = new byte[4096]; int bytesRead = -1; while (inputStream.read(buffer, 0, 4096) != -1) { out.write(buffer, 0, 4096); } inputStream.close(); out.flush(); out.close(); return "mydrive/temp"; }
From source file:org.nsesa.editor.gwt.an.amendments.server.service.PdfExportService.java
@Override public void export(AmendmentContainerDTO object, HttpServletResponse response) { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=" + object.getAmendmentContainerID() + ".pdf"); response.setCharacterEncoding("UTF8"); final String content = object.getBody(); final InputSource inputSource; byte[] bytes = content.getBytes(Charset.forName("UTF-8")); inputSource = new InputSource(new ByteArrayInputStream(bytes)); try {//from w w w . ja va 2 s. co m final NodeModel model = NodeModel.parse(inputSource); final Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); configuration.setDirectoryForTemplateLoading(template.getFile().getParentFile()); final StringWriter sw = new StringWriter(); Map<String, Object> root = new HashMap<String, Object>(); root.put("amendment", model); configuration.getTemplate(template.getFile().getName()).process(root, sw); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(sw.toString(), editorUrl + "/"); renderer.layout(); renderer.createPDF(response.getOutputStream()); response.setContentLength(sw.toString().length()); response.flushBuffer(); } catch (IOException e) { throw new RuntimeException("Could not read file.", e); } catch (SAXException e) { throw new RuntimeException("Could not parse file.", e); } catch (ParserConfigurationException e) { throw new RuntimeException("Could not parse file.", e); } catch (TemplateException e) { throw new RuntimeException("Could not load template.", e); } catch (DocumentException e) { throw new RuntimeException("Export to pdf failed", e); } }
From source file:code.Servlet.java
private void getStartData(BufferedReader reader, HttpServletResponse response, Statement stmt, PrintWriter out) throws IOException, SQLException { String line = reader.readLine(); String idEvent = line.substring(12, line.length() - 2); String query = "select * from event where idEvent=" + idEvent + "'"; ResultSet res = stmt.executeQuery(query); if (!res.next()) { System.out.println("Nessun evento"); }/*from www. j a va 2s. com*/ String resp = res.getString("start_lat") + "," + res.getString("start_lon"); response.setContentType("text/plain"); response.setContentLength(resp.length()); PrintWriter reply = response.getWriter(); reply.println(resp); out.close(); //non so se serve out out.flush(); }
From source file:alpha.portal.webapp.controller.PayloadVersionsController.java
/** * Gets the payload./*from w w w . j ava2 s . c om*/ * * @param request * the request * @param response * the response * @return the payload * @throws IOException * Signals that an I/O exception has occurred. */ @RequestMapping(method = RequestMethod.GET, params = { "seqNumber" }) public String getPayload(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final Locale locale = request.getLocale(); if ((request.getParameter("card") == null) || (request.getParameter("case") == null)) { this.saveError(request, this.getText("payloadVersions.cardNotFound", locale)); return ""; } final String cardId = request.getParameter("card"); final String caseId = request.getParameter("case"); final AlphaCard currentCard = this.alphaCardManager.get(new AlphaCardIdentifier(caseId, cardId)); final Payload payload = this.payloadManager .getVersion(new PayloadIdentifier(currentCard.getPayload().getPayloadIdentifier().getPayloadId(), Long.parseLong(request.getParameter("seqNumber")))); if (payload != null) { final BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(payload.getContent())); response.setBufferSize(payload.getContent().length); response.setContentType(payload.getMimeType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + payload.getFilename() + "\""); response.setContentLength(payload.getContent().length); FileCopyUtils.copy(in, response.getOutputStream()); in.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } return "redirect:/payloadVersions?case=" + currentCard.getAlphaCardIdentifier().getCaseId() + "&card=" + currentCard.getAlphaCardIdentifier().getCardId(); }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractLogoController.java
private void logoResponse(String imagePath, String defaultImagePath, HttpServletResponse response, String cssdkFilesDirectory) { FileInputStream fileinputstream = null; String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath); if (StringUtils.isNotBlank(cssdkFilesDirectory)) { rootImageDir = cssdkFilesDirectory; }/* w w w .ja va 2s .com*/ if (rootImageDir != null && !rootImageDir.trim().equals("")) { try { if (imagePath != null && !imagePath.trim().equals("")) { String absoluteImagePath = FilenameUtils.concat(rootImageDir, imagePath); fileinputstream = new FileInputStream(absoluteImagePath); if (fileinputstream != null) { int numberBytes = fileinputstream.available(); byte bytearray[] = new byte[numberBytes]; fileinputstream.read(bytearray); response.setContentType("image/" + FilenameUtils.getExtension(imagePath)); // TODO:Set Cache headers for browser to force browser to cache to reduce load OutputStream outputStream = response.getOutputStream(); response.setContentLength(numberBytes); outputStream.write(bytearray); outputStream.flush(); outputStream.close(); fileinputstream.close(); return; } } } catch (FileNotFoundException e) { logger.debug("###File not found in retrieving logo " + imagePath); } catch (IOException e) { logger.debug("###IO Error in retrieving logo"); } } response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", defaultImagePath); }