List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:com.novartis.pcs.ontology.rest.servlet.SubtermsServlet.java
private void serialize(String referenceId, boolean pending, HttpServletResponse response) { try {/*from w w w . ja va 2 s . c o m*/ EnumSet<Status> statusSet = pending ? EnumSet.of(Status.PENDING, Status.APPROVED) : EnumSet.of(Status.APPROVED); Collection<Term> terms = termDAO.loadSubTermsByReferenceId(referenceId, statusSet); List<TermDTO> dtos = new ArrayList<TermDTO>(terms.size()); for (Term term : terms) { if (statusSet.contains(term.getStatus())) { dtos.add(new TermDTO(term)); } } if (!dtos.isEmpty()) { 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(), dtos); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); } } catch (Exception e) { log("Failed to serialize synonyms to JSON", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); } }
From source file:architecture.ee.web.spring.controller.DownloadController.java
@RequestMapping(value = "/files/{fileId:[\\p{Digit}]+}/{filename:.+}", method = { RequestMethod.GET, RequestMethod.POST })//from ww w. ja v a2 s. c o m @ResponseBody public void downloadFile(@PathVariable("fileId") Long fileId, @PathVariable("filename") String filename, @RequestParam(value = "thumbnail", defaultValue = "false", required = false) boolean thumbnail, @RequestParam(value = "width", defaultValue = "150", required = false) Integer width, @RequestParam(value = "height", defaultValue = "150", required = false) Integer height, HttpServletResponse response) throws IOException { try { if (fileId > 0 && StringUtils.isNotEmpty(filename)) { Attachment attachment = attachmentManager.getAttachment(fileId); if (StringUtils.equals(filename, attachment.getName())) { if (thumbnail) { if (StringUtils.startsWithIgnoreCase(attachment.getContentType(), "image") || StringUtils.endsWithIgnoreCase(attachment.getContentType(), "pdf")) { InputStream input = attachmentManager.getAttachmentImageThumbnailInputStream(attachment, width, height); response.setContentType(attachment.getThumbnailContentType()); response.setContentLength(attachment.getThumbnailSize()); IOUtils.copy(input, response.getOutputStream()); response.flushBuffer(); } } else { InputStream input = attachmentManager.getAttachmentInputStream(attachment); response.setContentType(attachment.getContentType()); response.setContentLength(attachment.getSize()); IOUtils.copy(input, response.getOutputStream()); response.setHeader("contentDisposition", "attachment;filename=" + getEncodedFileName(attachment)); response.flushBuffer(); } } else { throw new NotFoundException(); } } else { throw new NotFoundException(); } } catch (NotFoundException e) { response.sendError(404); } }
From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileDownloadServiceImpl.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user = (User) req.getSession().getAttribute(CoreConstants.SESSION_USER); String operationId = req.getParameter("operationid"); if (user != null && operationId != null && !operationId.isEmpty()) { try {/*from w ww. j a va 2 s .co m*/ GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient(); Operation operation = client.getOperationById(operationId); File file = new File(operation.getDest()); if (file.isDirectory()) { file = new File(operation.getDest() + "/" + FilenameUtils.getName(operation.getSource())); } int length = 0; ServletOutputStream op = resp.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType(file.getName()); logger.info("(" + user.getEmail() + ") Downloading '" + file.getAbsolutePath() + "'."); resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); resp.setContentLength((int) file.length()); resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); byte[] bbuf = new byte[4096]; DataInputStream in = new DataInputStream(new FileInputStream(file)); while ((in != null) && ((length = in.read(bbuf)) != -1)) { op.write(bbuf, 0, length); } in.close(); op.flush(); op.close(); } catch (GRIDAClientException ex) { logger.error(ex); } } }
From source file:gov.redhawk.rap.internal.PluginProviderServlet.java
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final Path path = new Path(req.getRequestURI()); String pluginId = path.lastSegment(); if (pluginId.endsWith(".jar")) { pluginId = pluginId.substring(0, pluginId.length() - 4); }//from ww w. j av a2 s . c o m final Bundle b = Platform.getBundle(pluginId); if (b == null) { final String protocol = req.getProtocol(); final String msg = "Plugin does not exist: " + pluginId; if (protocol.endsWith("1.1")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); } return; } final File file = FileLocator.getBundleFile(b); resp.setContentType("application/octet-stream"); if (file.isFile()) { final String contentDisposition = "attachment; filename=\"" + file.getName() + "\""; resp.setHeader("Content-Disposition", contentDisposition); resp.setContentLength((int) file.length()); final FileInputStream istream = new FileInputStream(file); try { IOUtils.copy(istream, resp.getOutputStream()); } finally { istream.close(); } resp.flushBuffer(); } else { final String contentDisposition = "attachment; filename=\"" + file.getName() + ".jar\""; resp.setHeader("Content-Disposition", contentDisposition); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Manifest man = new Manifest(new FileInputStream(new File(file, "META-INF/MANIFEST.MF"))); final JarOutputStream out = new JarOutputStream(outputStream, man); final File binDir = new File(file, "bin"); if (binDir.exists()) { addFiles(out, Path.ROOT, binDir.listFiles()); for (final File f : file.listFiles()) { if (!f.getName().equals("bin")) { addFiles(out, Path.ROOT, f); } } } else { addFiles(out, Path.ROOT, file.listFiles()); } out.close(); outputStream.close(); final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); resp.setContentLength(outputStream.size()); try { IOUtils.copy(inputStream, resp.getOutputStream()); } finally { inputStream.close(); } resp.flushBuffer(); } }
From source file:mx.edu.um.mateo.rh.web.SolicitudVacacionesEmpleadoController.java
private void generaReporte(String tipo, List<SolicitudVacacionesEmpleado> vacacioness, HttpServletResponse response) throws JRException, IOException { log.debug("Generando reporte {}", tipo); byte[] archivo = null; switch (tipo) { case "PDF": archivo = generaPdf(vacacioness); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.pdf"); break;// ww w. j av a 2s . c om case "CSV": archivo = generaCsv(vacacioness); response.setContentType("text/csv"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.csv"); break; case "XLS": archivo = generaXls(vacacioness); response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.xls"); } if (archivo != null) { response.setContentLength(archivo.length); try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) { bos.write(archivo); bos.flush(); } } }
From source file:com.jaspersoft.jasperserver.war.action.AbstractReportExporter.java
protected void exportBuffered(RequestContext context, HttpServletResponse response, JasperPrint jasperPrint, String reportUnitURI) throws IOException, JRException { Map parameters = new HashMap(); parameters.put(JRExporterParameter.JASPER_PRINT, jasperPrint); FileBufferedOutputStream bufferedOutput = new FileBufferedOutputStream(getMemoryThreshold(), getInitialMemoryBufferSize()); parameters.put(JRExporterParameter.OUTPUT_STREAM, bufferedOutput); try {/* w w w.j av a 2 s .c o m*/ export(context, getExecutionContext(context), reportUnitURI, parameters); bufferedOutput.close(); int exportSize = bufferedOutput.size(); if (log.isDebugEnabled()) { log.debug("exported to buffer of size " + exportSize); } response.setContentType(getContentType(context)); setAdditionalResponseHeaders(context, response); response.setContentLength(exportSize); ServletOutputStream ouputStream = response.getOutputStream(); try { bufferedOutput.writeData(ouputStream); bufferedOutput.dispose(); ouputStream.flush(); } finally { if (ouputStream != null) { try { ouputStream.close(); } catch (IOException ex) { log.warn("Error closing output stream", ex); } } } } finally { bufferedOutput.close(); bufferedOutput.dispose(); } }
From source file:io.soabase.admin.details.IndexServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestURI = ((request.getRequestURI() != null) && (request.getRequestURI().length() > 0)) ? request.getRequestURI()/*from w w w . jav a 2 s .c o m*/ : "/"; if (requestURI.startsWith(FORCE)) { rebuild(); requestURI = (requestURI.length() > FORCE.length()) ? requestURI.substring(FORCE.length()) : "/"; } else { int componentManagerVersion = componentManager.getVersion(); int localBuiltFromVersion = builtFromVersion.get(); if (localBuiltFromVersion != componentManagerVersion) { if (builtFromVersion.compareAndSet(localBuiltFromVersion, componentManagerVersion)) { rebuild(); } } } Entry entry = files.get().get(requestURI); if (entry == null) { response.setStatus(404); return; } response.setStatus(200); response.setContentType("text/html"); response.setContentLength(entry.content.length()); response.setCharacterEncoding("UTF-8"); response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified.get()); response.setHeader(HttpHeaders.ETAG, entry.eTag); response.getWriter().print(entry.content); }
From source file:com.webpagebytes.cms.controllers.FileController.java
public void downloadResource(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {// www .j a v a2 s .c o m Long key = Long.valueOf((String) request.getAttribute("key")); WPBFile wbfile = adminStorage.get(key, WPBFile.class); WPBFilePath cloudFile = new WPBFilePath(PUBLIC_BUCKET, wbfile.getBlobKey()); InputStream is = cloudFileStorage.getFileContent(cloudFile); response.setContentType(wbfile.getContentType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + wbfile.getFileName() + "\""); response.setContentLength(wbfile.getSize().intValue()); OutputStream os = response.getOutputStream(); IOUtils.copy(is, os); os.flush(); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:mx.edu.um.mateo.rh.web.CategoriaController.java
private void generaReporte(String tipo, List<Categoria> categorias, HttpServletResponse response) throws JRException, IOException { log.debug("Generando reporte {}", tipo); byte[] archivo = null; switch (tipo) { case "PDF": archivo = generaPdf(categorias); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=Categorias.pdf"); break;// ww w . j av a2 s . com case "CSV": archivo = generaCsv(categorias); response.setContentType("text/csv"); response.addHeader("Content-Disposition", "attachment; filename=Categorias.csv"); break; case "XLS": archivo = generaXls(categorias); response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment; filename=Categorias.xls"); } if (archivo != null) { response.setContentLength(archivo.length); try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) { bos.write(archivo); bos.flush(); } } }
From source file:com.zimbra.cs.dav.service.DavServlet.java
private CacheStates checkCachedResponse(DavContext ctxt, Account authUser) throws IOException, DavException, ServiceException { CacheStates cache = new CacheStates(); // Are we running with cache enabled, and is this a cachable CalDAV ctag request? if (cache.ctagCacheEnabled && isCtagRequest(ctxt)) { cache.ctagResponseCache = CalendarCacheManager.getInstance().getCtagResponseCache(); cache.gzipAccepted = ctxt.isGzipAccepted(); String targetUser = ctxt.getUser(); Account targetAcct = Provisioning.getInstance().get(AccountBy.name, targetUser); boolean ownAcct = targetAcct != null && targetAcct.getId().equals(authUser.getId()); String parentPath = ctxt.getPath(); KnownUserAgent knownUA = ctxt.getKnownUserAgent(); // Use cache only when requesting own account and User-Agent and path are well-defined. if (ownAcct && knownUA != null && parentPath != null) { AccountKey accountKey = new AccountKey(targetAcct.getId()); AccountCtags allCtagsData = CalendarCacheManager.getInstance().getCtags(accountKey); // We can't use cache if it doesn't have data for this user. if (allCtagsData != null) { boolean validRoot = true; int rootFolderId = Mailbox.ID_FOLDER_USER_ROOT; if (!"/".equals(parentPath)) { CtagInfo calInfoRoot = allCtagsData.getByPath(parentPath); if (calInfoRoot != null) rootFolderId = calInfoRoot.getId(); else validRoot = false; }/*from ww w . j av a 2s . com*/ if (validRoot) { // Is there a previously cached response? cache.ctagCacheKey = new CtagResponseCacheKey(targetAcct.getId(), knownUA.toString(), rootFolderId); CtagResponseCacheValue ctagResponse = cache.ctagResponseCache.get(cache.ctagCacheKey); if (ctagResponse != null) { // Found a cached response. Let's check if it's stale. // 1. If calendar list has been updated since, cached response is no good. String currentCalListVer = allCtagsData.getVersion(); if (currentCalListVer.equals(ctagResponse.getVersion())) { // 2. We have to examine ctags of individual calendars. boolean cacheHit = true; Map<Integer, String> oldCtags = ctagResponse.getCtags(); // We're good if ctags from before are unchanged. for (Map.Entry<Integer, String> entry : oldCtags.entrySet()) { int calFolderId = entry.getKey(); String ctag = entry.getValue(); CtagInfo calInfoCurr = allCtagsData.getById(calFolderId); if (calInfoCurr == null) { // Just a sanity check. The cal list version check should have // already taken care of added/removed calendars. cacheHit = false; break; } if (!ctag.equals(calInfoCurr.getCtag())) { // A calendar has been modified. Stale! cacheHit = false; break; } } if (cacheHit) { ZimbraLog.dav.debug("CTAG REQUEST CACHE HIT"); // All good. Send cached response. ctxt.setStatus(DavProtocol.STATUS_MULTI_STATUS); HttpServletResponse response = ctxt.getResponse(); response.setStatus(ctxt.getStatus()); response.setContentType(DavProtocol.DAV_CONTENT_TYPE); byte[] respData = ctagResponse.getResponseBody(); response.setContentLength(ctagResponse.getRawLength()); byte[] unzipped = null; if (ZimbraLog.dav.isDebugEnabled() || (ctagResponse.isGzipped() && !cache.gzipAccepted)) { if (ctagResponse.isGzipped()) { ByteArrayInputStream bais = new ByteArrayInputStream(respData); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPInputStream gzis = null; try { gzis = new GZIPInputStream(bais, respData.length); ByteUtil.copy(gzis, false, baos, true); } finally { ByteUtil.closeStream(gzis); } unzipped = baos.toByteArray(); } else { unzipped = respData; } if (ZimbraLog.dav.isDebugEnabled()) { ZimbraLog.dav.debug("RESPONSE:\n" + new String(unzipped, "UTF-8")); } } if (!ctagResponse.isGzipped()) { response.getOutputStream().write(respData); } else { if (cache.gzipAccepted) { response.addHeader(DavProtocol.HEADER_CONTENT_ENCODING, DavProtocol.ENCODING_GZIP); response.getOutputStream().write(respData); } else { assert (unzipped != null); response.getOutputStream().write(unzipped); } } // Tell the context the response has been sent. ctxt.responseSent(); } } } if (!ctxt.isResponseSent()) { // Cache miss, or cached response is stale. We're gonna have to generate the // response the hard way. Capture a snapshot of current state of calendars // to attach to the response to be cached later. cache.cacheThisCtagResponse = true; cache.acctVerSnapshot = allCtagsData.getVersion(); cache.ctagsSnapshot = new HashMap<Integer, String>(); Collection<CtagInfo> childCals = allCtagsData.getChildren(rootFolderId); if (rootFolderId != Mailbox.ID_FOLDER_USER_ROOT) { CtagInfo ctagRoot = allCtagsData.getById(rootFolderId); if (ctagRoot != null) cache.ctagsSnapshot.put(rootFolderId, ctagRoot.getCtag()); } for (CtagInfo calInfo : childCals) { cache.ctagsSnapshot.put(calInfo.getId(), calInfo.getCtag()); } } } } if (!ctxt.isResponseSent()) ZimbraLog.dav.debug("CTAG REQUEST CACHE MISS"); } } return cache; }