List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.kolich.spring.views.mappers.KolichMappingPNGView.java
@Override public void myRenderMergedOutputModel(final KolichViewSerializable payload, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final ServletOutputStream os = response.getOutputStream(); // Be sure to set the Content-Length header on a MP3 audio file // response to the client (some MP3 players don't like chunked // transfer encoding so this fixes that). final byte[] bytes = payload.getEntity().getBytes(); response.setContentLength(bytes.length); os.write(bytes);/*from w ww.j ava 2 s. c o m*/ // Quietly close the output stream. IOUtils.closeQuietly(os); }
From source file:com.orange.mmp.mvc.bundle.Controller.java
@SuppressWarnings("unchecked") @Override/*from w ww . j a va 2 s. c o m*/ protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { int pathInfoStart = request.getRequestURI().indexOf(urlMapping); if (pathInfoStart < 0) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); return null; } // Get user agent to obtain branchID String userAgent = request.getHeader(Constants.HTTP_HEADER_USERAGENT); Mobile mobile = new Mobile(); mobile.setUserAgent(userAgent); Mobile[] mobiles = (Mobile[]) DaoManagerFactory.getInstance().getDaoManager().getDao("mobile").find(mobile); String branchId = null;//Constants.DEFAULT_BRANCH_ID; if (mobiles != null && mobiles.length > 0) { branchId = mobiles[0].getBranchId(); } else { Branch branch = new Branch(); branch.setDefault(true); Branch[] branches = (Branch[]) DaoManagerFactory.getInstance().getDaoManager().getDao("branch") .find(branch); if (branches != null && branches.length > 0) branchId = branches[0].getId(); } String pathInfo = request.getRequestURI().substring(pathInfoStart + urlMapping.length()); String requestParts[] = pathInfo.split("/"); String widgetId = null; String resourceName = null; InputStream input = null; if (requestParts.length > 2) { widgetId = requestParts[1]; resourceName = pathInfo.substring(widgetId.length() + 2); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); return null; } input = WidgetManager.getInstance().getWidgetResource(resourceName, widgetId, branchId); if (input == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); } else { ByteArrayOutputStream resourceBuffer = new ByteArrayOutputStream(); OutputStream output = response.getOutputStream(); try { IOUtils.copy(input, resourceBuffer); response.setContentLength(resourceBuffer.size()); resourceBuffer.writeTo(output); } catch (IOException ioe) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); } finally { if (input != null) input.close(); if (output != null) output.close(); if (resourceBuffer != null) resourceBuffer.close(); } } return null; }
From source file:com.sunflower.petal.controller.ImageController.java
@RequestMapping(value = "/thumbnail/{id}", method = RequestMethod.GET) public void thumbnail(HttpServletResponse response, @PathVariable Long id) { Image image = imageService.get(id); File imageFile = new File(fileUploadDirectory + "/" + image.getThumbnailFilename()); response.setContentType(image.getContentType()); response.setContentLength(image.getSize().intValue()); try {//from w w w. j av a2 s . c o m InputStream is = new FileInputStream(imageFile); IOUtils.copy(is, response.getOutputStream()); } catch (IOException e) { log.error("Could not show thumbnail " + id, e); } }
From source file:au.edu.uq.cmm.paul.servlet.FileView.java
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws IOException { File file = (File) model.get("file"); String contentType = (String) model.get("contentType"); try (FileInputStream fis = new FileInputStream(file)) { response.setContentType(contentType); long length = file.length(); if (length <= Integer.MAX_VALUE) { response.setContentLength((int) length); }/*w w w. j a v a 2 s.com*/ response.setStatus(HttpServletResponse.SC_OK); try (OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[8192]; int nosRead; while ((nosRead = fis.read(buffer)) > 0) { os.write(buffer, 0, nosRead); } } } catch (FileNotFoundException ex) { LOG.info("Cannot access file: " + ex.getLocalizedMessage()); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.sshdemo.common.report.manage.web.ParameterSetAction.java
private void buildText() { PrintWriter pw = null;/*from www.j ava2 s. co m*/ InputStream in = null; try { TextReport report = reportFac.findTextReportById(reportId); HttpServletResponse response = ServletActionContext.getResponse(); HttpServletRequest request = ServletActionContext.getRequest(); pw = response.getWriter(); response.reset();// response.setContentLength(0); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); byte[] bytes = textFactory.export(paraMap, report, fileFormat, response, request); in = new ByteArrayInputStream(bytes); int len = 0; while ((len = in.read()) > -1) { pw.write(len); } pw.flush(); } catch (Exception e) { // log.error(e.toString()); } finally { if (pw != null) { try { pw.close(); pw = null; } catch (Exception e) { } } if (in != null) { try { in.close(); in = null; } catch (Exception e) { } } } }
From source file:de.betterform.agent.web.WebUtil.java
/** * transforms an input document and writes it to the ServletOutputStream. * * @param context the servlet context/*from w w w. jav a 2 s . com*/ * @param response the servlet response * @param input an DOM input document to transform * @param stylesheetName the name of the stylesheet to use. This must be preloaded in CachingTransformerService. See WebFactory * @param params transformation parameters as a piece of DOM if any. The params object is passed as param 'params' to the stylesheets * @throws java.io.IOException */ public static void doTransform(ServletContext context, HttpServletResponse response, Document input, String stylesheetName, Object params) throws IOException { CachingTransformerService transformerService = (CachingTransformerService) context .getAttribute(TransformerService.TRANSFORMER_SERVICE); Source xmlSource = new DOMSource(input); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { Transformer transformer = transformerService.getTransformerByName(stylesheetName); if (params != null) { if (params instanceof Node) { transformer.setParameter("params", params); } } transformer.transform(xmlSource, new StreamResult(outputStream)); } catch (TransformerException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } response.setContentType(WebUtil.HTML_CONTENT_TYPE); response.setContentLength(outputStream.toByteArray().length); response.getOutputStream().write(outputStream.toByteArray()); response.getOutputStream().close(); }
From source file:bixo.fetcher.RedirectResponseHandler.java
@Override public void handle(String pathInContext, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws HttpException, IOException { if (pathInContext.equalsIgnoreCase(_originalPath)) { response.sendRedirect(_redirectUrl); } else if (_redirectUrl.contains(pathInContext)) { response.setStatus(HttpStatus.SC_OK); response.setContentType("text/plain"); String content = "redirected content"; response.setContentLength(content.length()); response.getOutputStream().write(content.getBytes()); } else {//from w ww. j a v a2 s. com response.setStatus(HttpStatus.SC_OK); response.setContentType("text/plain"); String content = "other content"; response.setContentLength(content.length()); response.getOutputStream().write(content.getBytes()); } }
From source file:net.duckling.ddl.web.controller.pan.WopiController.java
public void sendPreviewDoc(String skey, HttpServletRequest request, HttpServletResponse response) { OutputStream os = null;/*from www . ja v a 2 s.co m*/ long p0 = System.currentTimeMillis(); try { FileInfo info = (FileInfo) cacheService.get(skey); response.setCharacterEncoding("utf-8"); response.setContentLength((int) info.getSize()); response.setContentType("application/x-download"); String headerValue = ResponseHeaderUtils.buildResponseHeader(request, info.getFileName(), true); response.setHeader("Content-Disposition", headerValue); response.setHeader("Content-Length", info.getSize() + ""); os = response.getOutputStream(); if (StringUtils.isEmpty(info.getPanAcl().getUmtToken())) { //pan??? panService.getShareContent(info.getRemotePath(), null, os); } else { panService.download(info.getPanAcl(), info.getRemotePath(), info.getVersion(), os); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MeePoException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(os); long p1 = System.currentTimeMillis(); System.out.println("Send document use time " + (p1 - p0)); } }
From source file:org.primeframework.mvc.action.result.JSONResultTest.java
@Test(dataProvider = "httpMethod") public void errors(HTTPMethod httpMethod) throws IOException, ServletException { Post action = new Post(); ExpressionEvaluator ee = createStrictMock(ExpressionEvaluator.class); replay(ee);//from www. ja v a 2 s. c om MockServletOutputStream sos = new MockServletOutputStream(); HttpServletResponse response = createStrictMock(HttpServletResponse.class); response.setStatus(400); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.setContentLength(359); if (httpMethod == HTTPMethod.GET) { expect(response.getOutputStream()).andReturn(sos); } replay(response); Map<Class<?>, Object> additionalConfiguration = new HashMap<>(); additionalConfiguration.put(JacksonActionConfiguration.class, new JacksonActionConfiguration(null, null, "user")); ActionConfiguration config = new ActionConfiguration(Post.class, null, null, null, null, null, null, null, null, null, null, null, null, additionalConfiguration, null); ActionInvocationStore store = createStrictMock(ActionInvocationStore.class); expect(store.getCurrent()).andReturn(new ActionInvocation(action, new ExecuteMethodConfiguration(httpMethod, null, null), "/foo", "", config)); replay(store); MessageStore messageStore = createStrictMock(MessageStore.class); expect(messageStore.get(MessageScope.REQUEST)).andReturn(asList( new SimpleMessage(MessageType.ERROR, "[invalid]", "Invalid request"), new SimpleMessage(MessageType.ERROR, "[bad]", "Bad request"), new SimpleFieldMessage(MessageType.ERROR, "user.age", "[required]user.age", "Age is required"), new SimpleFieldMessage(MessageType.ERROR, "user.age", "[number]user.age", "Age must be a number"), new SimpleFieldMessage(MessageType.ERROR, "user.favoriteMonth", "[required]user.favoriteMonth", "Favorite month is required"))); replay(messageStore); JSON annotation = new JSONResultTest.JSONImpl("input", 400); JSONResult result = new JSONResult(ee, store, messageStore, objectMapper, response); result.execute(annotation); String expected = "{" + " \"fieldErrors\":{" + " \"user.age\":[{\"code\":\"[required]user.age\",\"message\":\"Age is required\"},{\"code\":\"[number]user.age\",\"message\":\"Age must be a number\"}]," + " \"user.favoriteMonth\":[{\"code\":\"[required]user.favoriteMonth\",\"message\":\"Favorite month is required\"}]" + " }," + " \"generalErrors\":[" + " {\"code\":\"[invalid]\",\"message\":\"Invalid request\"},{\"code\":\"[bad]\",\"message\":\"Bad request\"}" + " ]" + "}"; assertEquals(sos.toString(), httpMethod == HTTPMethod.GET ? expected.replace(" ", "") : ""); // Un-indent verify(ee, messageStore, response); }
From source file:com.google.code.jcaptcha4struts2.core.actions.support.CaptchaImageResult.java
/** * Action Execution Result. This will write the image bytes to response stream. * /*from ww w .j av a2s. com*/ * @param invocation * ActionInvocation * @throws IOException * if an IOException occurs while writing the image to output stream. * @throws IllegalArgumentException * if the action invocation was done by an action which is not the * {@link JCaptchaImageAction}. */ public void execute(ActionInvocation invocation) throws IOException, IllegalArgumentException { // Check if the invoked action was JCaptchaImageAction if (!(invocation.getAction() instanceof JCaptchaImageAction)) { throw new IllegalArgumentException( "CaptchaImageResult expects JCaptchaImageAction as Action Invocation"); } JCaptchaImageAction action = (JCaptchaImageAction) invocation.getAction(); HttpServletResponse response = ServletActionContext.getResponse(); // Read captcha image bytes byte[] image = action.getCaptchaImage(); // Send response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); response.setContentLength(image.length); try { response.getOutputStream().write(image); response.getOutputStream().flush(); } catch (IOException e) { LOG.error("IOException while writing image response for action : " + e.getMessage(), e); throw e; } }