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:ru.frostman.web.dispatch.Dispatcher.java
/** * Check headers for client side caching * * @param request object/*from w ww. j a v a 2 s . c o m*/ * @param response object * @param lastModified time * @param eTag smth like uid * * @return true iff request processed */ private boolean ensureNotModified(HttpServletRequest request, HttpServletResponse response, long lastModified, String eTag) { // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader(HEADER_IF_NONE_MATCH); if (ifNoneMatch != null && (Objects.equal(ifNoneMatch, eTag) || Objects.equal(ifNoneMatch, "*"))) { sendNotModified(response, eTag); return true; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader(HEADER_IF_MODIFIED_SINCE); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { sendNotModified(response, eTag); return true; } return false; }
From source file:com.github.zhanhb.ckfinder.download.PathPartial.java
/** * Check if the if-modified-since condition is satisfied. * * @param request The servlet request we are processing * @param attr File attributes/*from w ww .jav a2 s .c om*/ */ @SuppressWarnings("NestedAssignment") private void checkIfModifiedSince(HttpServletRequest request, BasicFileAttributes attr) { try { long headerValue; // If an If-None-Match header has been specified, if modified since // is ignored. if (request.getHeader(HttpHeaders.IF_NONE_MATCH) == null && (headerValue = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)) != -1 && attr.lastModifiedTime().toMillis() < 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_NOT_MODIFIED); } } catch (IllegalArgumentException ex) { } }
From source file:org.localmatters.lesscss4j.servlet.LessCssServlet.java
protected boolean isModified(HttpServletRequest request, CacheEntry cacheEntry) { String etag = request.getHeader(IF_NONE_MATCH); if (_useETag && etag != null) { String md5Sum = cacheEntry.getMd5Sum(); return !md5Sum.equals(etag); } else {/*from w w w . j a v a 2 s . c om*/ // If the If-Mod-Since header is missing, we get -1 back from // getDateHeader and this will always evaluate to true. Round // down to the nearest second for a proper compare. return request.getDateHeader(IF_MOD_SINCE) < (cacheEntry.getLastUpdate() / 1000 * 1000); } }
From source file:com.google.reducisaurus.servlets.BaseServlet.java
private boolean isMemcacheAllowed(HttpServletRequest hreq) { // If there are any caching related headers, don't use any server side // caches. This isn't built to HTTP spec, but it covers the // shift-reload case. String cacheControl = hreq.getHeader("Cache-Control"); if (cacheControl != null && (cacheControl.contains("max-age") || cacheControl.contains("no-cache"))) { return false; }/*w w w . ja va 2 s. com*/ String pragma = hreq.getHeader("Pragma"); if (pragma != null && pragma.contains("no-cache")) { return false; } try { long ims = hreq.getDateHeader("If-Modified-Since"); if (ims != -1) { return false; } } catch (IllegalArgumentException e) { return false; } return true; }
From source file:com.agiletec.apsadmin.system.dispatcher.Struts2ServletDispatcher.java
/** * Locate a static resource and copy directly to the response, * setting the appropriate caching headers. * * @param name The resource name/*from www . j a va 2s.c o m*/ * @param request The request * @param response The response * @throws IOException If anything goes wrong */ protected void findStaticResource(String name, HttpServletRequest request, HttpServletResponse response) throws IOException { if (!name.endsWith(".class")) { for (String pathPrefix : pathPrefixes) { InputStream is = findInputStream(name, pathPrefix); if (is != null) { Calendar cal = Calendar.getInstance(); // check for if-modified-since, prior to any other headers long ifModifiedSince = 0; try { ifModifiedSince = request.getDateHeader("If-Modified-Since"); } catch (Exception e) { LOG.warn("Invalid If-Modified-Since header value: '" + request.getHeader("If-Modified-Since") + "', ignoring"); } 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(name); 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(); } return; } } } response.sendError(HttpServletResponse.SC_NOT_FOUND); }
From source file:com.github.zhanhb.ckfinder.download.PathPartial.java
/** * Parse the range header./*from www .j a v a 2 s. co m*/ * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param attr File attributes * @param etag ETag of the entity * @return array of ranges */ @Nullable @SuppressWarnings("ReturnOfCollectionOrArrayField") private Range[] parseRange(HttpServletRequest request, HttpServletResponse response, BasicFileAttributes attr, String etag) throws IOException { // Checking If-Range String headerValue = request.getHeader(HttpHeaders.IF_RANGE); if (headerValue != null) { long headerValueTime = -1; try { headerValueTime = request.getDateHeader(HttpHeaders.IF_RANGE); } catch (IllegalArgumentException e) { // Ignore } // If the ETag the client gave does not match the entity // eTag, then the entire entity is returned. if (headerValueTime == -1 && !headerValue.trim().equals(etag) || attr.lastModifiedTime().toMillis() > headerValueTime + 1000) { // If the timestamp of the entity the client got is older than // the last modification date of the entity, the entire entity // is returned. return FULL; } } long fileLength = attr.size(); if (fileLength == 0) { return FULL; } // Retrieving the range header (if any is specified String rangeHeader = request.getHeader(HttpHeaders.RANGE); if (rangeHeader == null) { return FULL; } // bytes is the only range unit supported (and I don't see the point // of adding new ones). if (!rangeHeader.startsWith("bytes=")) { return FULL; } // List which will contain all the ranges which are successfully // parsed. List<Range> result = new ArrayList<>(4); // Parsing the range list // "bytes=".length() = 6 for (int index, last = 6;; last = index + 1) { index = rangeHeader.indexOf(',', last); boolean isLast = index == -1; final String rangeDefinition = (isLast ? rangeHeader.substring(last) : rangeHeader.substring(last, index)).trim(); final int dashPos = rangeDefinition.indexOf('-'); if (dashPos == -1) { break; } final Range currentRange = new Range(fileLength); try { if (dashPos == 0) { final long offset = Long.parseLong(rangeDefinition); if (offset == 0) { // -0, --0 break; } currentRange.start = Math.max(fileLength + offset, 0); } else { currentRange.start = Long.parseLong(rangeDefinition.substring(0, dashPos)); if (dashPos < rangeDefinition.length() - 1) { currentRange.end = Long .parseLong(rangeDefinition.substring(dashPos + 1, rangeDefinition.length())); } } } catch (NumberFormatException e) { break; } if (!currentRange.validate()) { break; } result.add(currentRange); if (isLast) { int size = result.size(); if (size == 0) { break; } return result.toArray(new Range[size]); } } response.addHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + fileLength); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; }
From source file:org.fao.unredd.portal.ApplicationController.java
@RequestMapping("/static/**") public void getCustomStaticFile(HttpServletRequest request, HttpServletResponse response) throws IOException { // Get path to file String fileName = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); // Verify file exists File file = new File(config.getDir() + "/static/" + fileName); if (!file.isFile()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;/*w ww . jav a2 s .com*/ } // Manage cache headers: Last-Modified and If-Modified-Since long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long lastModified = file.lastModified(); if (ifModifiedSince >= (lastModified / 1000 * 1000)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } response.setDateHeader("Last-Modified", lastModified); // Set content type FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(fileName); response.setContentType(type); // Send contents try { InputStream is = new FileInputStream(file); IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { logger.error("Error reading file", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.jahia.services.content.files.FileServlet.java
protected boolean isNotModified(FileKey fileKey, FileLastModifiedCacheEntry lastModifiedEntry, HttpServletRequest request, HttpServletResponse response) { if (lastModifiedEntry != null) { // check presence of the 'If-None-Match' header String eTag = request.getHeader("If-None-Match"); if (eTag != null) { return eTag.equals(lastModifiedEntry.getETag()); }/*from w w w. jav a2 s. c o m*/ // check presence of the 'If-Modified-Since' header long modifiedSince = request.getDateHeader("If-Modified-Since"); if (modifiedSince > -1 && lastModifiedEntry.getLastModified() > 0 && lastModifiedEntry.getLastModified() / 1000 * 1000 <= modifiedSince) { return true; } } return false; }
From source file:nl.isaac.dotcms.minify.servlet.MinifyServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check if the "uris" parameter is valid String urisAsString = request.getParameter("uris"); ParamValidationUtil.validateParamNotNull(urisAsString, "uris"); // Define variables whos content will be determined during the for loop. StringBuilder fileContentOfUris = new StringBuilder(); boolean isContentModified = false; ContentType overAllContentType = null; // Retrieve data that is used in the for loop only once for speed boolean isDebugMode = UtilMethods.isSet(request.getParameter("debug")); boolean isLiveMode = HostTools.isLiveMode(request); Date ifModifiedSince = new Date(request.getDateHeader("If-Modified-Since")); Host defaultHost = HostTools.getCurrentHost(request); try {/* w ww. ja va 2 s .c om*/ for (String uriAsString : StringListUtil.getCleanStringList(urisAsString)) { URI uri = new URI(uriAsString); ContentType currentContentType = ContentType.getContentType(uri); overAllContentType = overAllContentType == null ? currentContentType : overAllContentType; if (currentContentType == overAllContentType) { Host host = getHostOfUri(uri, defaultHost); if (isDebugMode) { fileContentOfUris.append(getOriginalFile(uri, host, isLiveMode)); isContentModified = true; } else { MinifyCacheKey key = new MinifyCacheKey(uri.getPath(), host.getHostname(), isLiveMode); MinifyCacheFile file = MinifyCacheHandler.INSTANCE.get(key); fileContentOfUris.append(file.getFileData()); Date modDate = file.getModDate(); isContentModified |= modDate.compareTo(ifModifiedSince) >= 0; } } else { Logger.warn(MinifyServlet.class, "Encountered uri with different contentType than the others, skipping file. Expected " + overAllContentType.extension + ", found: " + currentContentType.extension); } } response.setContentType(overAllContentType.contentTypeString); response.addHeader("Cache-Control", "public, max-age=" + BROWSER_CACHE_MAX_AGE); response.setDateHeader("Expires", new Date().getTime() + (BROWSER_CACHE_MAX_AGE * 1000)); if (isContentModified) { response.setDateHeader("Last-Modified", new Date().getTime()); response.getWriter().write(fileContentOfUris.toString()); } else { // No files are modified since the browser cached it, so send // status 304. Browser will then use the file from his cache response.setStatus(304); } } catch (DotCMSFileNotFoundException e) { Logger.error(MinifyServlet.class, "One or more files can't be found in dotCMS, sending 404 response", e); response.sendError(404); } catch (URISyntaxException e) { Logger.error(MinifyServlet.class, "Cannot parse one or more URIs", e); response.sendError(404); } }
From source file:wicket.protocol.http.WicketFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) *///w w w.ja va 2 s . co m public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; if (isWicketRequest(httpServletRequest)) { HttpServletResponse httpServletResponse = (HttpServletResponse) response; long lastModified = getLastModified(httpServletRequest); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic doGet(httpServletRequest, httpServletResponse); } else { long ifModifiedSince = httpServletRequest.getDateHeader("If-Modified-Since"); if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less maybeSetLastModified(httpServletResponse, lastModified); doGet(httpServletRequest, httpServletResponse); } else { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else { chain.doFilter(request, response); } }