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:org.yes.cart.web.filter.ImageFilter.java
public void handleRequestInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { final String requestPath = httpServletRequest.getRequestURI(); // RequestURI -> /yes-shop/imagevault/product/image.png final String contextPath = httpServletRequest.getContextPath(); // ContextPath -> /yes-shop final String servletPath = requestPath.substring(contextPath.length()); // ServletPath -> /imagevault/product/image.png final String previousToken = httpServletRequest.getHeader(IF_NONE_MATCH); final String currentToken = getETagValue(httpServletRequest); httpServletResponse.setHeader(ETAG, currentToken); final Date modifiedDate = new Date(httpServletRequest.getDateHeader(IF_MODIFIED_SINCE)); final Calendar calendar = Calendar.getInstance(); final Date now = calendar.getTime(); calendar.setTime(modifiedDate);/*from w ww.jav a 2 s . com*/ calendar.add(Calendar.MINUTE, getEtagExpiration()); if (currentToken.equals(previousToken) && (now.getTime() < calendar.getTime().getTime())) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED); // use the same date we sent when we created the ETag the first time through httpServletResponse.setHeader(LAST_MODIFIED, httpServletRequest.getHeader(IF_MODIFIED_SINCE)); final Logger log = ShopCodeContext.getLog(this); if (log.isDebugEnabled()) { log.debug("ETag the same, will return 304"); } } else { httpServletResponse.setDateHeader(LAST_MODIFIED, (new Date()).getTime()); final String width = httpServletRequest.getParameter(Constants.WIDTH); final String height = httpServletRequest.getParameter(Constants.HEIGHT); final ImageNameStrategy imageNameStrategy = imageService.getImageNameStrategy(servletPath); String code = imageNameStrategy.resolveObjectCode(servletPath); //optional product or sku code String locale = imageNameStrategy.resolveLocale(servletPath); //optional locale String originalFileName = imageNameStrategy.resolveFileName(servletPath); //here file name with prefix final String imageRealPathPrefix = getImageRepositoryRoot(); String absolutePathToOriginal = imageRealPathPrefix + imageNameStrategy.resolveRelativeInternalFileNamePath(originalFileName, code, locale); //path to not resized image final boolean origFileExists = imageService.isImageInRepository(originalFileName, code, imageNameStrategy.getUrlPath(), imageRealPathPrefix); if (!origFileExists) { code = Constants.NO_IMAGE; originalFileName = imageNameStrategy.resolveFileName(code); //here file name with prefix absolutePathToOriginal = imageRealPathPrefix + imageNameStrategy.resolveRelativeInternalFileNamePath(originalFileName, code, locale); //path to not resized image } String absolutePathToResized = null; if (width != null && height != null && imageService.isSizeAllowed(width, height)) { absolutePathToResized = imageRealPathPrefix + imageNameStrategy .resolveRelativeInternalFileNamePath(originalFileName, code, locale, width, height); } final byte[] imageFile = getImageFile(absolutePathToOriginal, absolutePathToResized, width, height); IOUtils.write(imageFile, httpServletResponse.getOutputStream()); } }
From source file:org.broadleafcommerce.cms.web.file.StaticAssetView.java
@Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { String cacheFilePath = (String) model.get("cacheFilePath"); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(cacheFilePath)); try {//from ww w.j a v a 2s .c o m String mimeType = (String) model.get("mimeType"); response.setContentType(mimeType); if (!browserAssetCachingEnabled) { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); } else { response.setHeader("Cache-Control", "public"); response.setHeader("Pragma", "cache"); if (!StringUtils.isEmpty(request.getHeader("If-Modified-Since"))) { long lastModified = request.getDateHeader("If-Modified-Since"); Calendar last = Calendar.getInstance(); last.setTime(new Date(lastModified)); Calendar check = Calendar.getInstance(); check.add(Calendar.SECOND, -2 * new Long(cacheSeconds).intValue()); if (check.compareTo(last) < 0) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } else { Calendar check = Calendar.getInstance(); check.add(Calendar.SECOND, -1 * new Long(cacheSeconds).intValue()); response.setDateHeader("Last-Modified", check.getTimeInMillis()); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, new Long(cacheSeconds).intValue()); response.setDateHeader("Expires", cal.getTimeInMillis()); } OutputStream os = response.getOutputStream(); boolean eof = false; while (!eof) { int temp = bis.read(); if (temp < 0) { eof = true; } else { os.write(temp); } } os.flush(); } catch (Exception e) { if (e.getCause() instanceof SocketException) { if (LOG.isDebugEnabled()) { LOG.debug("Unable to stream asset", e); } } else { LOG.error("Unable to stream asset", e); throw e; } } finally { try { bis.close(); } catch (Throwable e) { //do nothing } } }
From source file:de.blizzy.documentr.web.attachment.AttachmentController.java
@RequestMapping(value = "/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/" + "{branchName:" + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{pagePath:" + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}/" + "{name:.*}", method = { RequestMethod.GET, RequestMethod.HEAD }) @PreAuthorize("hasPagePermission(#projectName, #branchName, #pagePath, VIEW)") public ResponseEntity<byte[]> getAttachment(@PathVariable String projectName, @PathVariable String branchName, @PathVariable String pagePath, @PathVariable String name, @RequestParam(required = false) boolean download, HttpServletRequest request) throws IOException { try {/*from w w w . j a v a 2s .c o m*/ pagePath = Util.toRealPagePath(pagePath); PageMetadata metadata = pageStore.getAttachmentMetadata(projectName, branchName, pagePath, name); HttpHeaders headers = new HttpHeaders(); long lastEdited = metadata.getLastEdited().getTime(); long authenticationCreated = AuthenticationUtil.getAuthenticationCreationTime(request.getSession()); long lastModified = Math.max(lastEdited, authenticationCreated); if (!download) { long projectEditTime = PageUtil.getProjectEditTime(projectName); if (projectEditTime >= 0) { lastModified = Math.max(lastModified, projectEditTime); } long modifiedSince = request.getDateHeader("If-Modified-Since"); //$NON-NLS-1$ if ((modifiedSince >= 0) && (lastModified <= modifiedSince)) { return new ResponseEntity<byte[]>(headers, HttpStatus.NOT_MODIFIED); } } headers.setLastModified(lastModified); headers.setExpires(0); headers.setCacheControl("must-revalidate, private"); //$NON-NLS-1$ if (download) { headers.set("Content-Disposition", //$NON-NLS-1$ "attachment; filename=\"" + name.replace('"', '_') + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } Page attachment = pageStore.getAttachment(projectName, branchName, pagePath, name); headers.setContentType(MediaType.parseMediaType(attachment.getContentType())); return new ResponseEntity<byte[]>(attachment.getData().getData(), headers, HttpStatus.OK); } catch (PageNotFoundException e) { return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND); } }
From source file:org.opencms.main.CmsStaticResourceHandler.java
/** * Checks if the browser has an up to date cached version of requested * resource. Currently the check is performed using the "If-Modified-Since" * header. Could be expanded if needed.<p> * * @param request the HttpServletRequest from the browser * @param resourceLastModifiedTimestamp the timestamp when the resource was last modified. 0 if the last modification time is unknown * * @return true if the If-Modified-Since header tells the cached version in the browser is up to date, false otherwise *///from ww w. java2 s .c o m private boolean browserHasNewestVersion(HttpServletRequest request, long resourceLastModifiedTimestamp) { if (resourceLastModifiedTimestamp < 1) { // We do not know when it was modified so the browser cannot have an // up-to-date version return false; } /* * The browser can request the resource conditionally using an * If-Modified-Since header. Check this against the last modification * time. */ try { // If-Modified-Since represents the timestamp of the version cached // in the browser long headerIfModifiedSince = request.getDateHeader("If-Modified-Since"); if (headerIfModifiedSince >= resourceLastModifiedTimestamp) { // Browser has this an up-to-date version of the resource return true; } } catch (Exception e) { // Failed to parse header. Fail silently - the browser does not have // an up-to-date version in its cache. } return false; }
From source file:com.netspective.sparx.util.HttpServletResponseCache.java
public boolean isCacheHit(long lastModfTime, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Only do caching for GET requests String method = req.getMethod(); if (!method.equals("GET")) return false; // A last modified of -1 means we shouldn't use any cache logic if (lastModfTime == -1) return false; // If the client sent an If-Modified-Since header equal or after the // servlet's last modified time, send a short "Not Modified" status code // Round down to the nearest second since client headers are in seconds if ((lastModfTime / 1000 * 1000) <= req.getDateHeader("If-Modified-Since")) { res.setStatus(res.SC_NOT_MODIFIED); return true; }/*ww w . j a va 2 s .co m*/ String cacheKey = req.getServletPath() + req.getPathInfo() + req.getQueryString(); CacheData cacheData = (CacheData) pageCache.get(cacheKey); // Use the existing cache if it's current and valid if (cacheData != null && (lastModfTime <= cacheData.lastModf && cacheData.response.isValid())) { cacheData.response.writeTo(res); return true; } return false; }
From source file:com.autentia.common.util.web.ClasspathServlet.java
/** * Serve the file from the classpath//from ww w . ja v a2 s. c om */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getPathInfo(); /* if this servlet is not mapped to a path, use the request URI */ if (path == null) { path = request.getRequestURI().substring(request.getContextPath().length()); } if (!path.endsWith(PAGE_403)) { final String extension = path.substring(path.lastIndexOf('.')); if (!allowedExtensions.contains(extension)) { response.sendError(403, path + " denied"); return; } } final URL resource = Thread.currentThread().getContextClassLoader().getResource(path.substring(1)); if (resource == null) { response.sendError(404, path + " not found on classpath"); } else { /* check modification date */ final long ifModifiedSince = request.getDateHeader("If-Modified-Since"); final long lastModified = resource.openConnection().getLastModified(); if (ifModifiedSince != -1 && lastModified <= ifModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } if (log.isDebugEnabled()) { log.debug("Resolving URL " + path); } /* write to response */ response.setContentType(getServletContext().getMimeType(path)); final OutputStream out = new BufferedOutputStream(response.getOutputStream(), 512); final InputStream in = new BufferedInputStream(resource.openStream(), 512); final byte[] data = new byte[512]; int len; try { while ((len = in.read(data)) != -1) { out.write(data, 0, len); } } finally { in.close(); out.close(); } } }
From source file:com.newatlanta.appengine.servlet.GaeVfsServlet.java
/** * If a file is specified, return the file; if a folder is specified, then * either return a listing of the folder, or <code>FORBIDDEN</code>, based on * configuration./*from w w w .j a v a 2 s .c o m*/ */ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Path path = Paths.get(req.getRequestURI()); if (path.notExists()) { res.sendError(SC_NOT_FOUND); return; } BasicFileAttributes attrs = readBasicFileAttributes(path); if (attrs.isDirectory()) { if (dirListingAllowed) { res.getWriter().write(getListHTML(path)); res.flushBuffer(); } else { res.sendError(SC_FORBIDDEN, "Directory listing not allowed"); } return; } // the request is for a file, return it long lastModified = attrs.lastModifiedTime().to(SECONDS) * 1000; long ifModifiedSince = req.getDateHeader("If-Modified-Since"); if (lastModified == ifModifiedSince) { res.sendError(SC_NOT_MODIFIED); return; } res.setDateHeader("Last-Modified", lastModified); // the servlet MIME type is configurable via web.xml String contentType = getServletContext().getMimeType(path.getName().toString()); if (contentType != null) { res.setContentType(contentType); } // IOUtils.copy() buffers the InputStream internally InputStream in = path.newInputStream(); res.setContentLength(copy(in, res.getOutputStream())); in.close(); }
From source file:siddur.solidtrust.image.ImageController.java
@RequestMapping(value = "/images/{filename:.+}") public void serveImage(HttpServletRequest req, HttpServletResponse resp, @PathVariable("filename") String filename, @RequestParam(value = "s", required = false) String scope) throws IOException { String filepath = filename;/*from w w w .ja va 2 s . c om*/ if (scope != null) { filepath = scope + "/" + filepath; } //404 File f = new File(FileSystemUtil.getImageDir(), filepath); if (!f.exists()) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } //304 long lastModifiedTimestamp = f.lastModified(); long ifModifiedSince = req.getDateHeader("If-Modified-Since"); boolean notModified = (ifModifiedSince >= (lastModifiedTimestamp / 1000 * 1000)); if (notModified) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } else { resp.setDateHeader("Last-Modified", lastModifiedTimestamp); } //length resp.setContentLength((int) f.length()); //content type resp.setContentType("image/jpg"); //response FileCopyUtils.copy(new FileInputStream(f), resp.getOutputStream()); }
From source file:org.auraframework.http.AuraResourceServlet.java
/** * check the top level component/app./*from w w w. j a v a 2 s. c o m*/ * * This routine checks to see that we have a valid top level component. If our top level component is out of sync, * we have to ignore it here, but we _must_ force the client to not cache the response. * * If there is a QFE, we substitute the QFE descriptor for the one given us, and continue. Again, we cannot allow * caching. * * Finally, if there is no descriptor given, we simply ignore the request and give them an empty response. Which is * done here by returning null. * * Also note that this handles the 'if-modified-since' header, as we want to tell the browser that nothing changed * in that case. * * @param request the request (for exception handling) * @param response the response (for exception handling) * @param context the context to get the definition. * @return the set of descriptors we are sending back, or null in the case that we handled the response. * @throws IOException if there was an IO exception handling a client out of sync exception * @throws ServletException if there was a problem handling the out of sync */ private Set<DefDescriptor<?>> handleTopLevel(HttpServletRequest request, HttpServletResponse response, AuraContext context) throws IOException, ServletException { DefDescriptor<? extends BaseComponentDef> appDesc = context.getApplicationDescriptor(); DefinitionService definitionService = Aura.getDefinitionService(); MasterDefRegistry mdr = context.getDefRegistry(); context.setPreloading(true); if (appDesc == null) { // // This means we have nothing to say to the client, so the response is // left completely empty. // return null; } long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); String uid = context.getUid(appDesc); try { try { definitionService.updateLoaded(appDesc); if (uid != null && ifModifiedSince != -1) { // // In this case, we have an unmodified descriptor, so just tell // the client that. // response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return null; } } catch (ClientOutOfSyncException coose) { // // We can't actually handle an out of sync here, since we are doing a // preload. We have to ignore it, and continue as if nothing happened. // But in the process, we make sure to set 'no-cache' so that the result // is thrown away. This may actually not give the right result in bizarre // corner cases... beware cache inconsistencied on revert after a QFE. // // We actually probably should do something different, like send a minimalist // set of stuff to make the client re-try. // setNoCache(response); String oosUid = mdr.getUid(null, appDesc); return mdr.getDependencies(oosUid); } } catch (QuickFixException qfe) { DefDescriptor<ComponentDef> qfeDescriptor; // // A quickfix exception means that we couldn't compile something. // In this case, we still want to preload things, but we want to preload // quick fix values, note that we force NoCache here. // setNoCache(response); qfeDescriptor = definitionService.getDefDescriptor("markup://auradev:quickFixException", ComponentDef.class); context.setLoadingApplicationDescriptor(qfeDescriptor); String qfeUid; try { qfeUid = mdr.getUid(null, qfeDescriptor); } catch (QuickFixException death) { // // Ok, we really can't handle this here, so just punt. This means that // the quickfix display is broken, and whatever we try will give us grief. // response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } return mdr.getDependencies(qfeUid); } setLongCache(response); if (uid == null) { uid = context.getUid(appDesc); } return mdr.getDependencies(uid); }
From source file:org.ajax4jsf.resource.InternetResourceService.java
public void serviceResource(String resourceKey, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InternetResource resource;// getInternetResource(request); try {//from w ww .j a va 2 s. c om resource = getResourceBuilder().getResourceForKey(resourceKey); } catch (ResourceNotFoundException e) { throw new ServletException(e); } Object resourceDataForKey = getResourceBuilder().getResourceDataForKey(resourceKey); ResourceContext resourceContext = getResourceContext(resource, request, response); resourceContext.setResourceData(resourceDataForKey); try { if (resource.isCacheable(resourceContext) && this.cacheEnabled) { // Test for client request modification time. try { long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifModifiedSince >= 0) { // Test for modification. 1000 ms due to round // modification // time to seconds. long lastModified = resource.getLastModified(resourceContext).getTime() - 1000; if (lastModified <= ifModifiedSince) { response.setStatus(304); return; } } } catch (IllegalArgumentException e) { log.warn(Messages.getMessage(Messages.PARSING_IF_MODIFIED_SINCE_WARNING), e); } String cacheKey = resourceKey; CachedResourceContext cachedResourceContext = new CachedResourceContext(resourceContext); CacheContext cacheLoaderContext = new CacheContext(cachedResourceContext, resource); try { CacheContent content = (CacheContent) cache.get(cacheKey, cacheLoaderContext); if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.GET_CONTENT_FROM_CACHE_INFO, cacheKey)); } content.sendHeaders(response); // Correct expires date for resource. long expired = resource.getExpired(resourceContext); if (expired < 0) { expired = InternetResource.DEFAULT_EXPIRE; } response.setDateHeader("Expires", System.currentTimeMillis() + expired); // response.addHeader("Cache-control", "max-age=" // + (expired / 1000L)); if (!request.getMethod().equals("HEAD")) { content.send(response); } content.flush(response); } catch (CacheException e) { log.error(Messages.getMessage(Messages.SEND_RESOURCE_ERROR), e); throw new ServletException(Messages.getMessage(Messages.SEND_RESOURCE_ERROR_2, e.getMessage()), e); } } else { getLifecycle().send(resourceContext, resource); // sendResource(resource, request, response, // resourceDataForKey); } } finally { resourceContext.release(); } }