List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.twosigma.beaker.core.module.elfinder.impl.commands.FileCommand.java
@Override public void execute(FsService fsService, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) throws Exception { String target = request.getParameter("target"); boolean download = "1".equals(request.getParameter("download")); FsItemEx fsi = super.findItem(fsService, target); String mime = fsi.getMimeType(); response.setCharacterEncoding("utf-8"); response.setContentType(mime);//from w w w .j a v a2 s. c om //String fileUrl = getFileUrl(fileTarget); //String fileUrlRelative = getFileUrl(fileTarget); String fileName = fsi.getName(); //fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1"); if (download || MimeTypesUtils.isUnknownType(mime)) { response.setHeader("Content-Disposition", "attachments; " + getAttachementFileName(fileName, request.getHeader("USER-AGENT"))); //response.setHeader("Content-Location", fileUrlRelative); response.setHeader("Content-Transfer-Encoding", "binary"); } OutputStream out = response.getOutputStream(); InputStream is = null; response.setContentLength((int) fsi.getSize()); try { // serve file is = fsi.openInputStream(); IOUtils.copy(is, out); out.flush(); out.close(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.dotmarketing.portlets.cmsmaintenance.ajax.IndexAjaxAction.java
public void downloadIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DotDataException { Map<String, String> map = getURIParams(); response.setContentType("application/zip"); String indexName = getIndexNameOrAlias(map); if (!UtilMethods.isSet(indexName)) return;// w ww .j a v a 2s . com if (indexName.equalsIgnoreCase("live") || indexName.equalsIgnoreCase("working")) { IndiciesInfo info = APILocator.getIndiciesAPI().loadIndicies(); if (indexName.equalsIgnoreCase("live")) { indexName = info.live; } if (indexName.equalsIgnoreCase("working")) { indexName = info.working; } } File f = APILocator.getESIndexAPI().backupIndex(indexName); response.setContentLength((int) f.length()); OutputStream out = response.getOutputStream(); InputStream in = new FileInputStream(f); response.setHeader("Content-Type", "application/zip"); response.setHeader("Content-Disposition", "attachment; filename=" + indexName + ".zip"); IOUtils.copyLarge(in, out); f.delete(); return; }
From source file:it.geosolutions.opensdi.operations.FolderManagerOperationController.java
/** * Download a file with a stream//from www. ja va2 s .c o m * * @param resp * @param fileName * @param filePath * @return */ @SuppressWarnings("resource") private ResponseEntity<byte[]> download(HttpServletResponse resp, String fileName, String filePath) { final HttpHeaders headers = new HttpHeaders(); File toServeUp = new File(filePath); InputStream inputStream = null; try { inputStream = new FileInputStream(toServeUp); } catch (FileNotFoundException e) { // Also useful, this is a good was to serve down an error message String msg = "ERROR: Could not find the file specified."; headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND); } resp.setContentType("application/octet-stream"); resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); Long fileSize = toServeUp.length(); resp.setContentLength(fileSize.intValue()); OutputStream outputStream = null; try { outputStream = resp.getOutputStream(); } catch (IOException e) { String msg = "ERROR: Could not generate output stream."; headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND); } byte[] buffer = new byte[1024]; int read = 0; try { while ((read = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, read); } // close the streams to prevent memory leaks outputStream.flush(); outputStream.close(); inputStream.close(); } catch (Exception e) { String msg = "ERROR: Could not read file."; headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND); } return null; }
From source file:com.baidu.jprotobuf.rpc.server.HttpRequestHandlerServlet.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String context = request.getPathInfo(); if (context == null) { LOGGER.warn("invalid request path."); response.setStatus(HttpServletResponse.SC_NOT_FOUND); return;/*from w w w .j a v a2s . c o m*/ } else { if (context.startsWith("/")) { context = context.substring(1); } if (!serviceMap.containsKey(context)) { LOGGER.warn("invalid request path service name[" + context + "] not found."); response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } try { ServiceExporter idlServiceExporter = serviceMap.get(context); //to check if a get idl request if (request.getParameter(ServiceExporter.INPUT_IDL_PARAMETER) != null) { String inputIDL = idlServiceExporter.getInputIDL(); if (inputIDL != null) { response.setContentLength(inputIDL.length()); response.getOutputStream().write(inputIDL.getBytes()); return; } } else if (request.getParameter(ServiceExporter.OUTPUT_IDL_PARAMETER) != null) { String outputIDL = idlServiceExporter.getOutputIDL(); if (outputIDL != null) { response.setContentLength(outputIDL.length()); response.getOutputStream().write(outputIDL.getBytes()); return; } } IDLProxyObject inputIDLProxyObject = idlServiceExporter.getInputProxyObject(); IDLProxyObject input = null; if (inputIDLProxyObject != null && request.getContentLength() > 0) { byte[] bytes = readStream(request.getInputStream(), request.getContentLength()); input = inputIDLProxyObject.decode(bytes); } IDLProxyObject result = idlServiceExporter.execute(input); if (result != null) { byte[] bytes = result.encode(); response.setContentLength(bytes.length); response.getOutputStream().write(bytes); } } catch (Exception ex) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()); } finally { response.getOutputStream().flush(); response.getOutputStream().close(); } }
From source file:com.zimbra.cs.servlet.ZimbraServlet.java
/** * Filter the request based on incoming port. If the allowed.ports * parameter is specified for the servlet, the incoming port must * match one of the listed ports./* ww w . j av a2s. c o m*/ */ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean allowed = isRequestOnAllowedPort(request); if (!allowed) { SoapProtocol soapProto = SoapProtocol.Soap12; ServiceException e = ServiceException.FAILURE("Request not allowed on port " + request.getLocalPort(), null); ZimbraLog.soap.warn(null, e); Element fault = SoapProtocol.Soap12.soapFault(e); Element envelope = SoapProtocol.Soap12.soapEnvelope(fault); byte[] soapBytes = envelope.toUTF8(); response.setContentType(soapProto.getContentType()); response.setBufferSize(soapBytes.length + 2048); response.setContentLength(soapBytes.length); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getOutputStream().write(soapBytes); return; } super.service(request, response); }
From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java
private void doDownloadTemplatePost(HttpServletRequest request, HttpServletResponse response) { VitroRequest vreq = new VitroRequest(request); FileHarvestJob job = getJob(vreq, vreq.getParameter(PARAMETER_JOB)); File fileToSend = new File(job.getTemplateFilePath()); response.setContentType("application/octet-stream"); response.setContentLength((int) (fileToSend.length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileToSend.getName() + "\""); try {//w w w. j a v a 2 s .co m byte[] byteBuffer = new byte[(int) (fileToSend.length())]; DataInputStream inStream = new DataInputStream(new FileInputStream(fileToSend)); ServletOutputStream outputStream = response.getOutputStream(); for (int length = inStream.read(byteBuffer); length != -1; length = inStream.read(byteBuffer)) { outputStream.write(byteBuffer, 0, length); } inStream.close(); outputStream.flush(); outputStream.close(); } catch (IOException e) { log.error(e, e); } }
From source file:com.webpagebytes.cms.controllers.FileController.java
public void serveResource(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { InputStream is = null;//from ww w .j a v a2 s. com OutputStream os = null; try { Long key = Long.valueOf((String) request.getAttribute("key")); WPBFile wbfile = adminStorage.get(key, WPBFile.class); WPBFilePath cloudFile = new WPBFilePath(PUBLIC_BUCKET, wbfile.getBlobKey()); is = cloudFileStorage.getFileContent(cloudFile); response.setContentType(wbfile.getAdjustedContentType()); response.setContentLength(wbfile.getSize().intValue()); os = response.getOutputStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
From source file:com.portfolio.data.attachment.FileServlet.java
void InitAnswer(HttpURLConnection connection, HttpServletResponse response, String referer) throws MalformedURLException, IOException { String ref = null;//from w ww. j av a2 s .c om if (referer != null) { int first = referer.indexOf('/', 7); int last = referer.lastIndexOf('/'); ref = referer.substring(first, last); } response.setContentType(connection.getContentType()); response.setStatus(connection.getResponseCode()); response.setContentLength(connection.getContentLength()); /// Transfer headers Map<String, List<String>> headers = connection.getHeaderFields(); int size = headers.size(); for (int i = 1; i < size; ++i) { String key = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); // response.setHeader(key, value); response.addHeader(key, value); } /// Deal with correct path with set cookie List<String> setValues = headers.get("Set-Cookie"); if (setValues != null) { String setVal = setValues.get(0); int pathPlace = setVal.indexOf("Path="); if (pathPlace > 0) { setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break setVal = setVal + ref; response.setHeader("Set-Cookie", setVal); } } }
From source file:com.rplt.studioMusik.controller.OperatorController.java
@RequestMapping(value = "/cetakNota", method = RequestMethod.GET) public String cetakNota(HttpServletResponse response) { Connection conn = DatabaseConnection.getmConnection(); // File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file File reportFile = new File( servletConfig.getServletContext().getRealPath("/resources/report/nota_persewaan.jasper")); Map parameters = new HashMap(); Map<String, Object> params = new HashMap<String, Object>(); params.put("P_KODESEWA", request.getParameter("kodeSewa")); byte[] bytes = null; try {/*from w w w. ja va2 s .com*/ bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn); } catch (JRException ex) { Logger.getLogger(OperatorController.class.getName()).log(Level.SEVERE, null, ex); } response.setContentType("application/pdf"); response.setContentLength(bytes.length); try { ServletOutputStream outStream = response.getOutputStream(); outStream.write(bytes, 0, bytes.length); outStream.flush(); outStream.close(); } catch (IOException ex) { Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex); } return "halaman-cetakNota-operator"; }
From source file:it.eng.spagobi.tools.downloadFiles.service.DownloadZipAction.java
private void manageDownload(String fileName, String fileExtension, String folderPath, HttpServletResponse response, boolean deleteFile) { logger.debug("IN"); try {/*from www. j a va 2s. co m*/ File exportedFile = new File(folderPath + "/" + fileName); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileExtension + "\";"); byte[] exportContent = "".getBytes(); FileInputStream fis = null; try { fis = new FileInputStream(exportedFile); exportContent = GeneralUtilities.getByteArrayFromInputStream(fis); } catch (IOException ioe) { logger.error("Cannot get bytes of the download file", ioe); } response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";"); response.setContentLength(exportContent.length); response.getOutputStream().write(exportContent); response.getOutputStream().flush(); if (fis != null) fis.close(); if (deleteFile) { exportedFile.delete(); } } catch (IOException ioe) { logger.error("Cannot flush response", ioe); } finally { logger.debug("OUT"); } }