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.opencms.main.CmsStaticResourceHandler.java
/** * Sets the response headers.<p>//from ww w . ja va 2 s . c om * * @param request the request * @param response the response * @param filename the file name * @param resourceURL the resource URL */ protected void setResponseHeaders(HttpServletRequest request, HttpServletResponse response, String filename, URL resourceURL) { String cacheControl = "public, max-age=0, must-revalidate"; int resourceCacheTime = getCacheTime(filename); if (resourceCacheTime > 0) { cacheControl = "max-age=" + String.valueOf(resourceCacheTime); } response.setHeader("Cache-Control", cacheControl); response.setDateHeader("Expires", System.currentTimeMillis() + (resourceCacheTime * 1000)); // Find the modification timestamp long lastModifiedTime = 0; URLConnection connection = null; try { connection = resourceURL.openConnection(); lastModifiedTime = connection.getLastModified(); // Remove milliseconds to avoid comparison problems (milliseconds // are not returned by the browser in the "If-Modified-Since" // header). lastModifiedTime = lastModifiedTime - (lastModifiedTime % 1000); response.setDateHeader("Last-Modified", lastModifiedTime); if (browserHasNewestVersion(request, lastModifiedTime)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } catch (Exception e) { // Failed to find out last modified timestamp. Continue without it. LOG.debug("Failed to find out last modified timestamp. Continuing without it.", e); } finally { try { if (connection != null) { // Explicitly close the input stream to prevent it // from remaining hanging // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4257700 InputStream is = connection.getInputStream(); if (is != null) { is.close(); } } } catch (Exception e) { LOG.info("Error closing URLConnection input stream", e); } } // Set type mime type if we can determine it based on the filename String mimetype = OpenCms.getResourceManager().getMimeType(filename, "UTF-8"); if (mimetype != null) { response.setContentType(mimetype); } }
From source file:org.eclipse.dirigible.runtime.registry.RegistryServlet.java
private boolean setCacheHeaders(IEntity entity, HttpServletRequest request, HttpServletResponse response) throws IOException { boolean cached = false; IEntityInformation entityInformation = entity.getInformation(); String modifiedSinceHeader = request.getHeader(IF_MODIFIED_SINCE_HEADER); if ((entityInformation != null)) { Calendar lastModified = getCalendar(entityInformation.getModifiedAt()); if ((!StringUtils.isEmpty(modifiedSinceHeader))) { Calendar modifiedSince = getCalendar(parseDate(modifiedSinceHeader)); if (lastModified.getTimeInMillis() <= modifiedSince.getTimeInMillis()) { Calendar expires = getCalendar(lastModified); expires.add(Calendar.MONTH, 1); response.setDateHeader(EXPIRES_HEADER, expires.getTimeInMillis()); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); cached = true;//from ww w.j av a 2 s . c om } } response.setDateHeader(LAST_MODIFIED_HEADER, lastModified.getTimeInMillis()); } return cached; }
From source file:com.epam.catgenome.controller.util.MultipartFileSender.java
private boolean validateHeadersCaching(String fileName, long lastModified) throws IOException { // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return false; }//w w w.j a va2 s . c o m // 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("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + CONSTANT_1000 > lastModified) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return false; } return true; }
From source file:v7db.files.buckets.BucketsServlet.java
private void sendFile(HttpServletRequest request, HttpServletResponse response, byte[] sha, BSONObject file, Content content) throws IOException { String contentType = BSONUtils.getString(file, "contentType"); String name = BSONUtils.getString(file, "filename"); String eTag = Hex.encodeHexString(sha); String ifNoneMatch = request.getHeader("If-None-Match"); if (eTag.equals(ifNoneMatch)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return;//from ww w . j a v a2s.c om } response.setHeader("ETag", eTag); response.setHeader("Content-type", StringUtils.defaultString(contentType, "application/octet-stream")); if (StringUtils.isNotBlank(name)) response.setHeader("Content-disposition", "attachment; filename=\"" + name + "\""); response.setContentLength((int) content.getLength()); InputStream in = content.getInputStream(); try { IOUtils.copy(in, response.getOutputStream()); } finally { in.close(); } }
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 ww w. j ava 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:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java
protected boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode, String location) throws ServletException, IOException { // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION); if (locationHeader == null) { throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION + " header was found in the response"); }//from w ww . j ava 2s .c om // Modify the redirect to go to this proxy servlet rather that the proxied host String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue(), location); servletResponse.sendRedirect(locStr); return true; } // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } return false; }
From source file:org.alfresco.web.app.servlet.BaseDownloadContentServlet.java
/** * Processes the download request using the current context i.e. no authentication checks are made, it is presumed * they have already been done./*from w w w . j a v a2s. co m*/ * * @param req * The HTTP request * @param res * The HTTP response * @param allowLogIn * Indicates whether guest users without access to the content should be redirected to the log in page. If * <code>false</code>, a status 403 forbidden page is displayed instead. */ protected void processDownloadRequest(HttpServletRequest req, HttpServletResponse res, boolean allowLogIn, boolean transmitContent) throws ServletException, IOException { Log logger = getLogger(); String uri = req.getRequestURI(); if (logger.isDebugEnabled()) { String queryString = req.getQueryString(); logger.debug("Processing URL: " + uri + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); } uri = uri.substring(req.getContextPath().length()); StringTokenizer t = new StringTokenizer(uri, "/"); int tokenCount = t.countTokens(); t.nextToken(); // skip servlet name // attachment mode (either 'attach' or 'direct') String attachToken = t.nextToken(); boolean attachment = URL_ATTACH.equals(attachToken) || URL_ATTACH_LONG.equals(attachToken); ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); // get or calculate the noderef and filename to download as NodeRef nodeRef; String filename; // do we have a path parameter instead of a NodeRef? String path = req.getParameter(ARG_PATH); if (path != null && path.length() != 0) { // process the name based path to resolve the NodeRef and the Filename element try { PathRefInfo pathInfo = resolveNamePath(getServletContext(), path); nodeRef = pathInfo.NodeRef; filename = pathInfo.Filename; } catch (IllegalArgumentException e) { Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger); return; } } else { // a NodeRef must have been specified if no path has been found if (tokenCount < 6) { throw new IllegalArgumentException("Download URL did not contain all required args: " + uri); } // assume 'workspace' or other NodeRef based protocol for remaining URL elements StoreRef storeRef = new StoreRef(URLDecoder.decode(t.nextToken()), URLDecoder.decode(t.nextToken())); String id = URLDecoder.decode(t.nextToken()); // build noderef from the appropriate URL elements nodeRef = new NodeRef(storeRef, id); if (tokenCount > 6) { // found additional relative path elements i.e. noderefid/images/file.txt // this allows a url to reference siblings nodes via a cm:name based relative path // solves the issue with opening HTML content containing relative URLs in HREF or IMG tags etc. List<String> paths = new ArrayList<String>(tokenCount - 5); while (t.hasMoreTokens()) { paths.add(URLDecoder.decode(t.nextToken())); } filename = paths.get(paths.size() - 1); try { NodeRef parentRef = serviceRegistry.getNodeService().getPrimaryParent(nodeRef).getParentRef(); FileInfo fileInfo = serviceRegistry.getFileFolderService().resolveNamePath(parentRef, paths); nodeRef = fileInfo.getNodeRef(); } catch (FileNotFoundException e) { Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger); return; } } else { // filename is last remaining token filename = t.nextToken(); } } // get qualified of the property to get content from - default to ContentModel.PROP_CONTENT QName propertyQName = ContentModel.PROP_CONTENT; String property = req.getParameter(ARG_PROPERTY); if (property != null && property.length() != 0) { propertyQName = QName.createQName(property); } if (logger.isDebugEnabled()) { logger.debug("Found NodeRef: " + nodeRef); logger.debug("Will use filename: " + filename); logger.debug("For property: " + propertyQName); logger.debug("With attachment mode: " + attachment); } // get the services we need to retrieve the content NodeService nodeService = serviceRegistry.getNodeService(); ContentService contentService = serviceRegistry.getContentService(); // Check that the node still exists if (!nodeService.exists(nodeRef)) { Application.handleSystemError(getServletContext(), req, res, MSG_ERROR_NOT_FOUND, HttpServletResponse.SC_NOT_FOUND, logger); return; } try { // check that the user has at least READ_CONTENT access - else redirect to an error or login page if (!checkAccess(req, res, nodeRef, PermissionService.READ_CONTENT, allowLogIn)) { return; } // check If-Modified-Since header and set Last-Modified header as appropriate Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED); if (modified != null) { long modifiedSince = req.getDateHeader(HEADER_IF_MODIFIED_SINCE); 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) { if (logger.isDebugEnabled()) logger.debug("Returning 304 Not Modified."); res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } res.setDateHeader(HEADER_LAST_MODIFIED, modified.getTime()); res.setHeader(HEADER_CACHE_CONTROL, "must-revalidate, max-age=0"); res.setHeader(HEADER_ETAG, "\"" + Long.toString(modified.getTime()) + "\""); } if (attachment == true) { setHeaderContentDisposition(req, res, filename); } // get the content reader ContentReader reader = contentService.getReader(nodeRef, propertyQName); // ensure that it is safe to use reader = FileContentReader.getSafeContentReader(reader, Application.getMessage(req.getSession(), MSG_ERROR_CONTENT_MISSING), nodeRef, reader); String mimetype = reader.getMimetype(); // fall back if unable to resolve mimetype property if (mimetype == null || mimetype.length() == 0) { MimetypeService mimetypeMap = serviceRegistry.getMimetypeService(); mimetype = MIMETYPE_OCTET_STREAM; int extIndex = filename.lastIndexOf('.'); if (extIndex != -1) { String ext = filename.substring(extIndex + 1); mimetype = mimetypeMap.getMimetype(ext); } } // explicitly set the content disposition header if the content is powerpoint if (!attachment && (mimetype.equals(POWER_POINT_2007_DOCUMENT_MIMETYPE) || mimetype.equals(POWER_POINT_DOCUMENT_MIMETYPE))) { setHeaderContentDisposition(req, res, filename); } // get the content and stream directly to the response output stream // assuming the repo is capable of streaming in chunks, this should allow large files // to be streamed directly to the browser response stream. res.setHeader(HEADER_ACCEPT_RANGES, "bytes"); // for a GET request, transmit the content else just the headers are sent if (transmitContent) { try { boolean processedRange = false; String range = req.getHeader(HEADER_CONTENT_RANGE); if (range == null) { range = req.getHeader(HEADER_RANGE); } if (range != null) { if (logger.isDebugEnabled()) logger.debug("Found content range header: " + range); // ensure the range header is starts with "bytes=" and process the range(s) if (range.length() > 6) { HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(contentService); processedRange = rangeProcessor.processRange(res, reader, range.substring(6), nodeRef, propertyQName, mimetype, req.getHeader(HEADER_USER_AGENT)); } } if (processedRange == false) { if (logger.isDebugEnabled()) logger.debug("Sending complete file content..."); // set mimetype for the content and the character encoding for the stream res.setContentType(mimetype); res.setCharacterEncoding(reader.getEncoding()); // MNT-10642 Alfresco Explorer has javascript vulnerability opening HTML files if (req.getRequestURI().contains("/d/d/") && (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml") || mimetype.equals("text/xml"))) { String content = reader.getContentString(); if (mimetype.equals("text/html") || mimetype.equals("application/xhtml+xml")) { // process with HTML stripper content = StringUtils.stripUnsafeHTMLTags(content, false); } else if (mimetype.equals("text/xml") && mimetype.equals("text/x-component")) { // IE supports "behaviour" which means that css can load a .htc file that could // contain XSS code in the form of jscript, vbscript etc, to stop it form being // evaluated we set the contient type to text/plain res.setContentType("text/plain"); } String encoding = reader.getEncoding(); byte[] bytes = encoding != null ? content.getBytes(encoding) : content.getBytes(); res.setContentLength(bytes.length); res.getOutputStream().write(bytes); return; } // return the complete entity range long size = reader.getSize(); res.setHeader(HEADER_CONTENT_RANGE, "bytes 0-" + Long.toString(size - 1L) + "/" + Long.toString(size)); res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(size)); reader.getContent(res.getOutputStream()); } } catch (SocketException e1) { // the client cut the connection - our mission was accomplished apart from a little error message if (logger.isDebugEnabled()) logger.debug("Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader); } catch (ContentIOException e2) { if (logger.isInfoEnabled()) logger.info("Failed stream read:\n\tnode: " + nodeRef + " due to: " + e2.getMessage()); } catch (Throwable err) { if (err.getCause() instanceof SocketException) { // the client cut the connection - our mission was accomplished apart from a little error message if (logger.isDebugEnabled()) logger.debug( "Client aborted stream read:\n\tnode: " + nodeRef + "\n\tcontent: " + reader); } else throw err; } } else { if (logger.isDebugEnabled()) logger.debug("HEAD request processed - no content sent."); res.getOutputStream().close(); } } catch (Throwable err) { throw new AlfrescoRuntimeException( "Error during download content servlet processing: " + err.getMessage(), err); } }
From source file:org.opencastproject.workspace.impl.WorkspaceImpl.java
/** * {@inheritDoc}/*from www. j a v a2 s .c o m*/ * * @see org.opencastproject.workspace.api.Workspace#get(java.net.URI) */ public File get(final URI uri) throws NotFoundException, IOException { final String urlString = uri.toString(); final File f = getWorkspaceFile(uri, false); // Does the file exist and is it up to date? Long workspaceFileLastModified = new Long(0); // make sure this is not null, otherwise the requested file can not be // copied if (f.isFile()) { workspaceFileLastModified = new Long(f.lastModified()); } if (wfrRoot != null && wfrUrl != null) { if (uri.toString().startsWith(wfrUrl)) { String localPath = uri.toString().substring(wfrUrl.length()); File wfrCopy = new File(PathSupport.concat(wfrRoot, localPath)); if (wfrCopy.isFile()) { // if the file exists in the workspace, but is older than the wfr copy, replace it if (workspaceFileLastModified < wfrCopy.lastModified()) { logger.debug("Replacing {} with an updated version from the file repository", f.getAbsolutePath()); if (linkingEnabled) { FileUtils.deleteQuietly(f); FileSupport.link(wfrCopy, f); } else { FileSupport.copy(wfrCopy, f); } } else { logger.debug("{} is up to date", f); } logger.debug("Getting {} directly from working file repository root at {}", uri, f); return new File(f.getAbsolutePath()); } } } String ifNoneMatch = null; if (f.isFile()) { ifNoneMatch = md5(f); } final HttpGet get = new HttpGet(urlString); if (ifNoneMatch != null) get.setHeader("If-None-Match", ifNoneMatch); return locked(f, new Function<File, File>() { @Override public File apply(File file) { InputStream in = null; OutputStream out = null; HttpResponse response = null; try { response = trustedHttpClient.execute(get); if (HttpServletResponse.SC_NOT_FOUND == response.getStatusLine().getStatusCode()) { throw new NotFoundException(uri + " does not exist"); } else if (HttpServletResponse.SC_NOT_MODIFIED == response.getStatusLine().getStatusCode()) { logger.debug("{} has not been modified.", urlString); return file; } else if (HttpServletResponse.SC_ACCEPTED == response.getStatusLine().getStatusCode()) { logger.debug("{} is not ready, try again in one minute.", urlString); String token = response.getHeaders("token")[0].getValue(); get.setParams(new BasicHttpParams().setParameter("token", token)); Thread.sleep(60000); while (true) { response = trustedHttpClient.execute(get); if (HttpServletResponse.SC_NOT_FOUND == response.getStatusLine().getStatusCode()) { throw new NotFoundException(uri + " does not exist"); } else if (HttpServletResponse.SC_NOT_MODIFIED == response.getStatusLine() .getStatusCode()) { logger.debug("{} has not been modified.", urlString); return file; } else if (HttpServletResponse.SC_ACCEPTED == response.getStatusLine() .getStatusCode()) { logger.debug("{} is not ready, try again in one minute.", urlString); Thread.sleep(60000); } else if (HttpServletResponse.SC_OK == response.getStatusLine().getStatusCode()) { logger.info("Downloading {} to {}", urlString, file.getAbsolutePath()); file.createNewFile(); in = response.getEntity().getContent(); out = new FileOutputStream(file); IOUtils.copyLarge(in, out); return file; } else { logger.warn( "Received unexpected response status {} while trying to download from {}", response.getStatusLine().getStatusCode(), urlString); FileUtils.deleteQuietly(file); return chuck(new NotFoundException( "Unexpected response status " + response.getStatusLine().getStatusCode())); } } } else if (HttpServletResponse.SC_OK == response.getStatusLine().getStatusCode()) { logger.info("Downloading {} to {}", urlString, file.getAbsolutePath()); file.createNewFile(); in = response.getEntity().getContent(); out = new FileOutputStream(file); IOUtils.copyLarge(in, out); return file; } else { logger.warn("Received unexpected response status {} while trying to download from {}", response.getStatusLine().getStatusCode(), urlString); FileUtils.deleteQuietly(file); return chuck(new NotFoundException( "Unexpected response status " + response.getStatusLine().getStatusCode())); } } catch (Exception e) { logger.warn("Could not copy {} to {}: {}", new String[] { urlString, file.getAbsolutePath(), e.getMessage() }); FileUtils.deleteQuietly(file); return chuck(new NotFoundException(e)); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); trustedHttpClient.close(response); } } }); }
From source file:org.nuxeo.ecm.core.io.download.DownloadServiceImpl.java
@Override public void downloadBlob(HttpServletRequest request, HttpServletResponse response, DocumentModel doc, String xpath, Blob blob, String filename, String reason, Map<String, Serializable> extendedInfos, Boolean inline, Consumer<ByteRange> blobTransferer) throws IOException { Objects.requireNonNull(blob); // check blob permissions if (!checkPermission(doc, xpath, blob, reason, extendedInfos)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Permission denied"); return;// ww w . j a va 2 s . c o m } // check Blob Manager download link URI uri = redirectResolver.getURI(blob, UsageHint.DOWNLOAD, request); if (uri != null) { try { Map<String, Serializable> ei = new HashMap<>(); if (extendedInfos != null) { ei.putAll(extendedInfos); } ei.put("redirect", uri.toString()); logDownload(doc, xpath, filename, reason, ei); response.sendRedirect(uri.toString()); } catch (IOException ioe) { DownloadHelper.handleClientDisconnect(ioe); } return; } try { String digest = blob.getDigest(); if (digest == null) { digest = DigestUtils.md5Hex(blob.getStream()); } String etag = '"' + digest + '"'; // with quotes per RFC7232 2.3 response.setHeader("ETag", etag); // re-send even on SC_NOT_MODIFIED addCacheControlHeaders(request, response); String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null) { boolean match = false; if (ifNoneMatch.equals("*")) { match = true; } else { for (String previousEtag : StringUtils.split(ifNoneMatch, ", ")) { if (previousEtag.equals(etag)) { match = true; break; } } } if (match) { String method = request.getMethod(); if (method.equals("GET") || method.equals("HEAD")) { response.sendError(HttpServletResponse.SC_NOT_MODIFIED); } else { // per RFC7232 3.2 response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); } return; } } // regular processing if (StringUtils.isBlank(filename)) { filename = StringUtils.defaultIfBlank(blob.getFilename(), "file"); } String contentDisposition = DownloadHelper.getRFC2231ContentDisposition(request, filename, inline); response.setHeader("Content-Disposition", contentDisposition); response.setContentType(blob.getMimeType()); if (blob.getEncoding() != null) { response.setCharacterEncoding(blob.getEncoding()); } long length = blob.getLength(); response.setHeader("Accept-Ranges", "bytes"); String range = request.getHeader("Range"); ByteRange byteRange; if (StringUtils.isBlank(range)) { byteRange = null; } else { byteRange = DownloadHelper.parseRange(range, length); if (byteRange == null) { log.error("Invalid byte range received: " + range); } else { response.setHeader("Content-Range", "bytes " + byteRange.getStart() + "-" + byteRange.getEnd() + "/" + length); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); } } long contentLength = byteRange == null ? length : byteRange.getLength(); if (contentLength < Integer.MAX_VALUE) { response.setContentLength((int) contentLength); } logDownload(doc, xpath, filename, reason, extendedInfos); // execute the final download blobTransferer.accept(byteRange); } catch (UncheckedIOException e) { DownloadHelper.handleClientDisconnect(e.getCause()); } catch (IOException ioe) { DownloadHelper.handleClientDisconnect(ioe); } }
From source file:org.dspace.app.rest.utils.MultipartFileSenderTest.java
/** * Test if the Modified Since precondition works, should return 304 if it hasn't been modified * * @throws Exception/* ww w . ja v a 2 s .c o m*/ */ @Test public void testIfModifiedSinceNotModifiedSince() throws Exception { Long time = new Date().getTime(); MultipartFileSender multipartFileSender = MultipartFileSender.fromInputStream(is).with(requestWrapper) .withFileName(fileName).with(responseWrapper).withChecksum(checksum).withMimetype(mimeType) .withLength(length).withLastModified(time); when(request.getDateHeader(eq("If-Modified-Since"))).thenReturn(time + 100000); when(request.getDateHeader(eq("If-Unmodified-Since"))).thenReturn(-1L); multipartFileSender.isValid(); assertEquals(HttpServletResponse.SC_NOT_MODIFIED, responseWrapper.getStatusCode()); }