List of usage examples for javax.servlet.http HttpServletResponse setDateHeader
public void setDateHeader(String name, long date);
From source file:org.auraframework.impl.adapter.ServletUtilAdapterImpl.java
/** * Sets cache timeout to a given value.//from w ww . ja v a 2s. c o m * * This sets several headers to try to ensure that the page will be cached for the given length of time. Of note is * the last-modified header, which is set to a day ago so that browsers consider it to be safe. * * @param response the HTTP response to which we will add headers. * @param expiration timeout value in milliseconds. */ @Override public void setCacheTimeout(HttpServletResponse response, long expiration) { long now = System.currentTimeMillis(); response.setHeader(HttpHeaders.VARY, "Accept-Encoding"); response.setHeader(HttpHeaders.CACHE_CONTROL, String.format("max-age=%s, public", expiration / 1000)); response.setDateHeader(HttpHeaders.EXPIRES, now + expiration); response.setDateHeader(HttpHeaders.LAST_MODIFIED, now - SHORT_EXPIRE); }
From source file:com.haulmont.cuba.core.controllers.LogDownloadController.java
@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET) public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId, @RequestParam(value = "full", required = false) Boolean downloadFull, @PathVariable(value = "file") String logFileName) throws IOException { UserSession userSession = getSession(sessionId, response); if (userSession == null) return;/*w ww. j a v a2 s . co m*/ if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // security check, handle only valid file name String filename = FilenameUtils.getName(logFileName); try { File logFile = logControl.getLogFile(filename); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Content-Type", "application/zip"); response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Disposition", "attachment; filename=" + filename); OutputStream outputStream = null; try { outputStream = response.getOutputStream(); if (BooleanUtils.isTrue(downloadFull)) { LogArchiver.writeArchivedLogToStream(logFile, outputStream); } else { LogArchiver.writeArchivedLogTailToStream(logFile, outputStream); } } catch (RuntimeException | IOException ex) { log.error("Unable to download file", ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(outputStream); } } catch (LogFileNotFoundException e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.haulmont.cuba.web.controllers.LogDownloadController.java
@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET) public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId, @RequestParam(value = "full", required = false) Boolean downloadFull, @PathVariable(value = "file") String logFileName) throws IOException { UserSession userSession = getSession(sessionId, response); if (userSession == null) return;// ww w . j a va2 s .com if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // security check, handle only valid file name String filename = FilenameUtils.getName(logFileName); try { File logFile = logControl.getLogFile(filename); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Content-Type", "application/zip"); response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".zip"); OutputStream outputStream = null; try { outputStream = response.getOutputStream(); if (BooleanUtils.isTrue(downloadFull)) { LogArchiver.writeArchivedLogToStream(logFile, outputStream); } else { LogArchiver.writeArchivedLogTailToStream(logFile, outputStream); } } catch (RuntimeException | IOException ex) { log.error("Unable to download file", ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(outputStream); } } catch (LogFileNotFoundException e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.haulmont.cuba.portal.controllers.LogDownloadController.java
@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET) public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId, @RequestParam(value = "full", required = false) Boolean downloadFull, @PathVariable(value = "file") String logFileName) throws IOException { UserSession userSession = getSession(sessionId, response); if (userSession == null) return;/*w w w. java2s. co m*/ if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // security check, handle only valid file name String filename = FilenameUtils.getName(logFileName); try { File logFile = logControl.getLogFile(filename); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Content-Type", "application/zip"); response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Disposition", "attachment; filename=" + filename); OutputStream outputStream = null; try { outputStream = response.getOutputStream(); if (BooleanUtils.isTrue(downloadFull)) { LogArchiver.writeArchivedLogToStream(logFile, outputStream); } else { LogArchiver.writeArchivedLogTailToStream(logFile, outputStream); } } catch (RuntimeException | IOException ex) { log.error("Unable to assemble zipped log file", ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(outputStream); } } catch (LogFileNotFoundException e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.sap.dirigible.runtime.registry.RegistryServlet.java
private boolean setCacheHeaders(IEntity entity, HttpServletRequest request, HttpServletResponse response) throws IOException { boolean cached = false; IEntityInformation entityInformation = entity.getInformation(); String modifiedSinceHeader = request.getHeader(IF_MODIFIED_SINCE_HEADER); if ((entityInformation != null)) { Calendar lastModified = getCalendar(entityInformation.getModifiedAt()); if ((!StringUtils.isEmpty(modifiedSinceHeader))) { Calendar modifiedSince = getCalendar(DateUtils.parseDate(modifiedSinceHeader)); if (lastModified.compareTo(modifiedSince) <= 0) { Calendar expires = getCalendar(lastModified); expires.add(Calendar.MONTH, 1); response.setDateHeader(EXPIRES_HEADER, expires.getTimeInMillis()); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); cached = true;/*from w w w . ja va 2 s. co m*/ } } response.setDateHeader(LAST_MODIFIED_HEADER, lastModified.getTimeInMillis()); } return cached; }
From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java
private void processQuery(HttpServletRequest request, HttpServletResponse response) { try {/* w w w . j a va2 s . c om*/ System.out.println("--------------------------------------------"); for (Enumeration<String> en = request.getParameterNames(); en.hasMoreElements();) { String name = en.nextElement(); System.out.println(name + "=" + request.getParameter(name)); } // these are parameters I pass from my ProjectDataSource on all calls. Change to meet your needs. String context = request.getParameter("context"); String model = request.getParameter("model"); String xq = request.getParameter("xq"); String op = request.getParameter("_operationType"); response.setContentType("text/xml"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); getResponse(out, context, model, xq, op); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:org.nuxeo.theme.html.servlets.Images.java
@Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final String path = request.getPathInfo().substring(1); byte[] data = null; try {/* ww w .j av a2s . c o m*/ data = Manager.getThemeManager().getImageResource(path); } catch (ThemeException e) { log.error("Image not found: " + path); } if (data != null) { OutputStream os = response.getOutputStream(); BufferingServletOutputStream.stopBuffering(os); String ext = FileUtils.getFileExtension(path); String mimeType = Utils.getImageMimeType(ext); response.addHeader("content-type", mimeType); // Cache headers final String lifetime = "604800"; // 1 week final long now = System.currentTimeMillis(); response.addHeader("Cache-Control", "max-age=" + lifetime); response.addHeader("Cache-Control", "must-revalidate"); response.setDateHeader("Last-Modified", now); response.setDateHeader("Expires", now + new Long(lifetime) * 1000L); os.write(data); os.close(); } }
From source file:org.ambraproject.wombat.controller.StaticResourceController.java
/** * Serves a .js or .css asset that has already been concatenated and minified. See {@link AssetService} for details on * this process./*from ww w .ja v a 2s. c om*/ * * @param filePath the path to the file (relative to the theme) * @param response response object * @throws IOException */ private void serveCompiledAsset(String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException { // The hash is already included in the compiled asset's filename, so we take advantage // of that here and use it as the etag. Matcher matcher = COMPILED_ASSET_PATTERN.matcher(filePath); if (!matcher.matches()) { throw new IllegalArgumentException(filePath + " is not a valid compiled asset path"); } String basename = filePath.substring(COMPILED_NAMESPACE.length()); // This is a "strong" etag since it's based on a fingerprint of the contents. String etag = String.format("\"%s\"", matcher.group(1)); long lastModified = assetService.getLastModifiedTime(basename); if (HttpMessageUtil.checkIfModifiedSince(request, lastModified, etag)) { response.setHeader("Etag", etag); response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified); assetService.serveCompiledAsset(basename, response.getOutputStream()); } else { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("Etag", etag); } }
From source file:it.jugpadova.controllers.JCaptchaController.java
@RequestMapping public void image(HttpServletRequest req, HttpServletResponse res) throws IOException { byte[] captchaChallengeAsJpeg = null; // the output stream to render the captcha image as jpeg into ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); // get the session id that will identify the generated captcha. //the same id must be used to validate the res, the session id is a good candidate! String captchaId = req.getSession().getId(); // call the ImageCaptchaService getChallenge method BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, req.getLocale()); // a jpeg encoder JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream); jpegEncoder.encode(challenge);// w w w . j ava 2 s.c o m captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the res res.setHeader("Cache-Control", "no-store"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); res.setContentType("image/jpeg"); ServletOutputStream resOutputStream = res.getOutputStream(); resOutputStream.write(captchaChallengeAsJpeg); resOutputStream.flush(); resOutputStream.close(); }
From source file:org.rhq.enterprise.gui.download.DownloadServlet.java
private void download(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w ww .ja v a 2 s . c o m File downloadDir = getRootDownloadsDir(); File downloadFile = new File(downloadDir, req.getPathInfo()); if (!isForbiddenPath(downloadFile, resp)) { if (!downloadFile.exists()) { disableBrowserCache(resp); resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File does not exist: " + downloadFile.getName()); return; } resp.setContentType(getMimeType(downloadFile)); resp.setHeader("Content-Disposition", "attachment; filename=" + downloadFile.getName()); resp.setContentLength((int) downloadFile.length()); resp.setDateHeader("Last-Modified", downloadFile.lastModified()); FileInputStream stream = new FileInputStream(downloadFile); try { StreamUtil.copy(stream, resp.getOutputStream(), false); } finally { stream.close(); } } } catch (Throwable t) { log.error("Failed to stream download content.", t); disableBrowserCache(resp); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to download content"); } return; }