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.shredzone.cilla.view.AbstractView.java
/** * Streams a {@link ResourceDataSource}. Also cares about setting proper HTTP response * headers.//from w w w .ja v a2 s. c o m * * @param ds * {@link ResourceDataSource} to stream * @param req * {@link HttpServletRequest} * @param resp * {@link HttpServletResponse} */ protected void streamDataSource(ResourceDataSource ds, HttpServletRequest req, HttpServletResponse resp) throws ViewException { try { if (isNotModifiedSince(req, ds.getLastModified())) { throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED); } Long length = ds.getLength(); if (length != null && length <= Integer.MAX_VALUE) { // Converting long to int is safe here... resp.setContentLength(length.intValue()); } resp.setContentType(ds.getContentType()); resp.setDateHeader("Last-Modified", ds.getLastModified().getTime()); try (InputStream in = ds.getInputStream()) { FileCopyUtils.copy(in, resp.getOutputStream()); } } catch (IOException ex) { throw new ViewException(ex); } }
From source file:org.xwiki.webjars.internal.WebJarsResourceReferenceHandler.java
/** * @param resourceReference a reference to a WebJar resource * @return {@code true} if the referenced resource is static and is cached by the browser, {@code false} if the * browser should discard the cached version and use the new version from this response *//*from ww w.j ava 2s. com*/ private boolean shouldBrowserUseCachedContent(WebJarsResourceReference resourceReference) { // If the request contains an "If-Modified-Since" header and the referenced resource is not supposed to be // evaluated (i.e. no Velocity code) then return a 304 so to tell the browser to use its cached version. Request request = this.container.getRequest(); if (request instanceof ServletRequest && !shouldEvaluateResource(resourceReference)) { // This is a request for a static resource from a WebJar. if (((ServletRequest) request).getHttpServletRequest().getHeader("If-Modified-Since") != null) { // The user probably used F5 to reload the page and the browser checks if there are changes. Response response = this.container.getResponse(); if (response instanceof ServletResponse) { // Return the 304 Not Modified. Static WebJar resources don't change if their path doesn't change // (and the WebJar version is included in the path). ((ServletResponse) response).getHttpServletResponse() .setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } } } return false; }
From source file:org.b3log.symphony.processor.FileUploadServlet.java
@Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (QN_ENABLED) { return;/*from ww w . j a v a2 s . c o m*/ } final LatkeBeanManager beanManager = Lifecycle.getBeanManager(); final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class); final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class); final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class); try { final JSONObject option = optionQueryService.getOption(Option.ID_C_MISC_ALLOW_ANONYMOUS_VIEW); if (!"0".equals(option.optString(Option.OPTION_VALUE))) { if (null == userQueryService.getCurrentUser(req) && !userMgmtService.tryLogInWithCookie(req, resp)) { final String referer = req.getHeader("Referer"); if (!StringUtils.contains(referer, "fangstar.net")) { final String authorization = req.getHeader("Authorization"); LOGGER.debug("Referer [" + referer + "], Authorization [" + authorization + "]"); if (!StringUtils.contains(authorization, "Basic ")) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } else { String usernamePwd = StringUtils.substringAfter(authorization, "Basic "); usernamePwd = Base64.decodeToString(usernamePwd); final String username = usernamePwd.split(":")[0]; final String password = usernamePwd.split(":")[1]; if (!StringUtils.equals(username, Symphonys.get("http.basic.auth.username")) || !StringUtils.equals(password, Symphonys.get("http.basic.auth.password"))) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } } } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets file failed", e); resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } final String uri = req.getRequestURI(); String key = uri.substring("/upload/".length()); key = StringUtils.substringBeforeLast(key, "-64.jpg"); // Erase Qiniu template key = StringUtils.substringBeforeLast(key, "-260.jpg"); // Erase Qiniu template String path = UPLOAD_DIR + key; if (!FileUtil.isExistingFile(new File(path))) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final byte[] data = IOUtils.toByteArray(new FileInputStream(path)); final String ifNoneMatch = req.getHeader("If-None-Match"); final String etag = "\"" + MD5.hash(new String(data)) + "\""; resp.addHeader("Cache-Control", "public, max-age=31536000"); resp.addHeader("ETag", etag); resp.setHeader("Server", "Latke Static Server (v" + SymphonyServletListener.VERSION + ")"); if (etag.equals(ifNoneMatch)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } final OutputStream output = resp.getOutputStream(); IOUtils.write(data, output); output.flush(); IOUtils.closeQuietly(output); }
From source file:org.alfresco.repo.web.scripts.solr.NodeContentGet.java
/** * * @param req WebScriptRequest/*w w w .j a v a2 s . c o m*/ * @param res WebScriptResponse * @throws IOException */ public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException { ContentReader textReader = null; Exception transformException = null; String nodeIDString = req.getParameter("nodeId"); if (nodeIDString == null) { throw new WebScriptException("nodeID parameter is required for GetNodeContent"); } long nodeId = Long.valueOf(nodeIDString).longValue(); String propertyQName = req.getParameter("propertyQName"); QName propertyName = null; if (propertyQName == null) { propertyName = ContentModel.PROP_CONTENT; } else { propertyName = QName.createQName(propertyQName); } Pair<Long, NodeRef> pair = nodeDAO.getNodePair(nodeId); if (pair == null) { // If the node does not exists we treat it as if it has no content // We could be trying to update the content of a node in the index that has been deleted. res.setStatus(HttpStatus.SC_NO_CONTENT); return; } NodeRef nodeRef = pair.getSecond(); // check If-Modified-Since header and set Last-Modified header as appropriate Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED); // May be null - if so treat as just changed if (modified == null) { modified = new Date(); } long modifiedSince = -1; String modifiedSinceStr = req.getHeader("If-Modified-Since"); if (modifiedSinceStr != null) { try { modifiedSince = dateFormat.parse(modifiedSinceStr).getTime(); } catch (Throwable e) { if (logger.isWarnEnabled()) { logger.warn("Browser sent badly-formatted If-Modified-Since header: " + modifiedSinceStr); } } if (modifiedSince > 0L) { // round the date to the ignore millisecond value which is not supplied by header long modDate = (modified.getTime() / 1000L) * 1000L; if (modDate <= modifiedSince) { res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } } ContentReader reader = contentService.getReader(nodeRef, propertyName); if (reader == null) { res.setStatus(HttpStatus.SC_NO_CONTENT); return; } try { // get the transformer TransformationOptions options = new TransformationOptions(); options.setUse("index"); options.setSourceNodeRef(nodeRef); transformerDebug.pushAvailable(reader.getContentUrl(), reader.getMimetype(), MimetypeMap.MIMETYPE_TEXT_PLAIN, options); long sourceSize = reader.getSize(); List<ContentTransformer> transformers = contentService.getActiveTransformers(reader.getMimetype(), sourceSize, MimetypeMap.MIMETYPE_TEXT_PLAIN, options); transformerDebug.availableTransformers(transformers, sourceSize, options, "SolrIndexer"); if (transformers.isEmpty()) { res.setHeader(TRANSFORM_STATUS_HEADER, "noTransform"); res.setStatus(HttpStatus.SC_NO_CONTENT); return; } ContentTransformer transformer = transformers.get(0); // Perform transformation catering for mimetype AND encoding ContentWriter writer = contentService.getTempWriter(); writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); writer.setEncoding("UTF-8"); // Expect transformers to produce UTF-8 try { long start = System.currentTimeMillis(); transformer.transform(reader, writer, options); long transformDuration = System.currentTimeMillis() - start; res.setHeader(TRANSFORM_DURATION_HEADER, String.valueOf(transformDuration)); } catch (ContentIOException | UnsupportedTransformationException e) { transformException = e; } if (transformException == null) { // point the reader to the new-written content textReader = writer.getReader(); // Check that the reader is a view onto something concrete if (textReader == null || !textReader.exists()) { transformException = new ContentIOException( "The transformation did not write any content, yet: \n" + " transformer: " + transformer + "\n" + " temp writer: " + writer); } } if (transformException != null) { res.setHeader(TRANSFORM_STATUS_HEADER, "transformFailed"); res.setHeader(TRANSFORM_EXCEPTION_HEADER, transformException.getMessage()); res.setStatus(HttpStatus.SC_NO_CONTENT); } else { res.setStatus(HttpStatus.SC_OK); streamContentImpl(req, res, textReader, null, null, false, modified, String.valueOf(modified.getTime()), null, null); } } finally { transformerDebug.popAvailable(); } }
From source file:nl.b3p.viewer.stripes.ComponentActionBean.java
@DefaultHandler public Resolution source() throws IOException { File[] files = null;/*from www .jav a 2 s .c o m*/ if (className != null && component == null) { return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN, "User not authorized for this components' source"); } if (component == null) { // All source files for all components for this application // Sort list for consistency (error line numbers, cache, etc.) List<ConfiguredComponent> comps = new ArrayList<ConfiguredComponent>(application.getComponents()); Collections.sort(comps); Set<String> classNamesDone = new HashSet<String>(); List<File> fileList = new ArrayList<File>(); for (ConfiguredComponent cc : comps) { if (!Authorizations.isConfiguredComponentAuthorized(cc, context.getRequest())) { continue; } if (!classNamesDone.contains(cc.getClassName())) { classNamesDone.add(cc.getClassName()); if (cc.getViewerComponent() != null && cc.getViewerComponent().getSources() != null) { fileList.addAll(Arrays.asList(cc.getViewerComponent().getSources())); } } } files = fileList.toArray(new File[] {}); } else { // Source files specific to a component if (file != null) { // Search for the specified file in the component sources for (File f : component.getSources()) { if (f.getName().equals(file)) { files = new File[] { f }; break; } } if (files == null) { return new ErrorResolution(HttpServletResponse.SC_NOT_FOUND, file); } } else { // No specific sourcefile requested, return all sourcefiles // concatenated files = component.getSources(); } } long lastModified = -1; for (File f : files) { lastModified = Math.max(lastModified, f.lastModified()); } if (lastModified != -1) { long ifModifiedSince = context.getRequest().getDateHeader("If-Modified-Since"); if (ifModifiedSince != -1) { if (ifModifiedSince >= lastModified) { return new ErrorResolution(HttpServletResponse.SC_NOT_MODIFIED); } } } final File[] theFiles = files; StreamingResolution res = new StreamingResolution("application/javascript") { @Override public void stream(HttpServletResponse response) throws Exception { OutputStream out = response.getOutputStream(); for (File f : theFiles) { if (theFiles.length != 1) { out.write(("\n\n// Source file: " + f.getName() + "\n\n").getBytes("UTF-8")); } if (isMinified()) { String minified = getMinifiedSource(f); if (minified != null) { out.write(minified.getBytes("UTF-8")); } else { IOUtils.copy(new FileInputStream(f), out); } } else { IOUtils.copy(new FileInputStream(f), out); } } } }; if (lastModified != -1) { res.setLastModified(lastModified); } return res; }
From source file:com.sun.socialsite.web.filters.CustomizedPageCachingFilter.java
@Override protected void writeResponse(final HttpServletRequest request, final HttpServletResponse response, final PageInfo pageInfo) throws IOException, DataFormatException, ResponseHeadersNotModifiableException { if (pageInfo instanceof ExtendedPageInfo) { ExtendedPageInfo extendedPageInfo = (ExtendedPageInfo) pageInfo; if (extendedPageInfo.clientCanUseLocalCopy(request)) { log.trace("Telling client to use local copy: " + request.getRequestURI()); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; }//ww w . j a v a 2 s . c o m } super.writeResponse(request, response, pageInfo); }
From source file:org.tightblog.rendering.processors.PageProcessor.java
/** * Handle requests for weblog pages. GETs are for standard read-only retrieval of blog pages, * POSTs are for handling responses from the CommentProcessor, those will have a commentForm * attribute that translates to a WeblogEntryComment instance containing the comment. *//*from w w w .j av a 2s. c o m*/ @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { WeblogPageRequest incomingRequest = WeblogPageRequest.Creator.create(request, pageModel); Weblog weblog = weblogRepository.findByHandleAndVisibleTrue(incomingRequest.getWeblogHandle()); if (weblog == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } else { incomingRequest.setWeblog(weblog); } weblogPageCache.incrementIncomingRequests(); // is this the site-wide weblog? incomingRequest .setSiteWide(themeManager.getSharedTheme(incomingRequest.getWeblog().getTheme()).isSiteWide()); Instant lastModified = (incomingRequest.isSiteWide()) ? dp.getLastSitewideChange() : weblog.getLastModified(); // Respond with 304 Not Modified if it is not modified. // DB stores last modified in millis, browser if-modified-since in seconds, so need to truncate millis from the former. long inDb = lastModified.truncatedTo(ChronoUnit.SECONDS).toEpochMilli(); long inBrowser = getBrowserCacheExpireDate(request); if (inDb <= inBrowser) { weblogPageCache.incrementRequestsHandledBy304(); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // cache key to retrieve earlier generated content String cacheKey = null; // Check cache for content except during comment feedback/preview (i.e., commentForm present) WeblogEntryComment commentForm = (WeblogEntryComment) request.getAttribute("commentForm"); // pages containing user-specific comment forms aren't cached CachedContent rendererOutput = null; boolean newContent = false; if (commentForm == null) { cacheKey = generateKey(incomingRequest); rendererOutput = weblogPageCache.get(cacheKey, lastModified); } try { if (rendererOutput == null) { newContent = true; // not using cache so need to generate page from scratch // figure out what template to use if (incomingRequest.getCustomPageName() != null) { Template template = themeManager.getWeblogTheme(weblog) .getTemplateByName(incomingRequest.getCustomPageName()); // block internal custom pages from appearing directly if (template != null && template.getRole().isAccessibleViaUrl()) { incomingRequest.setTemplate(template); } } else { boolean invalid = false; if (incomingRequest.getWeblogEntryAnchor() != null) { WeblogEntry entry = weblogEntryManager.getWeblogEntryByAnchor(weblog, incomingRequest.getWeblogEntryAnchor()); if (entry == null || !entry.isPublished()) { invalid = true; } else { incomingRequest.setWeblogEntry(entry); incomingRequest.setTemplate( themeManager.getWeblogTheme(weblog).getTemplateByRole(Role.PERMALINK)); } } // use default template for other contexts (or, for entries, if PERMALINK template is undefined) if (!invalid && incomingRequest.getTemplate() == null) { incomingRequest .setTemplate(themeManager.getWeblogTheme(weblog).getTemplateByRole(Role.WEBLOG)); } } if (incomingRequest.getTemplate() == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // populate the rendering model Map<String, Object> initData = new HashMap<>(); initData.put("parsedRequest", incomingRequest); // if we're handling comments, add the comment form if (commentForm != null) { incomingRequest.setCommentForm(commentForm); } Map<String, Object> model = getModelMap("pageModelSet", initData); model.put("model", incomingRequest); // Load special models for site-wide blog if (incomingRequest.isSiteWide()) { model.put("site", siteModelFactory.apply(incomingRequest)); } // render content rendererOutput = thymeleafRenderer.render(incomingRequest.getTemplate(), model); } // write rendered content to response response.setContentType(rendererOutput.getRole().getContentType()); response.setContentLength(rendererOutput.getContent().length); // no-cache: browser may cache but must validate with server each time before using (check for 304 response) response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Last-Modified", lastModified.toEpochMilli()); response.getOutputStream().write(rendererOutput.getContent()); if (rendererOutput.getRole().isIncrementsHitCount()) { weblogManager.incrementHitCount(weblog); } if (newContent && cacheKey != null) { log.debug("PUT {}", cacheKey); weblogPageCache.put(cacheKey, rendererOutput); } } catch (Exception e) { log.error("Error during rendering for {}", incomingRequest, e); response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:ch.entwine.weblounge.test.harness.content.CacheTest.java
/** * Test if the cache is returning proper header to enable caching on the * client side, such as <code>Last-Modified</code>, <code>Expires</code> or * <code>ETag</code>.//from w w w . j a v a 2 s . c om * * @param serverUrl * the server url * @throws Exception * if the test fails */ private void testCacheHeaders(String serverUrl) throws Exception { logger.info("Preparing test of response caching"); DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); df.setTimeZone(TimeZone.getTimeZone("GMT")); // Prepare the request logger.info("Testing response cache"); String requestUrl = UrlUtils.concat(serverUrl, contentTestPage, language.getIdentifier()); logger.info("Sending request to the {} version of {}", language.getLocale().getDisplayName(), requestUrl); HttpGet request = new HttpGet(requestUrl); request.addHeader("X-Cache-Debug", "yes"); String[][] params = new String[][] { { "language", language.getIdentifier() } }; // Send and the request and examine the response. The first request might // not come out of the cache logger.debug("Sending request to {}", request.getURI()); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = TestUtils.request(httpClient, request, params); int statusCode = response.getStatusLine().getStatusCode(); boolean okOrNotModified = statusCode == HttpServletResponse.SC_OK || statusCode == HttpServletResponse.SC_NOT_MODIFIED; assertTrue(okOrNotModified); // Get the ETag header assertNotNull(response.getHeaders("ETag")); assertEquals(1, response.getHeaders("ETag").length); String eTag = response.getHeaders("ETag")[0].getValue(); // Get the Expires header assertNotNull(response.getHeaders("Expires")); assertEquals(1, response.getHeaders("Expires").length); Date expires = df.parse(response.getHeaders("Expires")[0].getValue()); // Prepare the second request response.getEntity().consumeContent(); httpClient.getConnectionManager().shutdown(); // Give the cache time to persist the entry Thread.sleep(1000); httpClient = new DefaultHttpClient(); request.setHeader("If-None-Match", eTag); request.setHeader("If-Modified-Since", df.format(System.currentTimeMillis())); response = TestUtils.request(httpClient, request, params); assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode()); // Get the Expires header assertNotNull(response.getHeaders("Expires")); assertEquals(1, response.getHeaders("Expires").length); // We are explicitly not checking for equality with the previously // received value, since on first request, that value is not yet correct // Get the ETag header assertNotNull(response.getHeaders("ETag")); assertEquals(0, response.getHeaders("ETag").length); // Test the Cache header assertNotNull(response.getHeaders("X-Cache-Key")); assertEquals(1, response.getHeaders("X-Cache-Key").length); // Test the expires header Date newExpires = df.parse(response.getHeaders("Expires")[0].getValue()); assertTrue(expires.before(newExpires) || expires.equals(newExpires)); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.dataconservancy.dcs.util.http.RequestHeaderUtil.java
/** * Implementation of RFC 2616 14.26// w w w .j a v a2 s .c om * * @param req the HttpServletRequest * @param res the HttpServletResponse * @param ifNoneMatch - comma separated list of etags to not match * @param objectToMatch - the object to match * @param objectToMatchEtag - the etag to match * @param objectToMatchId - the ID to match * @param lastModifiedDate - the last modified Date * @param ifModifiedSince - the modification reference Date * @return true if the response has been committed * @throws IOException an IO exception */ public boolean handleIfNoneMatch(HttpServletRequest req, HttpServletResponse res, String ifNoneMatch, Object objectToMatch, String objectToMatchEtag, String objectToMatchId, DateTime lastModifiedDate, Date ifModifiedSince) throws IOException { // If the header is null or empty, we don't do anything, simply return. if (ifNoneMatch == null || ifNoneMatch.trim().length() == 0) { return false; } // A objectToMatch was resolved ... if (objectToMatch != null) { // The client is performing a conditional request, based on the existence (or not) of any // version of the objectToMatch. if (ifNoneMatch.equals("*")) { if (ifModifiedSince == null) { // A objectToMatch exists, but If-None-Match was set to "*", and there is no If-Modified-Since header // to consider. res.addHeader(LAST_MODIFIED, DateUtility.toRfc822(lastModifiedDate)); res.addHeader(ETAG, objectToMatchEtag); res.sendError(HttpServletResponse.SC_NOT_MODIFIED); return true; } else { return handleIfModifiedSince(req, res, ifModifiedSince, lastModifiedDate); } } // The client is performing a conditional request, based on the existence (or not) of the specified // objectToMatch. final String[] candidateEtags = ifNoneMatch.split(","); for (String candidateEtag : candidateEtags) { if (candidateEtag.trim().equals(objectToMatchEtag)) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "If-None-Match header '" + ifNoneMatch + "' matched the requested Collection representation: '" + objectToMatchId + "' ('" + objectToMatchEtag + "')"); return true; } } } return false; }
From source file:com.xpn.xwiki.web.DownloadActionTest.java
@Test public void testIfModifiedSinceAfter() throws XWikiException, IOException { final Date d = new Date(); createAttachment(d, DEFAULT_FILE_NAME); setRequestExpectations(DEFAULT_URI, null, null, null, d.getTime() + 1000l); getMockery().checking(new Expectations() { {//from w w w . j a va 2 s . c o m allowing(DownloadActionTest.this.response).setStatus(with(HttpServletResponse.SC_NOT_MODIFIED)); } }); Assert.assertNull(this.action.render(getContext())); }