List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.ppcxy.cyfm.showcase.demos.web.RemoteContentServlet.java
private void fetchContentByApacheHttpClient(HttpServletResponse response, String contentUrl) throws IOException { // ?//from ww w . j a va2 s. c om HttpGet httpGet = new HttpGet(contentUrl); CloseableHttpResponse remoteResponse = httpClient.execute(httpGet); try { // int statusCode = remoteResponse.getStatusLine().getStatusCode(); if (statusCode >= 400) { response.sendError(statusCode, "fetch image error from " + contentUrl); return; } HttpEntity entity = remoteResponse.getEntity(); // Header response.setContentType(entity.getContentType().getValue()); if (entity.getContentLength() > 0) { response.setContentLength((int) entity.getContentLength()); } // InputStream input = entity.getContent(); OutputStream output = response.getOutputStream(); // byte?InputStreamOutputStream, ?4k. IOUtils.copy(input, output); output.flush(); } finally { remoteResponse.close(); } }
From source file:com.arcadian.loginservlet.LecturesServlet.java
/** * Handles the HTTP//from w w w . j a v a 2 s . c om * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("filename") != null) { String fileName = request.getParameter("filename"); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName); System.out.println("File location on server::" + file.getAbsolutePath()); ServletContext ctx = getServletContext(); InputStream fis = new FileInputStream(file); String mimeType = ctx.getMimeType(file.getAbsolutePath()); System.out.println("mime type=" + mimeType); response.setContentType(mimeType != null ? mimeType : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); ServletOutputStream os = response.getOutputStream(); byte[] bufferData = new byte[102400]; int read = 0; while ((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); } os.flush(); os.close(); fis.close(); System.out.println("File downloaded at client successfully"); } processRequest(request, response); }
From source file:com.novartis.pcs.ontology.rest.servlet.TermsServlet.java
private void serialize(String referenceId, HttpServletResponse response) { try {// w ww.j a va 2 s .c o m Term term = termDAO.loadByReferenceId(referenceId, true); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType(MEDIA_TYPE_JSON + ";charset=utf-8"); response.setHeader("Cache-Control", "public, max-age=0"); // As per jackson javadocs - Encoding will be UTF-8 mapper.writeValue(response.getOutputStream(), term); } catch (EntityNotFoundException e) { log("Failed to find term with reference id: " + referenceId, e); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); } catch (Exception e) { log("Failed to serialize term to JSON", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); } }
From source file:ch.entwine.weblounge.common.impl.request.Http11ProtocolHandler.java
/** * Method generateHeaders.// w w w . j av a 2 s . c o m * * @param resp * @param type */ public static void generateHeaders(HttpServletResponse resp, Http11ResponseType type) { /* generate headers only once! */ if (type.headers) return; type.headers = true; /* adjust the statistics */ ++stats[STATS_HEADER_GENERATED]; incResponseStats(type.type, headerStats); /* set the date header */ resp.setDateHeader(HEADER_DATE, type.time); /* check expires */ if (type.expires > type.time + MS_PER_YEAR) { type.expires = type.time + MS_PER_YEAR; log.warn("Expiration date too far in the future. Adjusting."); } /* set the standard headers and status code */ switch (type.type) { case RESPONSE_PARTIAL_CONTENT: if (type.expires > type.time) resp.setDateHeader(HEADER_EXPIRES, type.expires); if (type.modified > 0) { resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified)); resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified); } if (type.size < 0 || type.from < 0 || type.to < 0 || type.from > type.to || type.to > type.size) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); break; } resp.setContentLength((int) type.size); resp.setHeader(HEADER_CONTENT_RANGE, "bytes " + type.from + "-" + type.to + "/" + type.size); resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); break; case RESPONSE_OK: if (type.expires > type.time) { resp.setDateHeader(HEADER_EXPIRES, type.expires); } else if (type.expires == 0) { resp.setHeader(HEADER_CACHE_CONTROL, "no-cache"); resp.setHeader(HEADER_PRAGMA, "no-cache"); resp.setDateHeader(HEADER_EXPIRES, 0); } if (type.modified > 0) { resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified)); resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified); } if (type.size >= 0) resp.setContentLength((int) type.size); resp.setStatus(HttpServletResponse.SC_OK); break; case RESPONSE_NOT_MODIFIED: if (type.expires > type.time) resp.setDateHeader(HEADER_EXPIRES, type.expires); if (type.modified > 0) resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified)); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); break; case RESPONSE_METHOD_NOT_ALLOWED: resp.setHeader(HEADER_ALLOW, "GET, POST, HEAD"); resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); break; case RESPONSE_PRECONDITION_FAILED: if (type.expires > type.time) resp.setDateHeader(HEADER_EXPIRES, type.expires); if (type.modified > 0) { resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified)); resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified); } resp.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); break; case RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE: if (type.expires > type.time) resp.setDateHeader(HEADER_EXPIRES, type.expires); if (type.modified > 0) { resp.setHeader(HEADER_ETAG, Http11Utils.calcETag(type.modified)); resp.setDateHeader(HEADER_LAST_MODIFIED, type.modified); } if (type.size >= 0) resp.setHeader(HEADER_CONTENT_RANGE, "*/" + type.size); break; case RESPONSE_INTERNAL_SERVER_ERROR: default: resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:com.googlesource.gerrit.plugins.github.velocity.VelocityStaticServlet.java
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final Resource p = local(req); if (p == null) { CacheHeaders.setNotCacheable(rsp); rsp.setStatus(HttpServletResponse.SC_NOT_FOUND); return;/*from www .j a v a2 s. c om*/ } final String type = contentType(p.getName()); final byte[] tosend; if (!type.equals("application/x-javascript") && RPCServletUtils.acceptsGzipEncoding(req)) { rsp.setHeader("Content-Encoding", "gzip"); tosend = compress(readResource(p)); } else { tosend = readResource(p); } CacheHeaders.setCacheable(req, rsp, 12, TimeUnit.HOURS); rsp.setDateHeader("Last-Modified", p.getLastModified()); rsp.setContentType(type); rsp.setContentLength(tosend.length); final OutputStream out = rsp.getOutputStream(); try { out.write(tosend); } finally { out.close(); } }
From source file:fr.ortolang.diffusion.api.format.MetadataFormatResource.java
@GET @Path("/download") public void download(final @QueryParam(value = "id") String id, final @QueryParam(value = "name") String name, @Context HttpServletResponse response) throws OrtolangException, CoreServiceException, DataNotFoundException, IOException, BinaryStoreServiceException { LOGGER.log(Level.INFO, "GET /metadataformats/download"); MetadataFormat format;/*w w w . j a va 2 s.co m*/ if (id != null && id.length() > 0) { format = core.findMetadataFormatById(id); } else if (name != null && name.length() > 0) { format = core.getMetadataFormat(name); } else { throw new DataNotFoundException("either id or name must be provided in order to find metadata format"); } if (format != null) { response.setHeader("Content-Disposition", "attachment; filename=" + format.getName()); response.setContentType(format.getMimeType()); response.setContentLength((int) format.getSize()); InputStream input = store.get(format.getSchema()); try { IOUtils.copy(input, response.getOutputStream()); } finally { IOUtils.closeQuietly(input); } } else { throw new DataNotFoundException("unable to find a metadata format for this name or this id"); } }
From source file:de.ifgi.mosia.wpswfs.handler.ProxyRequestHandler.java
protected void writeResponse(String filteredContent, String enc, Header contentType, int statusCode, HttpServletResponse resp) throws IOException { if (enc == null) { enc = "UTF-8"; }//from www.j a v a2 s. co m byte[] bytes; if (statusCode == HttpStatus.SC_NO_CONTENT) { bytes = new byte[0]; } else if (filteredContent == null) { /* * recursive call end exit */ writeResponse(new ExceptionReportWrapper(new IOException("Proxy server issue")).toXML(), "UTF-8", new BasicHeader("Content-Type", "application/xml"), HttpStatus.SC_INTERNAL_SERVER_ERROR, resp); return; } else { bytes = filteredContent.getBytes(enc); } resp.setContentType(contentType == null ? "application/xml" : contentType.getValue()); resp.setCharacterEncoding(enc); resp.setContentLength(bytes.length); resp.setStatus(statusCode); resp.getOutputStream().write(bytes); resp.getOutputStream().flush(); }
From source file:com.qcadoo.report.internal.controller.ReportController.java
@RequestMapping(value = "generateSavedReport/{plugin}/{model}", method = RequestMethod.GET) public void generateSavedReport(@PathVariable("plugin") final String plugin, @PathVariable("model") final String model, @RequestParam("id") final String id, @RequestParam(value = "reportNo", required = false, defaultValue = "0") final String reportNo, final HttpServletRequest request, final HttpServletResponse response) throws ReportException { ReportService.ReportType reportType = getReportType(request); Entity entity = dataDefinitionService.get(plugin, model).get(Long.parseLong(id)); String filename = entity.getStringField("fileName").split(",")[Integer.valueOf(reportNo)]; String translatedFileName = filename.substring(filename.lastIndexOf(File.separator) + 1) + "." + reportType.getExtension(); response.setHeader("Content-disposition", "inline; filename=" + translatedFileName); response.setContentType(reportType.getMimeType()); try {/*from w w w . jav a 2 s. c o m*/ int bytes = copy(new FileInputStream(new File(filename + "." + reportType.getExtension())), response.getOutputStream()); response.setContentLength(bytes); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } }
From source file:org.xmlactions.web.conceal.HttpPager.java
private String serviceJasperPdfRequest(HttpServletResponse response, byte[] pdfImage, String outputPdfFileName) { InputStream inputStream = null; OutputStream responseOutputStream = null; try {/*from w w w . jav a2s. com*/ response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + outputPdfFileName); response.setContentLength(pdfImage.length); inputStream = new ByteArrayInputStream(pdfImage); responseOutputStream = response.getOutputStream(); int bytes; while ((bytes = inputStream.read()) != -1) { responseOutputStream.write(bytes); } } catch (Exception ex) { return ("EX:" + ex.getMessage()); } finally { IOUtils.closeQuietly(inputStream); // IOUtils.closeQuietly(responseOutputStream); } return null; }
From source file:architecture.ee.web.spring.controller.SecureDownloadController.java
@RequestMapping(value = "/logo/{logoId}", method = RequestMethod.GET) @ResponseBody//from w ww .j a va 2s . c o m public void handleLogo(@PathVariable("logoId") Long logoId, @RequestParam(value = "width", defaultValue = "0", required = false) Integer width, @RequestParam(value = "height", defaultValue = "0", required = false) Integer height, HttpServletResponse response) throws IOException { try { LogoImage image = logoManager.getLogoImageById(logoId); if (image != null) { InputStream input; String contentType; int contentLength; if (width > 0 && width > 0) { input = logoManager.getImageThumbnailInputStream(image, width, height); contentType = image.getThumbnailContentType(); contentLength = image.getThumbnailSize(); } else { input = logoManager.getImageInputStream(image); contentType = image.getImageContentType(); contentLength = image.getImageSize(); } response.setContentType(contentType); response.setContentLength(contentLength); IOUtils.copy(input, response.getOutputStream()); response.flushBuffer(); } } catch (Exception e) { log.warn(e); response.setStatus(301); String url = ApplicationHelper.getApplicationProperty("components.download.images.no-logo-url", "/images/common/what-to-know-before-getting-logo-design.png"); response.addHeader("Location", url); } }