List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.metamesh.opencms.rfs.RfsFileLoader.java
/** * @see org.opencms.loader.I_CmsResourceLoader#load(org.opencms.file.CmsObject, org.opencms.file.CmsResource, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w . ja v a2 s . com public void load(CmsObject cms, CmsResource resource, HttpServletRequest req, HttpServletResponse res) throws IOException, CmsException { if (canSendLastModifiedHeader(resource, req, res)) { // no further processing required return; } // set response status to "200 - OK" (required for static export "on-demand") res.setStatus(HttpServletResponse.SC_OK); // set content length header res.setContentLength(resource.getLength()); if (CmsWorkplaceManager.isWorkplaceUser(req)) { // prevent caching for Workplace users res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis()); CmsRequestUtil.setNoCacheHeaders(res); } else { // set date last modified header res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, resource.getDateLastModified()); // set "Expires" only if cache control is not already set if (!res.containsHeader(CmsRequestUtil.HEADER_CACHE_CONTROL)) { long expireTime = resource.getDateExpired(); if (expireTime == CmsResource.DATE_EXPIRED_DEFAULT) { expireTime--; // flex controller will automatically reduce this to a reasonable value } // now set "Expires" header CmsFlexController.setDateExpiresHeader(res, expireTime, m_clientCacheMaxAge); } } service(cms, resource, req, res); }
From source file:com.orange.mmp.api.ws.rest.RestResponse.java
/** * Send the Rest Response based on the response Object and the HttpServletResponse * //from ww w . ja v a 2 s . c om * @param rootElement The XML root element name of the response * @param responseClass The Class of the response Object * @param responseObject The response object * @param errorType Service error type (body or http) * @param httpServletResponse The HttpServletResponse to use to send response * @throws MMPException */ @SuppressWarnings({ "unchecked", "deprecation" }) protected void send(String rootElement, Class responseClass, Object responseObject, String errorType, HttpServletResponse httpServletResponse) throws MMPException { if (errorType == null || errorType.length() == 0) errorType = RETURN_TYPE_BODY; //Specific status code handling if (this.responseContext.getStatusCode() >= 300) { try { if (errorType.equals(RETURN_TYPE_HTTP)) { httpServletResponse.setContentLength(0); httpServletResponse.setStatus(this.responseContext.getStatusCode(), this.responseContext.getStatusMessage()); } else { String responseStr = "<?xml version=\"1.0\" encoding=\"" + Constants.DEFAULT_ENCODING + "\"?>" + "<error>" + "<code>" + this.responseContext.getStatusCode() + "</code>" + "<message><![CDATA[" + this.responseContext.getStatusMessage() + "]]></message>" + "</error>"; responseContext.setContentLength(responseStr.getBytes(Constants.DEFAULT_ENCODING).length); responseContext.setContentType(com.orange.mmp.cadap.Constants.MIME_TYPE_XMLCONTENT); responseContext.setCharacterEncoding(Constants.DEFAULT_ENCODING); responseContext.getWriter().write(responseStr); } } catch (IOException ioe) { throw new MMPApiException(ioe); } } //Throwed Error handling else if (responseClass.isAssignableFrom(Throwable.class)) { this.parseThrowable((Throwable) responseObject); try { if (errorType.equals(RETURN_TYPE_HTTP)) { httpServletResponse.setContentLength(0); httpServletResponse.sendError(this.responseContext.getStatusCode(), this.responseContext.getStatusMessage()); } else { String responseStr = "<?xml version=\"1.0\" encoding=\"" + Constants.DEFAULT_ENCODING + "\"?>" + "<error>" + "<code>" + this.responseContext.getStatusCode() + "</code>" + "<message><![CDATA[" + this.responseContext.getStatusMessage() + "]]></message>" + "</error>"; responseContext.setContentLength(responseStr.getBytes(Constants.DEFAULT_ENCODING).length); responseContext.setContentType(com.orange.mmp.cadap.Constants.MIME_TYPE_XMLCONTENT); responseContext.setCharacterEncoding(Constants.DEFAULT_ENCODING); responseContext.getWriter().write(responseStr); } } catch (IOException ioe) { throw new MMPApiException(ioe); } } //Void handling (hardcoded for perfomances but can be done with JAXB using null element marshalling) else if (responseClass.getName().equals("void")) { String responseStr = "<?xml version=\"1.0\" encoding=\"" + Constants.DEFAULT_ENCODING + "\"?>" + "<" + rootElement + "/>"; try { responseContext.setContentLength(responseStr.getBytes(Constants.DEFAULT_ENCODING).length); responseContext.setContentType(com.orange.mmp.cadap.Constants.MIME_TYPE_XMLCONTENT); responseContext.setCharacterEncoding(Constants.DEFAULT_ENCODING); responseContext.getWriter().write(responseStr); } catch (IOException ioe) { throw new MMPApiException(ioe); } } //Others cases else { try { String ae = this.requestContext.getHeader("accept-encoding"); boolean gzip = (ae != null && ae.indexOf("gzip") != -1); ByteArrayInputStream in = null; //If response is an array of byte[], handled as binary data transfer (download) if (responseObject != null && responseObject.getClass().isAssignableFrom(byte[].class) && !responseObject.getClass().isAssignableFrom(String.class)) { if (gzip) { byte[] zippedResult = this.gzip((byte[]) responseObject); responseContext.setContentLength(zippedResult.length); responseContext.addHeader("Content-Encoding", "gzip"); in = new ByteArrayInputStream(zippedResult); } else { responseContext.setContentLength(((byte[]) responseObject).length); in = new ByteArrayInputStream((byte[]) responseObject); } if (responseContext.getContentType() == null) { responseContext.setContentType(com.orange.mmp.cadap.Constants.MIME_TYPE_OCTETSTREAM); } } //XML Binding else { ByteArrayOutputStream out = new ByteArrayOutputStream(); responseContext.setContentType(com.orange.mmp.cadap.Constants.MIME_TYPE_XMLCONTENT); try { new XMLBinding().write(responseObject, out, responseClass, rootElement); } catch (BindingException be) { throw new MMPException(be); } if (gzip) { byte[] zippedResult = this.gzip(out.toByteArray()); responseContext.setContentLength(zippedResult.length); responseContext.addHeader("Content-Encoding", "gzip"); in = new ByteArrayInputStream(zippedResult); } else { responseContext.setContentLength(out.size()); in = new ByteArrayInputStream(out.toByteArray()); } } IOUtils.copy(in, responseContext.getOutputStream()); } catch (IOException ioe) { throw new MMPApiException(ioe); } } }
From source file:architecture.ee.web.community.spring.controller.DownloadController.java
@RequestMapping(value = "/streams/photo/{linkId}", method = RequestMethod.GET) @ResponseBody/*from ww w . ja v a2 s.c o m*/ public void handleStreamPhoto(@PathVariable("linkId") String linkId, HttpServletResponse response) throws IOException { try { Photo photo = photoStreamsManager.getPhotoById(linkId); Image image = imageManager.getImage(photo.getImageId()); InputStream input = imageManager.getImageInputStream(image); String contentType = image.getContentType(); int contentLength = image.getSize(); response.setContentType(contentType); response.setContentLength(contentLength); IOUtils.copy(input, response.getOutputStream()); response.flushBuffer(); } catch (NotFoundException e) { response.sendError(404); } }
From source file:com.qcadoo.report.internal.controller.ReportController.java
@RequestMapping(value = "generateReportForEntity/{templatePlugin}/{templateName}", method = RequestMethod.GET) public void generateReportForEntity(@PathVariable("templatePlugin") final String templatePlugin, @PathVariable("templateName") final String templateName, @RequestParam("id") final List<Long> entityIds, @RequestParam("additionalArgs") final String requestAdditionalArgs, final HttpServletRequest request, final HttpServletResponse response, final Locale locale) throws ReportException { ReportService.ReportType reportType = getReportType(request); Map<String, String> additionalArgs = convertJsonStringToMap(requestAdditionalArgs); response.setContentType(reportType.getMimeType()); try {/*from w w w.j a v a 2 s . c o m*/ int bytes = copy(new ByteArrayInputStream(reportService.generateReportForEntity(templatePlugin, templateName, reportType, entityIds, additionalArgs, locale)), response.getOutputStream()); response.setContentLength(bytes); } catch (IOException e) { throw new ReportException(ReportException.Type.ERROR_WHILE_COPYING_REPORT_TO_RESPONSE, e); } disableCache(response); }
From source file:com.gantzgulch.sharing.controller.SharedFileDownloadController.java
@RequestMapping(method = RequestMethod.GET) public void showUploadForm(@RequestParam(required = true) String id, final HttpServletResponse response, final HttpServletRequest request) { SharedFile sharedFile = sharedFileManager.findById(id); InputStream is = null;/*from ww w.j ava2 s.c o m*/ OutputStream os = null; try { is = sharedFileManager.download(id, userManager.getCurrentUser()); os = response.getOutputStream(); response.setHeader("Content-Disposition", "attachment; filename=\"" + sharedFile.getFilename() + "\""); response.setHeader("Content-Type", "application/force-download"); if (sharedFile.getSize() < Integer.MAX_VALUE) { response.setContentLength((int) sharedFile.getSize()); } IOUtils.copyLarge(is, os); os.flush(); } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { IOUtils.closeQuietly(is); } }
From source file:be.fedict.eid.dss.sp.servlet.DownloadServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); HttpSession httpSession = request.getSession(); byte[] document = (byte[]) httpSession.getAttribute("document"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1 if (!request.getScheme().equals("https")) { // else the download fails in IE response.setHeader("Pragma", "no-cache"); // http 1.0 } else {//from w ww .java 2 s. c o m response.setHeader("Pragma", "public"); } response.setDateHeader("Expires", -1); response.setContentLength(document.length); String contentType = (String) httpSession.getAttribute("ContentType"); LOG.debug("content-type: " + contentType); response.setContentType(contentType); response.setContentLength(document.length); ServletOutputStream out = response.getOutputStream(); out.write(document); out.flush(); }
From source file:com.igame.app.controller.Image2Controller.java
@RequestMapping(value = "/app-{appid:\\d+}/{id:\\d+}-thumbnail.{type}", method = RequestMethod.GET) public void thumbnail(HttpServletResponse response, @PathVariable("appid") Long appid, @PathVariable("id") Long id) { log.debug("thumbnail {}", id); Image image = imageService.get(id); System.out.println(/* w ww .ja v a 2 s . co m*/ "======= " + fileUploadDirectory + "/" + "app-" + appid + "/" + image.getThumbnailFilename()); File imageFile = new File(fileUploadDirectory + "/" + "app-" + appid + "/" + image.getThumbnailFilename()); response.setContentType(image.getContentType()); response.setContentLength(image.getThumbnailSize().intValue()); try { InputStream is = new FileInputStream(imageFile); IOUtils.copy(is, response.getOutputStream()); } catch (IOException e) { log.error("Could not show thumbnail " + id, e); } }
From source file:com.enonic.cms.server.service.portal.mvc.controller.AttachmentController.java
private void putBinaryOnResponse(boolean download, HttpServletResponse response, BinaryDataEntity binaryData) throws IOException { final BlobRecord blob = this.binaryService.fetchBinary(binaryData.getBinaryDataKey()); HttpServletUtil.setContentDisposition(response, download, binaryData.getName()); response.setContentType(HttpServletUtil.resolveMimeType(getServletContext(), binaryData.getName())); response.setContentLength((int) blob.getLength()); ByteStreams.copy(blob.getStream(), response.getOutputStream()); }
From source file:com.gcrm.action.crm.BaseEditAction.java
/** * response?/*w w w. j a v a 2 s . c o m*/ * * @param bytes * @param fileName * @throws Exception */ protected void response2download(byte[] bytes, String fileName) throws Exception { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/octet-stream"); response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setContentLength(bytes.length); response.getOutputStream().write(bytes); }
From source file:org.gallery.web.controller.ImageController.java
@RequestMapping(value = "/picture/{id}", method = RequestMethod.GET) public void picture(HttpServletResponse response, @PathVariable Long id) { ImageEntity entity = imageDao.getById(id); String thumbnailFilename = entity.getName(); File imageFile = new File(fileUploadDirectory + File.separatorChar + thumbnailFilename); response.setContentType(entity.getContentType()); response.setContentLength((int) imageFile.length()); try {/* w w w. j a va 2 s . c o m*/ InputStream is = new FileInputStream(imageFile); IOUtils.copy(is, response.getOutputStream()); // IOUtils.copy(is,new // FileOutputStream("c:\\tmp\\picture-"+thumbnailFilename)); } catch (IOException e) { log.error("Could not show picture " + id, e); } }