List of usage examples for javax.servlet.http HttpServletRequest getDateHeader
public long getDateHeader(String name);
long
value that represents a Date
object. From source file:grails.plugin.cache.web.PageInfo.java
/** * Returns true if the page's last-modified header indicates it is newer than * the copy held by the client as indicated by the request's if-modified-since header. *//* w w w . java 2s.c om*/ public boolean isModified(HttpServletRequest request) { long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); long lastModified = getDateHeader(HttpHeaders.LAST_MODIFIED); if (ifModifiedSince == -1 || lastModified == -1) { return true; } return lastModified > ifModifiedSince; }
From source file:am.ik.categolj2.api.file.FileRestController.java
@RequestMapping(value = "{fileId}/{fileName:.+}", method = RequestMethod.GET) public ResponseEntity<byte[]> downloadFile(@PathVariable("fileId") String fileId, @PathVariable("fileName") String fileName, HttpServletRequest request) { UploadFileSummary summary = uploadFileService.findOneSummary(fileId); HttpHeaders headers = new HttpHeadersBuilder(mediaTypeResolver) .contentTypeAttachmentIfNeccessary(summary.getFileName()) .lastModified(summary.getLastModifiedDate()).cacheForSeconds(cacheSeconds, false).build(); long ifModifiedSince = request.getDateHeader(com.google.common.net.HttpHeaders.IF_MODIFIED_SINCE); fileHelper.checkFileName(summary.getFileName(), fileName); return fileHelper.creteHttpResponse(ifModifiedSince, summary, headers); }
From source file:org.shredzone.commons.gravatar.GravatarCacheServlet.java
@Override protected void doService(HttpServletRequest req, HttpServletResponse resp) throws Exception { Matcher m = HASH_PATTERN.matcher(req.getPathInfo()); if (!m.matches()) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return;//from ww w . j av a 2 s .c o m } String hash = m.group(1); GravatarService gs = getWebApplicationContext().getBean("gravatarService", GravatarService.class); File gravatarFile = gs.fetchGravatar(hash); long modifiedSinceTs = -1; try { modifiedSinceTs = req.getDateHeader("If-Modified-Since"); } catch (IllegalArgumentException ex) { // As stated in RFC2616 Sec. 14.25, an invalid date will just be ignored. } if (modifiedSinceTs >= 0 && (modifiedSinceTs / 1000L) == (gravatarFile.lastModified() / 1000L)) { // The image has not been modified since last request resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } long size = gravatarFile.length(); if (size > 0 && size <= Integer.MAX_VALUE) { // Cast to int is safe resp.setContentLength((int) size); } resp.setContentType("image/png"); resp.setDateHeader("Date", System.currentTimeMillis()); resp.setDateHeader("Last-Modified", gravatarFile.lastModified()); try (InputStream in = new FileInputStream(gravatarFile)) { FileCopyUtils.copy(in, resp.getOutputStream()); } }
From source file:com.bstek.dorado.web.resolver.AbstractWebFileResolver.java
protected void outputResourcesWrapper(ResourcesWrapper resourcesWrapper, HttpServletRequest request, HttpServletResponse response) throws Exception { if (resourcesWrapper.getHttpStatus() != 0) { response.setStatus(resourcesWrapper.getHttpStatus()); } else {//from w w w . j a v a 2 s .co m // ?Client??-1 long cachedLastModified = request.getDateHeader(HttpConstants.IF_MODIFIED_SINCE); // ?Server?? long lastModified = resourcesWrapper.getLastModified(); // ?Client if (lastModified != 0 && cachedLastModified != 0 && Math.abs(lastModified - cachedLastModified) < ONE_SECOND) { // ?Server???Client response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { String contentType = getContentType(resourcesWrapper); response.setContentType(contentType); // Client?? SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH); dateFormat.setTimeZone(GMT_TIME_ZONE); response.addHeader(HttpConstants.LAST_MODIFIED, dateFormat.format(new Date(lastModified))); Resource[] resources = resourcesWrapper.getResources(); OutputStream out = getOutputStream(request, response, resourcesWrapper); try { for (int i = 0; i < resources.length; i++) { if (i > 0 && contentType.contains("text")) { out.write("\n".getBytes(response.getCharacterEncoding())); } outputFile(out, resources[i]); } } finally { try { out.close(); } catch (IOException e) { // do nothing } } } } }
From source file:com.mirantis.cachemod.filter.CacheFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { if (request.getAttribute(conf.getAlreadyFilteredKey()) != null || !isCacheable(request)) { /*/*from w w w.j a v a 2 s . co m*/ * This request is not Cacheable */ chain.doFilter(request, response); } else { request.setAttribute(conf.getAlreadyFilteredKey(), Boolean.TRUE); HttpServletRequest httpRequest = (HttpServletRequest) request; boolean fragmentRequest = isFragment(httpRequest); String key = conf.getCacheKeyProvider().createKey(httpRequest); CacheEntry cacheEntry = conf.getCacheProvider().getEntry(key); if (cacheEntry != null) { if (!fragmentRequest) { /* * -1 of no in header */ long clientLastModified = httpRequest.getDateHeader("If-Modified-Since"); /* * Reply with SC_NOT_MODIFIED for client that has newest page */ if ((clientLastModified != -1) && (clientLastModified >= cacheEntry.getLastModified())) { ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } writeCacheToResponse(cacheEntry, response, fragmentRequest); } else { cacheEntry = conf.getCacheProvider().instantiateEntry(); CacheHttpServletResponse cacheResponse = new CacheHttpServletResponse( (HttpServletResponse) response, cacheEntry, conf, fragmentRequest); chain.doFilter(request, cacheResponse); if (cacheResponse.getStatus() == HttpServletResponse.SC_OK) { cacheResponse.commit(); if (conf.getUserDataProvider() != null) { cacheEntry.setUserData(conf.getUserDataProvider().createUserData(httpRequest)); } conf.getCacheProvider().putEntry(key, cacheEntry); } } } }
From source file:org.apache.struts2.dispatcher.DefaultStaticContentLoader.java
protected void process(InputStream is, String path, HttpServletRequest request, HttpServletResponse response) throws IOException { if (is != null) { Calendar cal = Calendar.getInstance(); // check for if-modified-since, prior to any other headers long ifModifiedSince = 0; try {/*from w w w. ja v a 2s. c om*/ ifModifiedSince = request.getDateHeader("If-Modified-Since"); } catch (Exception e) { LOG.warn("Invalid If-Modified-Since header value: '{}', ignoring", request.getHeader("If-Modified-Since")); } long lastModifiedMillis = lastModifiedCal.getTimeInMillis(); long now = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_MONTH, 1); long expires = cal.getTimeInMillis(); if (ifModifiedSince > 0 && ifModifiedSince <= lastModifiedMillis) { // not modified, content is not sent - only basic // headers and status SC_NOT_MODIFIED response.setDateHeader("Expires", expires); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); is.close(); return; } // set the content-type header String contentType = getContentType(path); if (contentType != null) { response.setContentType(contentType); } if (serveStaticBrowserCache) { // set heading information for caching static content response.setDateHeader("Date", now); response.setDateHeader("Expires", expires); response.setDateHeader("Retry-After", expires); response.setHeader("Cache-Control", "public"); response.setDateHeader("Last-Modified", lastModifiedMillis); } else { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "-1"); } try { copy(is, response.getOutputStream()); } finally { is.close(); } } }
From source file:com.github.zhanhb.ckfinder.download.PathPartial.java
/** * Check if the if-unmodified-since condition is satisfied. * * @param request The servlet request we are processing * @param attr File attributes/*from www .j a va 2 s . c o m*/ */ private void checkIfUnmodifiedSince(HttpServletRequest request, BasicFileAttributes attr) { if (request.getHeader(HttpHeaders.IF_MATCH) == null) { try { long lastModified = attr.lastModifiedTime().toMillis(); long headerValue = request.getDateHeader(HttpHeaders.IF_UNMODIFIED_SINCE); if (headerValue != -1 && lastModified >= headerValue + 1000) { // The entity has not been modified since the date // specified by the client. This is not an error case. throw new UncheckException(HttpServletResponse.SC_PRECONDITION_FAILED); } } catch (IllegalArgumentException ex) { throw new UncheckException(HttpServletResponse.SC_PRECONDITION_FAILED); } } }
From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java
/** * Validate request headers for resume./* w w w . j ava2s .c o m*/ * * <ul> * <li>"If-Match" header should contain "*" or ETag.</li> * <li>"If-Unmodified-Since" header should be greater than LastModified.</li> * </ul> */ private boolean preconditionFailed(HttpServletRequest request, ResourceInfo resourceInfo) { String match = request.getHeader("If-Match"); long unmodified = request.getDateHeader("If-Unmodified-Since"); return (match != null) ? !matches(match, resourceInfo.eTag) : (unmodified != -1 && modified(unmodified, resourceInfo.lastModified)); }
From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java
/** * <ul>// w w w . ja va 2s. co m * <li>Request-Header "If-None-Match" should contain "*" or ETag.</li> * <li>If-Modified-Since header should be greater than LastModified. This header is ignored if any If-None-Match * header is specified.</li> * </ul> */ private boolean notModified(HttpServletRequest request, ResourceInfo resourceInfo) { String noMatch = request.getHeader("If-None-Match"); long modified = request.getDateHeader("If-Modified-Since"); return (noMatch != null) ? matches(noMatch, resourceInfo.eTag) : (modified != -1 && !modified(modified, resourceInfo.lastModified)); }
From source file:com.manydesigns.portofino.pageactions.text.TextAction.java
protected Resolution streamAttachment(boolean isAttachment) { // find the attachment Attachment attachment = TextLogic.findAttachmentById(textConfiguration, id); if (attachment == null) { return new ErrorResolution(404, "Attachment not found"); }/*from ww w . ja va2 s . c o m*/ try { String attachmentId = attachment.getId(); final File file = RandomUtil.getCodeFile(pageInstance.getDirectory(), ATTACHMENT_FILE_NAME_PATTERN, attachmentId); //Cache HttpServletResponse response = context.getResponse(); ServletUtils.markCacheableForever(response); //Suggerisce al browser di usare la risorsa che ha in cache invece di riscaricarla - serve ancora? HttpServletRequest request = context.getRequest(); if (request.getHeader("If-Modified-Since") != null) { long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince >= file.lastModified()) { return new ErrorResolution(304); //Not modified } } InputStream is = new FileInputStream(file); StreamingResolution resolution = new StreamingResolution(attachment.getContentType(), is) .setLength(attachment.getSize()).setFilename(attachment.getFilename()) .setAttachment(isAttachment).setLastModified(file.lastModified()); return resolution; } catch (IOException e) { logger.error("Download failed", e); return new ErrorResolution(500, "Attachment error"); } }