List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.iana.dver.controller.DverUserController.java
@RequestMapping("/downloadDver/{dverDetailId}") @ResponseBody/*from www .j av a2 s . co m*/ public byte[] getDverFile(@PathVariable("dverDetailId") Integer dverDetailId, HttpServletRequest request, HttpServletResponse response) throws IOException { try { logger.info("Perform download Dver File....."); DverFileVO dverFileVO = this.dverDetailsService.getDverFileFromDverDetail(dverDetailId); if (dverFileVO != null) { byte[] bytes = dverFileVO.getDverContent(); response.setHeader("Content-Disposition", "attachment; filename=\"" + dverFileVO.getDverName() + ".pdf\""); response.setContentLength(bytes.length); response.setContentType("application/pdf"); return bytes; } else { return null; } } catch (Exception ex) { DVERUtil.sendExceptionEmails("getDverFile method of DverUserController \n " + ex); logger.error("Error in getDverFile()....." + ex); return null; } }
From source file:com.ibm.jaggr.core.impl.layer.LayerImpl.java
protected void setResponseHeaders(HttpServletRequest request, HttpServletResponse response, int size) { response.setContentType("application/x-javascript; charset=utf-8"); //$NON-NLS-1$ response.setContentLength(size); if (RequestUtil.isGzipEncoding(request)) { response.setHeader("Content-Encoding", "gzip"); //$NON-NLS-1$ //$NON-NLS-2$ }/*from ww w .j a v a 2 s .co m*/ }
From source file:net.sf.ehcache.constructs.web.filter.CachingFilter.java
/** * Writes the response content.//from ww w .j a va 2 s . c o m * This will be gzipped or non gzipped depending on whether the User Agent accepts * GZIP encoding. * <p/> * If the body is written gzipped a gzip header is added. * * @param response * @param pageInfo * @throws IOException */ protected void writeContent(final HttpServletRequest request, final HttpServletResponse response, final PageInfo pageInfo) throws IOException, ResponseHeadersNotModifiableException { byte[] body; if (acceptsGzipEncoding(request)) { ResponseUtil.addGzipHeader(response); body = pageInfo.getGzippedBody(); if (ResponseUtil.shouldGzippedBodyBeZero(body, request)) { body = new byte[0]; } } else { body = pageInfo.getUngzippedBody(); } boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, pageInfo.getStatusCode()); if (shouldBodyBeZero) { body = new byte[0]; } response.setContentLength(body.length); OutputStream out = new BufferedOutputStream(response.getOutputStream()); out.write(body); out.flush(); }
From source file:org.ala.spatial.web.services.DownloadController.java
@RequestMapping(value = "/session/{sessionid}", method = RequestMethod.GET) @ResponseBody//from www.ja v a 2 s .c o m public String downloadSessionUrl(@PathVariable String sessionid, HttpServletResponse response) { try { String basedir = AlaspatialProperties.getBaseOutputDir() + File.separator + "output" + File.separator; String sessiondir = basedir + "session" + File.separator + sessionid; File sDir = new File(sessiondir); if (sDir.exists() && sDir.isDirectory()) { StringBuffer sbSession = new StringBuffer(); sbSession.append("[InternetShortcut]").append("\n"); sbSession.append("URL=").append(AlaspatialProperties.getBaseOutputURL()); sbSession.append("?ss=").append(sessionid).append("\n"); response.setContentType("application/internet-shortcut"); response.setContentLength(safeLongToInt(sbSession.length())); response.setHeader("Content-Disposition", "attachment; filename=\"ALA_Spatial_Portal_Session_" + sessionid + ".url\""); FileCopyUtils.copy(sbSession.toString(), response.getWriter()); return null; } } catch (Exception e) { System.out.println("Could not find session directory"); } return ""; }
From source file:com.qcadoo.mes.cmmsMachineParts.controller.PlannedEventMultiUploadController.java
@RequestMapping(value = "/getAttachmentForPlannedEvent.html", method = RequestMethod.GET) public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) { DataDefinition attachmentDD = dataDefinitionService.get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER, CmmsMachinePartsConstants.MODEL_PLANNED_EVENT_ATTACHMENT); Entity attachment = attachmentDD.get(ids[0]); InputStream is = fileService//from w ww .j a v a 2 s . c om .getInputStream(attachment.getStringField(PlannedEventAttachmentFields.ATTACHMENT)); try { if (is == null) { response.sendRedirect("/error.html?code=404"); } response.setHeader("Content-disposition", "inline; filename=" + attachment.getStringField(PlannedEventAttachmentFields.NAME)); response.setContentType( fileService.getContentType(attachment.getStringField(PlannedEventAttachmentFields.ATTACHMENT))); int bytes = IOUtils.copy(is, response.getOutputStream()); response.setContentLength(bytes); response.flushBuffer(); } catch (IOException e) { logger.error("Unable to copy attachment file to response stream.", e); } }
From source file:com.googlecode.jsonplugin.JSONUtil.java
public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException { StringBuilder stringBuilder = new StringBuilder(); if (TextUtils.stringSet(serializationParams.getSerializedJSON())) stringBuilder.append(serializationParams.getSerializedJSON()); if (TextUtils.stringSet(serializationParams.getWrapPrefix())) stringBuilder.insert(0, serializationParams.getWrapPrefix()); else if (serializationParams.isWrapWithComments()) { stringBuilder.insert(0, "/* "); stringBuilder.append(" */"); } else if (serializationParams.isPrefix()) stringBuilder.insert(0, "{}&& "); if (TextUtils.stringSet(serializationParams.getWrapSuffix())) stringBuilder.append(serializationParams.getWrapSuffix()); String json = stringBuilder.toString(); if (log.isDebugEnabled()) { log.debug("[JSON]" + json); }//from w w w.jav a2s . c om HttpServletResponse response = serializationParams.getResponse(); //status or error code if (serializationParams.getStatusCode() > 0) response.setStatus(serializationParams.getStatusCode()); else if (serializationParams.getErrorCode() > 0) response.sendError(serializationParams.getErrorCode()); //content type if (serializationParams.isSmd()) response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding()); else response.setContentType( serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding()); if (serializationParams.isNoCache()) { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "0"); response.setHeader("Pragma", "No-cache"); } if (serializationParams.isGzip()) { response.addHeader("Content-Encoding", "gzip"); GZIPOutputStream out = null; InputStream in = null; try { out = new GZIPOutputStream(response.getOutputStream()); in = new ByteArrayInputStream(json.getBytes()); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if (in != null) in.close(); if (out != null) { out.finish(); out.close(); } } } else { response.setContentLength(json.getBytes(serializationParams.getEncoding()).length); PrintWriter out = response.getWriter(); out.print(json); } }
From source file:SendMp3.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendMp3 servlet."); if (fileName.indexOf(".mp3") == -1) fileName = fileName + ".mp3"; String mp3Dir = getServletContext().getInitParameter("mp3-dir"); if (mp3Dir == null || mp3Dir.equals("")) throw new ServletException("Invalid or non-existent mp3Dir context-param."); ServletOutputStream stream = null;/*ww w . j a v a 2 s . c o m*/ BufferedInputStream buf = null; try { stream = response.getOutputStream(); File mp3 = new File(mp3Dir + "/" + fileName); //set response headers response.setContentType("audio/mpeg"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) mp3.length()); FileInputStream input = new FileInputStream(mp3); buf = new BufferedInputStream(input); int readBytes = 0; //read from the file; write to the ServletOutputStream while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
From source file:arena.web.view.DownloadView.java
@Override @SuppressWarnings("unchecked") protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setStatus(HttpServletResponse.SC_OK); String mt = (mimeTypeParam != null ? (String) model.get(mimeTypeParam) : this.mimeType); if (mt != null) { response.setContentType(this.mimeType); }/*from w w w . j a va2 s . com*/ Object contentObj = model.get(this.contentParam); String fileName = ServletUtils.replaceWildcards(this.filenamePattern, this.allowRequestArgs, model, request); if (!fileName.equals("")) { String rfc2047Name = javax.mail.internet.MimeUtility.encodeText(fileName, "UTF-8", null); String fullHeader = "attachment;filename=" + rfc2047Name; response.setHeader("Content-Disposition", fullHeader); } ServletOutputStream out = response.getOutputStream(); if (contentObj instanceof byte[]) { byte[] content = (byte[]) model.get(this.contentParam); response.setContentLength(content == null ? 0 : content.length); if (content != null && content.length > 0) { out.write(content); } } else if (contentObj instanceof InputStream) { InputStream content = (InputStream) contentObj; byte[] buffer = new byte[response.getBufferSize()]; int read = 0; while ((read = content.read(buffer)) >= 0) { out.write(buffer, 0, read); } if (this.closeStream) { content.close(); } } }
From source file:io.fabric8.maven.impl.MavenProxyServletSupportTest.java
private void testDownload(Handler serverHandler) throws Exception { String old = System.getProperty("karaf.data"); System.setProperty("karaf.data", new File("target").getCanonicalPath()); FileUtils.deleteDirectory(new File("target/tmp")); Server server = new Server(0); server.setHandler(serverHandler);//from ww w . j a v a 2 s . c o m server.start(); try { int localPort = server.getConnectors()[0].getLocalPort(); List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central"); RuntimeProperties props = new MockRuntimeProperties(); MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(props, "target/tmp", remoteRepos, false, "always", "warn", "http", "localhost", localPort, "fuse", "fuse", null); HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(request.getPathInfo()) .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar"); HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() { @Override public void write(int b) throws IOException { baos.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { baos.write(b, off, len); } }).anyTimes(); response.setStatus(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentLength(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentType((String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong()); EasyMock.expectLastCall().anyTimes(); response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(request, response); servlet.start(); servlet.doGet(request, response); Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray()); EasyMock.verify(request, response); } finally { server.stop(); if (old != null) { System.setProperty("karaf.data", old); } } }
From source file:net.duckling.ddl.web.api.pan.APIPanDownloadController.java
@WebLog(method = "mobilePanPage", params = "pid,itemType") @RequestMapping/*from w w w. java 2s .c om*/ public void service(@RequestParam("pid") String rid, @RequestParam("itemType") String itemType, HttpServletRequest request, HttpServletResponse response) { String imageSize = request.getParameter("imageType"); rid = decode(rid); PanAcl acl = PanAclUtil.getInstance(request); MeePoMeta meta = null; try { meta = panService.ls(acl, rid, true); } catch (MeePoException e1) { LOG.error(e1.getMessage()); return; } OutputStream os = null; long[] re = getOffer(request, meta.size); long offset = re[0]; long size = re[1]; long p0 = System.currentTimeMillis(); long tmpSize = size; try { response.setCharacterEncoding("utf-8"); String headerValue = ResponseHeaderUtils.buildResponseHeader(request, meta.name, true); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", headerValue); response.setContentLength((int) size); response.setHeader("Content-Length", tmpSize + ""); os = response.getOutputStream(); //??? //if(FileType.IMAGE.equals(FileTypeHelper.getName(meta.name))){ // panService.thumbnails(acl, rid, convertPanImageType(imageSize), os); //}else{ panService.download(PanAclUtil.getInstance(request), rid, meta.version, os, offset, size); //} } catch (UnsupportedEncodingException e) { LOG.error("", e); } catch (MeePoException e) { LOG.error("", e); } catch (IOException e) { LOG.error("", e); } catch (Exception e) { LOG.error("", e); } finally { IOUtils.closeQuietly(os); long p1 = System.currentTimeMillis(); LOG.info("Download document[name:" + meta.name + ",size:" + tmpSize + "] use time " + (p1 - p0)); } }