List of usage examples for javax.servlet.http HttpServletResponse setContentLengthLong
public void setContentLengthLong(long len);
From source file:org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter.java
private void addResponseHeaders() { RequestContext context = RequestContext.getCurrentContext(); HttpServletResponse servletResponse = context.getResponse(); if (INCLUDE_DEBUG_HEADER.get()) { @SuppressWarnings("unchecked") List<String> rd = (List<String>) context.get(ROUTING_DEBUG_KEY); if (rd != null) { StringBuilder debugHeader = new StringBuilder(); for (String it : rd) { debugHeader.append("[[[" + it + "]]]"); }/*from w w w. j a v a2 s. c om*/ servletResponse.addHeader(X_ZUUL_DEBUG_HEADER, debugHeader.toString()); } } List<Pair<String, String>> zuulResponseHeaders = context.getZuulResponseHeaders(); if (zuulResponseHeaders != null) { for (Pair<String, String> it : zuulResponseHeaders) { servletResponse.addHeader(it.first(), it.second()); } } // Only inserts Content-Length if origin provides it and origin response is not // gzipped if (SET_CONTENT_LENGTH.get()) { Long contentLength = context.getOriginContentLength(); if (contentLength != null && !context.getResponseGZipped()) { if (useServlet31) { servletResponse.setContentLengthLong(contentLength); } else { //Try and set some kind of content length if we can safely convert the Long to an int if (isLongSafe(contentLength)) { servletResponse.setContentLength(contentLength.intValue()); } } } } }
From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java
@RequestMapping(value = "/channel/{channelId}/viewCacheEntry", method = RequestMethod.GET) @HttpConstraint(rolesAllowed = { "MANAGER", "ADMIN" }) public ModelAndView viewCacheEntry(@PathVariable("channelId") final String channelId, @RequestParameter("namespace") final String namespace, @RequestParameter("key") final String key, final HttpServletResponse response) { final Map<String, Object> model = new HashMap<>(); final Channel channel = this.service.getChannel(channelId); if (channel == null) { return CommonController.createNotFound("channel", channelId); }/*from w w w . j a va2 s. c om*/ model.put("channel", channel); if (!channel.streamCacheEntry(new MetaKey(namespace, key), (cacheEntry) -> { response.setContentLengthLong(cacheEntry.getSize()); response.setContentType(cacheEntry.getMimeType()); response.setHeader("Content-Disposition", String.format("inline; filename=%s", URLEncoder.encode(cacheEntry.getName(), "UTF-8"))); // response.setHeader ( "Content-Disposition", String.format ( "attachment; filename=%s", info.getName () ) ); ByteStreams.copy(cacheEntry.getStream(), response.getOutputStream()); })) { return CommonController.createNotFound("channel cache entry", String.format("%s:%s", namespace, key)); } return null; }
From source file:org.eclipse.packagedrone.repo.channel.web.channel.ChannelController.java
@RequestMapping(value = "/channel/{channelId}/viewCacheEntry", method = RequestMethod.GET) @HttpConstraint(rolesAllowed = { "MANAGER", "ADMIN" }) public ModelAndView viewCacheEntry(@PathVariable("channelId") final String channelId, @RequestParameter("namespace") final String namespace, @RequestParameter("key") final String key, final HttpServletResponse response) { return withChannel(channelId, ReadableChannel.class, channel -> { if (!channel.streamCacheEntry(new MetaKey(namespace, key), entry -> { logger.trace("Length: {}, Mime: {}", entry.getSize(), entry.getMimeType()); response.setContentLengthLong(entry.getSize()); response.setContentType(entry.getMimeType()); response.setHeader("Content-Disposition", String.format("inline; filename=%s", URLEncoder.encode(entry.getName(), "UTF-8"))); // response.setHeader ( "Content-Disposition", String.format ( "attachment; filename=%s", entry.getName () ) ); ByteStreams.copy(entry.getStream(), response.getOutputStream()); })) {/* w w w. java2 s. co m*/ return CommonController.createNotFound("channel cache entry", String.format("%s:%s", namespace, key)); } return null; }); }
From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java
protected ModelAndView performExport(final HttpServletResponse response, final String filename, final IOConsumer<OutputStream> exporter) { try {/*ww w.jav a2s . c o m*/ final Path tmp = Files.createTempFile("export-", null); try { try (OutputStream tmpStream = new BufferedOutputStream(new FileOutputStream(tmp.toFile()))) { // first we spool this out to temp file, so that we don't block the channel for too long exporter.accept(tmpStream); } response.setContentLengthLong(tmp.toFile().length()); response.setContentType("application/zip"); response.setHeader("Content-Disposition", String.format("attachment; filename=%s", filename)); try (InputStream inStream = new BufferedInputStream(new FileInputStream(tmp.toFile()))) { ByteStreams.copy(inStream, response.getOutputStream()); } return null; } finally { Files.deleteIfExists(tmp); } } catch (final IOException e) { return CommonController.createError("Failed to export", null, e); } }
From source file:com.orange.clara.cloud.servicedbdumper.controllers.ManagerController.java
@RequestMapping(value = Routes.DOWNLOAD_DUMP_FILE_ROOT + "/{dumpFileId:[0-9]+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public @ResponseBody void download(@PathVariable Integer dumpFileId, HttpServletRequest request, HttpServletResponse resp, @RequestParam(value = "original", required = false) String original) throws IOException, DumpFileDeletedException { DatabaseDumpFile databaseDumpFile = getDatabaseDumpFile(dumpFileId); this.checkDbDumperServiceInstance(databaseDumpFile.getDbDumperServiceInstance()); this.checkDatabaseDumpFile(databaseDumpFile); String userRequest = ""; String passwordRequest = ""; String authorization = request.getHeader("Authorization"); if (authorization != null && authorization.startsWith("Basic")) { String base64Credentials = authorization.substring("Basic".length()).trim(); String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); String[] values = credentials.split(":", 2); userRequest = values[0];/*from w ww.j av a 2s . c om*/ passwordRequest = values[1]; } else { this.getErrorResponseEntityBasicAuth(resp); return; } if (!userRequest.equals(databaseDumpFile.getUser()) || !passwordRequest.equals(databaseDumpFile.getPassword())) { this.getErrorResponseEntityBasicAuth(resp); return; } String fileName = DumpFileHelper.getFilePath(databaseDumpFile); resp.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); resp.setContentLengthLong(this.filer.getContentLength(fileName)); InputStream inputStream = null; if (original == null || original.isEmpty()) { inputStream = filer.retrieveWithOriginalStream(fileName); } else { inputStream = filer.retrieveWithStream(fileName); File file = new File(fileName); String[] filenames = file.getName().split("\\."); if (filenames.length >= 2) { fileName = filenames[0] + "." + filenames[1]; } } inputStream = new BufferedInputStream(inputStream); File file = new File(fileName); resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); OutputStream outputStream = null; outputStream = resp.getOutputStream(); try { ByteStreams.copy(inputStream, outputStream); } finally { Closeables.closeQuietly(inputStream); outputStream.flush(); resp.flushBuffer(); Closeables.close(outputStream, true); } }
From source file:org.cirdles.webServices.calamari.CalamariServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww . ja v a2s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Integer accessCount; synchronized (session) { accessCount = (Integer) session.getAttribute("accessCount"); if (accessCount == null) { accessCount = 0; // autobox int to Integer } else { accessCount = accessCount + 1; } session.setAttribute("accessCount", accessCount); } response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=calamari-reports.zip"); boolean useSBM = ServletRequestUtils.getBooleanParameter(request, "useSBM", true); boolean useLinFits = ServletRequestUtils.getBooleanParameter(request, "userLinFits", false); String firstLetterRM = ServletRequestUtils.getStringParameter(request, "firstLetterRM", "T"); Part filePart = request.getPart("prawnFile"); String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); InputStream fileStream = filePart.getInputStream(); File myFile = new File(fileName); PrawnFileHandlerService handler = new PrawnFileHandlerService(); String fileExt = FilenameUtils.getExtension(fileName); try { File report = null; if (fileExt.equals("zip")) { report = handler.generateReportsZip(fileName, fileStream, useSBM, useLinFits, firstLetterRM) .toFile(); } else if (fileExt.equals("xml")) { report = handler.generateReports(fileName, fileStream, useSBM, useLinFits, firstLetterRM).toFile(); } response.setContentLengthLong(report.length()); IOUtils.copy(new FileInputStream(report), response.getOutputStream()); } catch (Exception e) { System.err.println(e); } }
From source file:uk.co.everywheremusic.model.RestApi.java
/** * * @param request/*from w w w.ja v a2 s . c o m*/ * @param response * @throws ServletException * @throws IOException */ public void handleSongRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = ""; boolean auth = false; if (queryString != null) { String[] args = queryString.split(Pattern.quote("&")); if (args != null && args.length == 2) { String[] keyValueOne = args[0].split(Pattern.quote("=")); if (keyValueOne != null && keyValueOne.length == 2) { if (keyValueOne[0].equals("path")) { path = keyValueOne[1]; } } String[] keyValueTwo = args[1].split(Pattern.quote("=")); if (keyValueTwo != null && keyValueTwo.length == 2) { if (keyValueTwo[0].equals("auth")) { DBManager dbm = new DBManager(installFolder); PasswordDAO pdao = dbm.getPasswordDAO(); auth = pdao.authenticatePassword(keyValueTwo[1]); } } } } if (auth) { // check if valid song DBManager dbm = new DBManager(installFolder); SongDAO sdao = dbm.getSongDAO(); SongBean song = sdao.getSongFromPath(path); if (song != null) { File file = new File(path); String mime = Files.probeContentType(Paths.get(file.getAbsolutePath())); response.setStatus(HttpServletResponse.SC_OK); response.setContentType(mime); response.setHeader("Content-Disposition", "filename=\"" + file.getName() + "\""); response.setContentLengthLong(file.length()); FileUtils.copyFile(file, response.getOutputStream()); } else { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("<h1>Error 400: Bad request</h1><br />Invalid song"); } } else { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().println("<h1>Error 401: Forbidden</h1>"); } }
From source file:com.qwazr.webapps.example.DocumentationServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String path = request.getPathInfo().substring(remotePrefix.length()); File file = new File(documentationPath, path); if (!file.exists()) { response.sendError(404, "File not found: " + file); return;//from ww w . ja v a 2s . c o m } if (file.isDirectory()) { if (!path.endsWith("/")) { response.sendRedirect(request.getPathInfo() + '/'); return; } for (String indexFileName : indexFileNames) { File readMefile = new File(file, indexFileName); if (readMefile.exists()) { file = readMefile; break; } } } Pair<String, String[]> paths = getRemoteLink(path); request.setAttribute("original_link", paths.getLeft()); request.setAttribute("breadcrumb_parts", paths.getRight()); if (!file.exists()) { response.sendError(404, "File not found: " + file); return; } request.setAttribute("currentfile", file); final String extension = FilenameUtils.getExtension(file.getName()); final List<File> fileList = getBuildList(file.getParentFile()); if ("md".equals(extension)) { request.setAttribute("markdown", markdownTool.toHtml(file)); request.setAttribute("filelist", fileList); } else if ("adoc".equals(extension)) { request.setAttribute("adoc", asciiDoctorTool.convertFile(file)); request.setAttribute("filelist", fileList); } else if (file.isFile()) { String type = mimeTypeMap.getContentType(file); if (type != null) response.setContentType(type); response.setContentLengthLong(file.length()); response.setDateHeader("Last-Modified", file.lastModified()); response.setHeader("Cache-Control", "max-age=86400"); response.setDateHeader("Expires", System.currentTimeMillis() + 86400 * 1000); InputStream inputStream = new FileInputStream(file); try { IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } return; } else if (file.isDirectory()) { request.setAttribute("filelist", getBuildList(file)); } else { response.sendRedirect(paths.getLeft()); } try { freemarkerTool.template(templatePath, request, response); } catch (TemplateException e) { throw new ServletException(e); } }
From source file:com.formkiq.core.api.FolderFilesController.java
/** * Gets a File./* ww w . j a v a2 s . co m*/ * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} * @param folder {@link String} * @param uuid {@link String} * @param resetuuid {@link String} * @throws IOException IOException */ @Transactional @RequestMapping(value = API_FOLDER_FILE + "/{folder}/{uuid}", method = GET) public void get(final HttpServletRequest request, final HttpServletResponse response, @PathVariable(name = "folder", required = true) final String folder, @PathVariable(name = "uuid", required = true) final String uuid, @RequestParam(value = "resetuuid", required = false) final boolean resetuuid) throws IOException { ArchiveDTO archiveDTO = null; String contentType = "application/zip"; String accept = request.getHeader("Accept"); String uri = request.getRequestURI(); Pair<byte[], String> p = this.folderService.findFormData(folder, uuid); String sha1hash = p.getRight(); byte[] data = p.getLeft(); if (resetuuid) { archiveDTO = this.archiveService.extractJSONFromZipFile(data); this.archiveService.resetUUID(archiveDTO); data = this.archiveService.createZipFile(archiveDTO); sha1hash = ""; } if (hasText(accept) && accept.contains("+json")) { archiveDTO = archiveDTO != null ? archiveDTO : this.archiveService.extractJSONFromZipFile(data); data = this.jsonService.writeValueAsBytes(archiveDTO); contentType = "application/json"; } if (hasText(accept) && (accept.contains("+pdf") || uri.endsWith(".pdf"))) { contentType = "application/pdf"; archiveDTO = archiveDTO != null ? archiveDTO : this.archiveService.extractJSONFromZipFile(data); if (archiveDTO.getPDF().isEmpty()) { this.folderService.createWorkflowOutput(archiveDTO); } if (archiveDTO.getPDF().isEmpty()) { throw new PreconditionFailedException("No PDF Found"); } data = archiveDTO.getPDF().values().iterator().next(); } response.addHeader("sha1hash", sha1hash); response.setContentType(contentType); response.setContentLengthLong(data.length); IOUtils.write(data, response.getOutputStream()); }