List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED
int SC_NOT_MODIFIED
To view the source code for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.
Click Source Link
From source file:org.dataconservancy.dcs.util.http.RequestHeaderUtil.java
public boolean handleIfModifiedSince(HttpServletRequest req, HttpServletResponse res, Date ifModifiedSince, DateTime lastModified) throws IOException { if (lastModified == null || ifModifiedSince == null) { return false; }/* w ww .jav a 2s .c o m*/ final DateTime ifModifiedInstant = new DateTime(ifModifiedSince); if (ifModifiedInstant.isAfter(DateTime.now())) { return false; } if (lastModified.isAfter(ifModifiedInstant)) { return false; } res.sendError(HttpServletResponse.SC_NOT_MODIFIED); return true; }
From source file:org.openlaszlo.data.DataSource.java
/** * Determine the datasource from the incoming request, * get the data, convert it to SWF, and write it out * to the given response.// w w w . j a va 2 s .c o m * * @param app absolute path name to app requesting data * @param req request * @param res response * @param converter converter to use * @throws DataSourceException if the data source encounters an error * @throws ConversionException if the conversion to SWF returns an error * @throws IOException if there is an IO error */ final public void getAsSWF(String app, HttpServletRequest req, HttpServletResponse res, Converter converter) throws DataSourceException, ConversionException, IOException { Data data = null; InputStream input = null; OutputStream output = null; long size = -1; long since = -1; // Check to see if client side caching is on boolean doClientCache = isClientCacheable(req); if (doClientCache) { String hdr = req.getHeader(LZHttpUtils.IF_MODIFIED_SINCE); if (hdr != null) { mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="req last modified time: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-96", new Object[] { hdr })); since = LZHttpUtils.getDate(hdr); } } mLogger.info( /* (non-Javadoc) * @i18n.test * @org-mes="requesting URL: '" + p[0] + "'" */ org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-108", new Object[] { DataSource.getURL(req) })); try { data = getData(app, req, res, since); if (data.notModified()) { mLogger.info( /* (non-Javadoc) * @i18n.test * @org-mes="NOT_MODIFIED" */ org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-120")); res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } mLogger.debug("got data"); if (!data.getMimeType().equals(MimeType.SWF)) { input = converter.convertToSWF(data, req, res); size = input.available(); mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="converted to " + p[0] + " bytes of SWF" */ org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-138", new Object[] { size })); // FIXME: [2003-09-22 bloch] input.available not realiable String enc = converter.chooseEncoding(req); if (enc != null && !enc.equals("")) { input = converter.encode(req, input, enc); res.setHeader(LZHttpUtils.CONTENT_ENCODING, enc); size = input.available(); } } else { mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="remote content was SWF" */ org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-156")); input = data.getInputStream(); size = data.size(); } if (size != -1) { mLogger.debug( /* (non-Javadoc) * @i18n.test * @org-mes="setting content length: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-169", new Object[] { size })); //res.setContentLength((int)size); } if (doClientCache) { long t = data.lastModified(); if (t != -1) { res.setDateHeader(LZHttpUtils.LAST_MODIFIED, t); } } else { LZHttpUtils.noStore(res); } try { output = res.getOutputStream(); long n = FileUtils.sendToStream(input, output); mLogger.info( /* (non-Javadoc) * @i18n.test * @org-mes=p[0] + " bytes sent" */ org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-192", new Object[] { n })); } catch (FileUtils.StreamWritingException e) { mLogger.warn( /* (non-Javadoc) * @i18n.test * @org-mes="StreamWritingException while responding: " + p[0] */ org.openlaszlo.i18n.LaszloMessages.getMessage(DataSource.class.getName(), "051018-201", new Object[] { e.getMessage() })); } } finally { if (data != null) { data.release(); } FileUtils.close(output); FileUtils.close(input); } }
From source file:net.siegmar.japtproxy.misc.IOHandler.java
/** * Sends a locally stored pool object to the client. This method will * send HTTP status code 304 (not modified) if the client sent a * 'If-Modified-Since' header and the pool object wasn't modified since * that date.//from w ww . ja va 2s . c om * * @param poolObject the pool object to sent * @param requestModifiedSince the "If-Modified-Since" header * @param res the HttpServletResponse object * @throws IOException is thrown if a problem occured while sending data */ protected void sendLocalFile(final PoolObject poolObject, final long requestModifiedSince, final HttpServletResponse res) throws IOException { final long poolModification = poolObject.getLastModified(); if (requestModifiedSince != -1 && poolModification <= requestModifiedSince) { LOG.debug("Requested resource wasn't modified since last request. " + "Returning status code 304 - not modified"); res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } res.setContentType(poolObject.getContentType()); res.setContentLength((int) poolObject.getSize()); res.setDateHeader(HttpHeaderConstants.LAST_MODIFIED, poolObject.getLastModified()); InputStream is = null; final OutputStream sendOs = res.getOutputStream(); try { LOG.info("Sending locally cached object '{}'", poolObject.getName()); is = poolObject.getInputStream(); IOUtils.copy(is, sendOs); } finally { IOUtils.closeQuietly(is); } }
From source file:wicket.protocol.http.WicketFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) *///from ww w .j a v a2 s. c om 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); } }
From source file:org.openbravo.erpCommon.utility.ImageUtils.java
/** * Outputs the image/content to the response *//* www. j ava 2 s . c om*/ public static void outputImageResource(final HttpServletRequest req, final HttpServletResponse resp, final String imageType) throws IOException, ServletException { try { OBContext.setAdminMode(true); // enforce cache validation/checks every time resp.addHeader(RESPONSE_HEADER_CACHE_CONTROL, RESPONSE_NO_CACHE); VariablesSecureApp vars = new VariablesSecureApp(req); Image img = null; if (imageType == "logo") { String logo = vars.getStringParameter("logo"); String org = vars.getStringParameter("orgId"); img = Utility.getImageLogoObject(logo, org); if (img == null) { byte[] imageFileContent = Utility.getImageLogo(logo, org); String mimeType = MimeTypeUtil.getInstance().getMimeTypeName(imageFileContent); resp.setContentType(mimeType); OutputStream out = resp.getOutputStream(); resp.setContentLength(imageFileContent.length); out.write(imageFileContent); out.close(); return; } } else { img = Utility.getImageObject(vars.getStringParameter("id")); } if (img != null) { String imageID = "IMGTAG" + img.getUpdated().toString(); if (ImageUtils.isImageResponseRequired(req, resp, imageID)) { // read the image data byte[] imgByte = img.getBindaryData(); // write the mimetype String mimeType = img.getMimetype();// write the mimetype if (mimeType == null) { mimeType = MimeTypeUtil.getInstance().getMimeTypeName(img.getBindaryData()); if (img != null) { // If there is an OBContext, we attempt to save the MIME type of the image updateMimeType(img.getId(), mimeType); } } if (!mimeType.equals("")) { resp.setContentType(mimeType); } // write the image OutputStream out = resp.getOutputStream(); resp.setContentLength(imgByte.length); out.write(imgByte); out.close(); } else { resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); resp.setDateHeader(RESPONSE_HEADER_LASTMODIFIED, req.getDateHeader(REQUEST_HEADER_IFMODIFIEDSINCE)); } } } finally { OBContext.restorePreviousMode(); } }
From source file:com.twitter.common.net.http.handlers.AssetHandler.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { OutputStream responseBody = resp.getOutputStream(); if (checksumMatches(req)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else {/*from w ww . j a v a 2 s. c o m*/ setPayloadHeaders(resp); boolean gzip = supportsGzip(req); if (gzip) { resp.setHeader("Content-Encoding", GZIP_ENCODING); } InputStream in = new ByteArrayInputStream(gzip ? staticAsset.getGzipData() : staticAsset.getRawData()); ByteStreams.copy(in, responseBody); } Closeables.close(responseBody, /* swallowIOException */ true); }
From source file:org.openmrs.module.atomfeed.web.AtomFeedDownloadServletTest.java
/** * @see AtomFeedDownloadServlet#doHead(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) * @verifies send valid headers if atom feed has changed */// ww w . j av a 2 s.c o m @Test public void doHead_shouldSendValidHeadersIfAtomFeedHasChanged() throws Exception { // create servlet and corresponding request and response object to be sent AtomFeedDownloadServlet atomFeedDownloadServlet = new AtomFeedDownloadServlet(); MockHttpServletRequest request = new MockHttpServletRequest("HEAD", "/atomfeed"); request.setContextPath("/somecontextpath"); MockHttpServletResponse response = new MockHttpServletResponse(); // intentionally change atom feed in order to not depend from other tests AtomFeedUtil.objectCreated(new Encounter()); String etagToken = "somevalue"; Date lastModified = new Date(); // set request headers request.addHeader("If-None-Match", '"' + etagToken + '"'); request.addHeader("If-Modified-Since", lastModified); atomFeedDownloadServlet.service(request, response); // check response headers Assert.assertNotSame(0, response.getContentLength()); Assert.assertEquals("application/atom+xml", response.getContentType()); Assert.assertNotSame(HttpServletResponse.SC_NOT_MODIFIED, response.getStatus()); Assert.assertNotSame('"' + etagToken + '"', response.getHeader("Etag")); Assert.assertNotNull(response.getHeader("Last-Modified")); }
From source file:net.voidfunction.rm.common.FileServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setMaxInactiveInterval(120); response.setHeader("Date", HTTPUtils.getServerTime(0)); // Parse the filename and the ID out of the URL String[] urlParts = request.getRequestURI().substring(1).split("/"); if (urlParts.length < 2) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return;/*from ww w. j ava 2s . co m*/ } String fileID = urlParts[1]; String fileName = ""; if (urlParts.length > 2) fileName = urlParts[2]; String logOut = "File " + fileID + " (" + fileName + ") requested by " + request.getRemoteHost() + " [Result: "; RMFile file = node.getFileRepository().getFileById(fileID); if (file == null) { // File with given ID not found - no redirect for you. logOut += "Not found]"; node.getLog().info(logOut); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().write("<b>404 Not Found</b><br/>Could not find a file with ID " + fileID); return; } boolean workerDL = (fileName.equals("Worker-Download")); if (workerDL) logOut += " (Worker Download) "; // Let the download listener know, if any, but don't count worker downloads if (dlListener != null && !workerDL) dlListener.fileDownloaded(file); String redirURL = null; if (locator != null) redirURL = (String) request.getSession().getAttribute("fileURL-" + fileID); if (redirURL == null && locator != null) redirURL = locator.locateURL(fileID, fileName); if (redirURL != null) { node.getLog().debug("Found redirect URL: " + redirURL); request.getSession().setAttribute("fileURL-" + fileID, redirURL); // Redirect to the new URL logOut += "Redirect]"; node.getLog().info(logOut); response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.setHeader("Location", redirURL); } else { // We have to try to find it ourselves logOut += "Found locally]"; node.getLog().info(logOut); // Caching magic - we can safely assume the file won't change String etag = Hex.encodeHexString(file.getHash()); response.setHeader("ETag", etag); String ifModifiedSince = request.getHeader("If-Modified-Since"); String ifNoneMatch = request.getHeader("If-None-Match"); boolean etagMatch = (ifNoneMatch != null) && (ifNoneMatch.equals(etag)); if (ifModifiedSince != null || etagMatch) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("Last-Modified", ifModifiedSince); } else { // Send the HTTP response and file data response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Expires", HTTPUtils.getServerTime(3600)); response.setHeader("Cache-Control", "max-age=3600"); response.setContentType(file.getMimetype()); response.setHeader("Content-Length", String.valueOf(file.getSize())); // Stream the file data to the output stream using Apache IOUtils InputStream fileIn = node.getFileRepository().getFileData(fileID); IOUtils.copyLarge(fileIn, response.getOutputStream()); } } }
From source file:com.enonic.cms.server.service.portal.mvc.controller.PortalRenderResponseServer.java
private ModelAndView servePageResponse(PortalRequest request, PortalResponse response, HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException { HttpServletUtil.setDateHeader(httpResponse, request.getRequestTime().toDate()); final SitePath requestedPath = request.getSitePath(); final SiteKey requestedSiteKey = requestedPath.getSiteKey(); final UserEntity requester = userDao.findByKey(request.getRequester()); final SiteEntity site = siteDao.findByKey(requestedSiteKey); final boolean cacheHeadersEnabled = resolveCacheHeadersEnabledForSite(requestedSiteKey); boolean forceNoCache = false; if (isInPreviewMode(httpRequest) || RenderTrace.isTraceOn()) { forceNoCache = true;//from w w w .j a v a 2 s. c o m final DateTime expirationTime = request.getRequestTime(); setHttpCacheHeaders(requester, request.getRequestTime(), expirationTime, httpResponse, forceNoCache, site); } else if (cacheHeadersEnabled) { forceNoCache = resolveForceNoCacheForSite(requestedSiteKey); final DateTime expirationTime = resolveExpirationTime(request.getRequestTime(), response.getExpirationTime()); setHttpCacheHeaders(requester, request.getRequestTime(), expirationTime, httpResponse, forceNoCache, site); } // filter response with any response plugins String content = filterResponseWithPlugins(httpRequest, response.getContent(), response.getHttpContentType()); response.setContent(content); boolean handleEtagLogic = cacheHeadersEnabled && !forceNoCache; if (handleEtagLogic) { // Handling etag logic if cache headers are enabled if (StringUtils.isEmpty(content)) { httpResponse.setContentType(response.getHttpContentType()); writeContent(httpResponse, response.getContentAsBytes()); } else { final String etagFromContent = resolveEtag(content); final boolean contentIsModified = isContentModified(httpRequest, etagFromContent); if (contentIsModified) { HttpServletUtil.setEtag(httpResponse, etagFromContent); httpResponse.setContentType(response.getHttpContentType()); writeContent(httpResponse, response.getContentAsBytes()); } else { httpResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else { httpResponse.setContentType(response.getHttpContentType()); writeContent(httpResponse, response.getContentAsBytes()); } return null; }
From source file:org.jahia.services.content.files.FileServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long timer = System.currentTimeMillis(); int code = HttpServletResponse.SC_OK; try {/*ww w .ja v a2 s .c om*/ FileKey fileKey = parseKey(req); if (fileKey != null && fileKey.getWorkspace() != null && StringUtils.isNotEmpty(fileKey.getPath())) { Cache<String, FileLastModifiedCacheEntry> lastModifiedCache = cacheManager.getLastModifiedCache(); FileLastModifiedCacheEntry lastModifiedEntry = lastModifiedCache.get(fileKey.getCacheKey()); if (isNotModified(fileKey, lastModifiedEntry, req, res)) { // resource is not changed code = HttpServletResponse.SC_NOT_MODIFIED; res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); logAccess(fileKey, req, "ok-not-modified"); return; } Cache<String, Map<String, FileCacheEntry>> contentCache = cacheManager.getContentCache(); Map<String, FileCacheEntry> entries = contentCache.get(fileKey.getCacheKey()); FileCacheEntry fileEntry = entries != null ? entries.get(fileKey.getThumbnail()) : null; if (fileEntry == null) { JCRNodeWrapper n = getNode(fileKey); if (n == null || !n.isFile()) { // cannot find it or it is not a file code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Date lastModifiedDate = n.getLastModifiedAsDate(); long lastModified = lastModifiedDate != null ? lastModifiedDate.getTime() : 0; String eTag = generateETag(n.getIdentifier(), lastModified); if (lastModifiedEntry == null) { lastModifiedEntry = new FileLastModifiedCacheEntry(eTag, lastModified); if (canCache(n)) { lastModifiedCache.put(fileKey.getCacheKey(), lastModifiedEntry); } } if (isNotModified(fileKey, lastModifiedEntry, req, res)) { // resource is not changed code = HttpServletResponse.SC_NOT_MODIFIED; res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); logAccess(fileKey, req, "ok-not-modified"); return; } fileEntry = getFileEntry(fileKey, n, lastModifiedEntry); if (fileEntry != null && fileEntry.getData() != null) { entries = contentCache.get(fileKey.getCacheKey()); if (entries == null) { entries = new HashMap<String, FileCacheEntry>(1); } entries.put(fileKey.getThumbnail(), fileEntry); contentCache.put(fileKey.getCacheKey(), entries); logAccess(fileKey, req, "ok"); } } else { if (lastModifiedEntry == null) { lastModifiedEntry = new FileLastModifiedCacheEntry(fileEntry.getETag(), fileEntry.getLastModified()); lastModifiedCache.put(fileKey.getCacheKey(), lastModifiedEntry); } logAccess(fileKey, req, "ok-cached"); if (logger.isDebugEnabled()) { logger.debug("Serving cached file entry {}", fileKey.toString()); } } if (fileEntry != null) { List<RangeUtils.Range> ranges; boolean useRanges = true; if (fileEntry.getBinary() instanceof BinaryRangesSupport) { useRanges = ((BinaryRangesSupport) fileEntry.getBinary()).supportRanges(); } ranges = useRanges ? RangeUtils.parseRange(req, res, fileEntry.getETag(), fileEntry.getLastModified(), fileEntry.getContentLength()) : null; if (fileKey.getPath().indexOf('%', fileKey.getPath().lastIndexOf('/')) != -1) { res.setHeader("Content-Disposition", "inline; filename=\"" + JCRContentUtils.unescapeLocalNodeName( StringUtils.substringAfterLast(fileKey.getPath(), "/")) + "\""); } res.setDateHeader("Last-Modified", fileEntry.getLastModified()); res.setHeader("ETag", fileEntry.getETag()); InputStream is = null; if (fileEntry.getData() != null) { // writing in-memory data is = new ByteArrayInputStream(fileEntry.getData()); } else if (fileEntry.getBinary() != null) { // spool from an input stream is = fileEntry.getBinary().getStream(); } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (ranges == null || (ranges == RangeUtils.FULL)) { res.setContentType(fileEntry.getMimeType()); if (fileEntry.getContentLength() <= Integer.MAX_VALUE) { res.setContentLength((int) fileEntry.getContentLength()); } else { res.setHeader("Content-Length", Long.toString(fileEntry.getContentLength())); } ServletOutputStream os = res.getOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); } else { res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { res.setContentType(fileEntry.getMimeType()); RangeUtils.Range range = (RangeUtils.Range) ranges.get(0); res.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { res.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long res.setHeader("Content-Length", "" + length); } ServletOutputStream os = res.getOutputStream(); RangeUtils.copy(is, os, range); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } else { res.setContentType("multipart/byteranges; boundary=" + RangeUtils.MIME_SEPARATION); try { res.setBufferSize(RangeUtils.getOutput()); } catch (IllegalStateException e) { // Silent catch } ServletOutputStream os = res.getOutputStream(); RangeUtils.copy(is, os, ranges.iterator(), fileEntry.getMimeType()); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } if ((fileEntry.getData() == null) && (fileEntry.getBinary() != null)) { fileEntry.getBinary().dispose(); fileEntry.setBinary(null); } SpringContextSingleton.getInstance() .publishEvent(new FileDownloadEvent(this, req, fileEntry.getIdentifier(), fileKey.getPath(), fileEntry.getNodeTypes(), fileKey.getWorkspace())); } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (RepositoryException e) { logger.error("Cannot get file", e); code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { if (logger.isDebugEnabled()) { logger.debug("Served [{}] with status code [{}] in [{}ms]", new Object[] { req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : ""), code, (System.currentTimeMillis() - timer) }); } } }