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.openmrs.module.patientnarratives.web.servlet.FileServlet.java
/** * Process the actual request./* w ww . j a v a 2s . c o m*/ * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------------------------------ Integer videoObsId = Integer.parseInt(request.getParameter("obsId")); Obs complexObs = Context.getObsService().getComplexObs(videoObsId, OpenmrsConstants.RAW_VIEW); ComplexData complexData = complexObs.getComplexData(); byte[] videoObjectData = ((byte[]) complexData.getData()); String fileExt_file = complexData.getTitle(); String arrFileExt[] = fileExt_file.split(" "); tempMergedVideoFile = createFile(arrFileExt[0]); String requestedFile = tempMergedVideoFile.getCanonicalPath(); FileUtils.writeByteArrayToFile(new File(requestedFile), videoObjectData); // Check if file is actually supplied to the request URL. if (requestedFile == null) { // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // URL-decode the file name (might contain spaces and on) and prepare file object. File file = new File(requestedFile); // Check if file actually exists in filesystem. if (!file.exists()) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // 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 + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); tempMergedVideoFile.delete(); } }
From source file:org.restcomm.connect.http.filters.FileCacheServlet.java
/** * Process the actual request./* ww w.j a va2 s . c o m*/ * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not * (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------------------------------ // Get requested file by path info. String requestedFile = request.getPathInfo(); if (logger.isDebugEnabled()) { logger.debug("Requested path:" + requestedFile); } // Check if file is actually supplied to the request URL. if (requestedFile == null) { logger.debug("No file requested, return 404."); // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Configuration rootConfiguration = (Configuration) request.getServletContext() .getAttribute(Configuration.class.getName()); Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings"); String basePath = runtimeConfiguration.getString("cache-path"); int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE); long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME); // URL-decode the file name (might contain spaces and on) and prepare file object. String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8"); File file = new File(basePath, fDecodedPath); // Check if file actually exists in filesystem. if (!file.exists()) { logger.debug("Requested file not found, return 404."); // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + expireTime; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { logger.debug("IfNoneMatch/Etag not matching, return 304."); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // 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 + 1000 > lastModified) { logger.debug("IfModifiedSince not matching, return 304."); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { logger.debug("ifMatch not matching, return 412."); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { logger.debug("ifUnmodifiedSince not matching, return 412."); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and content disposition. String contentType = getServletContext().getMimeType(fileName); String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, expand content type with the one and right character encoding. if (contentType.startsWith("text")) { contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(bufferSize); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. FileInputStream input = null; OutputStream output = null; if (content) { logger.debug("Content requested,streaming."); // Open streams. input = new FileInputStream(file); output = response.getOutputStream(); long streamed = stream(input, output, bufferSize); if (logger.isDebugEnabled()) { logger.debug("Bytes streamed:" + streamed); } } }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Check if the if-modified-since condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param folder the folder object//ww w. jav a 2 s .com * @return boolean true if the resource meets the specified condition, and * false if the condition is not satisfied, in which case request * processing is stopped */ public boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, Folder folder) { try { long headerValue = request.getDateHeader("If-Modified-Since"); long lastModified = folder.getAuditInfo().getModificationDate().getTime(); if (headerValue != -1) // If an If-None-Match header has been specified, if modified // since is ignored. if (request.getHeader("If-None-Match") == null && lastModified < headerValue + 1000) { // The entity has not been modified since the date // specified by the client. This is not an error case. response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return false; } } catch (IllegalArgumentException illegalArgument) { return true; } return true; }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Check if the if-modified-since condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param file the file object//from w w w. ja v a 2 s . com * @param oldBody the old version of the file, if requested * @return boolean true if the resource meets the specified condition, and * false if the condition is not satisfied, in which case request * processing is stopped */ private boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, FileHeader file, FileBody oldBody) { try { long headerValue = request.getDateHeader("If-Modified-Since"); long lastModified = oldBody == null ? file.getAuditInfo().getModificationDate().getTime() : oldBody.getAuditInfo().getModificationDate().getTime(); if (headerValue != -1) // If an If-None-Match header has been specified, if modified // since is ignored. if (request.getHeader("If-None-Match") == null && lastModified < headerValue + 1000) { // The entity has not been modified since the date // specified by the client. This is not an error case. response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", getETag(file, oldBody)); return false; } } catch (IllegalArgumentException illegalArgument) { return true; } return true; }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Check if the if-unmodified-since condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param file the file object//from w ww. j av a2 s . c om * @param oldBody the old version of the file, if requested * @return boolean true if the resource meets the specified condition, and * false if the condition is not satisfied, in which case request * processing is stopped * @throws IOException */ private boolean checkIfUnmodifiedSince(HttpServletRequest request, HttpServletResponse response, FileHeader file, FileBody oldBody) throws IOException { try { long lastModified = oldBody == null ? file.getAuditInfo().getModificationDate().getTime() : oldBody.getAuditInfo().getModificationDate().getTime(); long headerValue = request.getDateHeader("If-Unmodified-Since"); if (headerValue != -1) if (lastModified >= headerValue + 1000) { // The entity has not been modified since the date // specified by the client. This is not an error case. response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } catch (IllegalArgumentException illegalArgument) { return true; } return true; }
From source file:org.dspace.app.webui.servlet.HandleServlet.java
protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String handle = null;//ww w . ja v a 2 s .c o m String extraPathInfo = null; DSpaceObject dso = null; // Original path info, of the form "1721.x/1234" // or "1721.x/1234/extra/stuff" String path = request.getPathInfo(); if (path != null) { // substring(1) is to remove initial '/' path = path.substring(1); try { // Extract the Handle int firstSlash = path.indexOf('/'); int secondSlash = path.indexOf('/', firstSlash + 1); if (secondSlash != -1) { // We have extra path info handle = path.substring(0, secondSlash); extraPathInfo = path.substring(secondSlash); } else { // The path is just the Handle handle = path; } } catch (NumberFormatException nfe) { // Leave handle as null } } // Find out what the handle relates to if (handle != null) { dso = HandleManager.resolveToObject(context, handle); } if (dso == null) { log.info(LogManager.getHeader(context, "invalid_id", "path=" + path)); JSPManager.showInvalidIDError(request, response, StringEscapeUtils.escapeHtml(path), -1); return; } if ("/statistics".equals(extraPathInfo)) { // Check configuration properties, auth, etc. // Inject handle attribute log.info(LogManager.getHeader(context, "display_statistics", "handle=" + handle + ", path=" + extraPathInfo)); request.setAttribute("handle", handle); // Forward to DisplayStatisticsServlet without changing path. RequestDispatcher dispatch = getServletContext().getNamedDispatcher("displaystats"); dispatch.forward(request, response); // If we don't return here, we keep processing and end up // throwing a NPE when checking community authorization // and firing a usage event for the DSO we're reporting for return; } // OK, we have a valid Handle. What is it? if (dso.getType() == Constants.ITEM) { // do we actually want to display the item, or forward to another page? if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) { Item item = (Item) dso; // Only use last-modified if this is an anonymous access // - caching content that may be generated under authorisation // is a security problem if (context.getCurrentUser() == null) { response.setDateHeader("Last-Modified", item.getLastModified().getTime()); // Check for if-modified-since header long modSince = request.getDateHeader("If-Modified-Since"); if (modSince != -1 && item.getLastModified().getTime() < modSince) { // Item has not been modified since requested date, // hence bitstream has not been, either; return 304 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { // Display the item page displayItem(context, request, response, item, handle); } } else { // Display the item page displayItem(context, request, response, item, handle); } } else { // Forward to another servlet request.getRequestDispatcher(extraPathInfo).forward(request, response); } } else if (dso.getType() == Constants.COLLECTION) { Collection c = (Collection) dso; // Store collection location in request request.setAttribute("dspace.collection", c); /* * Find the "parent" community the collection, mainly for * "breadcrumbs" FIXME: At the moment, just grab the first community * the collection is in. This should probably be more context * sensitive when we have multiple inclusion. */ Community[] parents = c.getCommunities(); request.setAttribute("dspace.community", parents[0]); /* * Find all the "parent" communities for the collection for * "breadcrumbs" */ request.setAttribute("dspace.communities", getParents(parents[0], true)); // home page, or forward to another page? if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) { collectionHome(context, request, response, parents[0], c); } else { // Forward to another servlet request.getRequestDispatcher(extraPathInfo).forward(request, response); } } else if (dso.getType() == Constants.COMMUNITY) { Community c = (Community) dso; // Store collection location in request request.setAttribute("dspace.community", c); /* * Find all the "parent" communities for the community */ request.setAttribute("dspace.communities", getParents(c, false)); // home page, or forward to another page? if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) { communityHome(context, request, response, c); } else { // Forward to another servlet request.getRequestDispatcher(extraPathInfo).forward(request, response); } } else { // Shouldn't happen. Log and treat as invalid ID log.info(LogManager.getHeader(context, "Handle not an item, collection or community", "handle=" + handle)); JSPManager.showInvalidIDError(request, response, StringEscapeUtils.escapeHtml(path), -1); return; } }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Parse the range header.// www. j av a2 s . c o m * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param file * @param oldBody the old version of the file, if requested * @return Vector of ranges * @throws IOException */ protected ArrayList parseRange(HttpServletRequest request, HttpServletResponse response, FileHeader file, FileBody oldBody) throws IOException { // Checking If-Range String headerValue = request.getHeader("If-Range"); if (headerValue != null) { long headerValueTime = -1L; try { headerValueTime = request.getDateHeader("If-Range"); } catch (IllegalArgumentException e) { // Do nothing. } String eTag = getETag(file, oldBody); long lastModified = oldBody == null ? file.getAuditInfo().getModificationDate().getTime() : oldBody.getAuditInfo().getModificationDate().getTime(); if (headerValueTime == -1L) { // If the ETag the client gave does not match the entity // etag, then the entire entity is returned. if (!eTag.equals(headerValue.trim())) return FULL; } else // If the timestamp of the entity the client got is older than // the last modification date of the entity, the entire entity // is returned. if (lastModified > headerValueTime + 1000) return FULL; } long fileLength = oldBody == null ? file.getCurrentBody().getFileSize() : oldBody.getFileSize(); if (fileLength == 0) return null; // Retrieving the range header (if any is specified). String rangeHeader = request.getHeader("Range"); if (rangeHeader == null) return null; // bytes is the only range unit supported (and I don't see the point // of adding new ones). if (!rangeHeader.startsWith("bytes")) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } rangeHeader = rangeHeader.substring(6); // Vector that will contain all the ranges which are successfully // parsed. ArrayList<Range> result = new ArrayList<Range>(); StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ","); // Parsing the range list while (commaTokenizer.hasMoreTokens()) { String rangeDefinition = commaTokenizer.nextToken().trim(); Range currentRange = new Range(); currentRange.length = fileLength; int dashPos = rangeDefinition.indexOf('-'); if (dashPos == -1) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } if (dashPos == 0) try { long offset = Long.parseLong(rangeDefinition); currentRange.start = fileLength + offset; currentRange.end = fileLength - 1; } catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } else try { currentRange.start = Long.parseLong(rangeDefinition.substring(0, dashPos)); if (dashPos < rangeDefinition.length() - 1) currentRange.end = Long .parseLong(rangeDefinition.substring(dashPos + 1, rangeDefinition.length())); else currentRange.end = fileLength - 1; } catch (NumberFormatException e) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } if (!currentRange.validate()) { response.addHeader("Content-Range", "bytes */" + fileLength); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } result.add(currentRange); } return result; }
From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java
protected void processAggregatorRequest(HttpServletRequest req, HttpServletResponse resp) { final String sourceMethod = "processAggregatorRequest"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { req, resp }); }//from w w w .j a v a 2s . co m req.setAttribute(AGGREGATOR_REQATTRNAME, this); ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>(); req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap); try { // Validate config last-modified if development mode is enabled if (getOptions().isDevelopmentMode()) { long lastModified = -1; URI configUri = getConfig().getConfigUri(); if (configUri != null) { try { // try to get platform URI from IResource in case uri specifies // aggregator specific scheme like namedbundleresource configUri = newResource(configUri).getURI(); } catch (UnsupportedOperationException e) { // Not fatal. Just use uri as specified. } lastModified = configUri.toURL().openConnection().getLastModified(); } if (lastModified > getConfig().lastModified()) { if (reloadConfig()) { // If the config has been modified, then dependencies will be revalidated // asynchronously. Rather than forcing the current request to wait, return // a response that will display an alert informing the user of what is // happening and asking them to reload the page. String content = "alert('" + //$NON-NLS-1$ StringUtil.escapeForJavaScript(Messages.ConfigModified) + "');"; //$NON-NLS-1$ resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$ CopyUtil.copy(new StringReader(content), resp.getOutputStream()); return; } } } getTransport().decorateRequest(req); notifyRequestListeners(RequestNotifierAction.start, req, resp); ILayer layer = getLayer(req); long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$ long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req)) / 1000) * 1000; if (modifiedSince >= lastModified) { if (log.isLoggable(Level.FINER)) { log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$ getName() + ":" //$NON-NLS-1$ + req.getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME).toString()); } resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { // Get the InputStream for the response. This call sets the Content-Type, // Content-Length and Content-Encoding headers in the response. InputStream in = layer.getInputStream(req, resp); // if any of the readers included an error response, then don't cache the layer. if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) { resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$ } else { resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$ int expires = getConfig().getExpires(); resp.addHeader("Cache-Control", //$NON-NLS-1$ "public" + (expires > 0 ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ); } CopyUtil.copy(in, resp.getOutputStream()); } notifyRequestListeners(RequestNotifierAction.end, req, resp); } catch (DependencyVerificationException e) { // clear the cache now even though it will be cleared when validateDeps has // finished (asynchronously) so that any new requests will be forced to wait // until dependencies have been validated. getCacheManager().clearCache(); getDependencies().validateDeps(false); resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$ if (getOptions().isDevelopmentMode()) { String msg = StringUtil.escapeForJavaScript(MessageFormat.format(Messages.DepVerificationFailed, new Object[] { e.getMessage(), "aggregator " + //$NON-NLS-1$ "validatedeps " + //$NON-NLS-1$ getName() + " clean", //$NON-NLS-1$ getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$ })); String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$ try { CopyUtil.copy(new StringReader(content), resp.getOutputStream()); } catch (IOException e1) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, e1.getMessage(), e1); } resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } catch (ProcessingDependenciesException e) { resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$ if (getOptions().isDevelopmentMode()) { String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$ try { CopyUtil.copy(new StringReader(content), resp.getOutputStream()); } catch (IOException e1) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, e1.getMessage(), e1); } resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } catch (BadRequestException e) { exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST); } catch (NotFoundException e) { exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND); } catch (Exception e) { exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { concurrentMap.clear(); } if (isTraceLogging) { log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod); } }
From source file:org.opencms.webdav.CmsWebdavServlet.java
/** * Parse the range header.<p>//from w ww.jav a 2 s . c om * * @param request the servlet request we are processing * @param response the servlet response we are creating * @param item the WebdavItem with the information * * @return Vector of ranges */ protected ArrayList<CmsWebdavRange> parseRange(HttpServletRequest request, HttpServletResponse response, I_CmsRepositoryItem item) { // Checking If-Range String headerValue = request.getHeader(HEADER_IFRANGE); if (headerValue != null) { long headerValueTime = (-1L); try { headerValueTime = request.getDateHeader(HEADER_IFRANGE); } catch (Exception e) { // noop } String eTag = getETag(item); long lastModified = item.getLastModifiedDate(); if (headerValueTime == (-1L)) { // If the ETag the client gave does not match the entity // etag, then the entire entity is returned. if (!eTag.equals(headerValue.trim())) { return FULL_RANGE; } } else { // If the timestamp of the entity the client got is older than // the last modification date of the entity, the entire entity // is returned. if (lastModified > (headerValueTime + 1000)) { return FULL_RANGE; } } } long fileLength = item.getContentLength(); if (fileLength == 0) { return null; } // Retrieving the range header (if any is specified String rangeHeader = request.getHeader(HEADER_RANGE); if (rangeHeader == null) { return null; } // bytes is the only range unit supported (and I don't see the point // of adding new ones). if (!rangeHeader.startsWith("bytes")) { response.addHeader(HEADER_CONTENTRANGE, "bytes */" + fileLength); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } rangeHeader = rangeHeader.substring(6); // Vector which will contain all the ranges which are successfully parsed. ArrayList<CmsWebdavRange> result = new ArrayList<CmsWebdavRange>(); StringTokenizer commaTokenizer = new StringTokenizer(rangeHeader, ","); // Parsing the range list while (commaTokenizer.hasMoreTokens()) { String rangeDefinition = commaTokenizer.nextToken().trim(); CmsWebdavRange currentRange = new CmsWebdavRange(); currentRange.setLength(fileLength); int dashPos = rangeDefinition.indexOf('-'); if (dashPos == -1) { response.addHeader(HEADER_CONTENTRANGE, "bytes */" + fileLength); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } if (dashPos == 0) { try { long offset = Long.parseLong(rangeDefinition); currentRange.setStart(fileLength + offset); currentRange.setEnd(fileLength - 1); } catch (NumberFormatException e) { response.addHeader(HEADER_CONTENTRANGE, "bytes */" + fileLength); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } } else { try { currentRange.setStart(Long.parseLong(rangeDefinition.substring(0, dashPos))); if (dashPos < (rangeDefinition.length() - 1)) { currentRange.setEnd( Long.parseLong(rangeDefinition.substring(dashPos + 1, rangeDefinition.length()))); } else { currentRange.setEnd(fileLength - 1); } } catch (NumberFormatException e) { response.addHeader(HEADER_CONTENTRANGE, "bytes */" + fileLength); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } } if (!currentRange.validate()) { response.addHeader(HEADER_CONTENTRANGE, "bytes */" + fileLength); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return null; } result.add(currentRange); } return result; }
From source file:org.apache.myfaces.renderkit.html.util.MyFacesResourceLoader.java
/** * Given a URI of form "{partial.class.name}/{resourceName}", locate the * specified file within the current classpath and write it to the * response object.//ww w .j a va 2 s . co m * <p> * The partial class name has "org.apache.myfaces.custom." prepended * to it to form the fully qualified classname. This class object is * loaded, and Class.getResourceAsStream is called on it, passing * a uri of "resource/" + {resourceName}. * <p> * The data written to the response stream includes http headers * which define the mime content-type; this is deduced from the * filename suffix of the resource. * <p> * @see org.apache.myfaces.renderkit.html.util.ResourceLoader#serveResource(javax.servlet.ServletContext, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String) */ public void serveResource(ServletContext context, HttpServletRequest request, HttpServletResponse response, String resourceUri) throws IOException { String[] uriParts = resourceUri.split("/", 2); String component = uriParts[0]; if (component == null || component.trim().length() == 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request"); log.error("Could not find parameter for component to load a resource."); return; } Class componentClass; String className = ORG_APACHE_MYFACES_CUSTOM + "." + component; try { componentClass = loadComponentClass(className); } catch (ClassNotFoundException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); log.error("Could not find the class for component " + className + " to load a resource."); return; } String resource = uriParts[1]; if (resource == null || resource.trim().length() == 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No resource defined"); log.error("No resource defined component class " + className); return; } InputStream is = null; try { ResourceProvider resourceProvider; if (ResourceProvider.class.isAssignableFrom(componentClass)) { try { resourceProvider = (ResourceProvider) componentClass.newInstance(); } catch (InstantiationException e) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Unable to instantiate resource provider for resource " + resource + " for component " + component); log.error("Unable to instantiate resource provider for resource " + resource + " for component " + component, e); return; } catch (IllegalAccessException e) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Unable to instantiate resource provider for resource " + resource + " for component " + component); log.error("Unable to instantiate resource provider for resource " + resource + " for component " + component, e); return; } } else { resourceProvider = new DefaultResourceProvider(componentClass); } if (!resourceProvider.exists(context, resource)) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unable to find resource " + resource + " for component " + component + ". Check that this file is available " + "in the classpath in sub-directory " + "/resource of the package-directory."); log.error("Unable to find resource " + resource + " for component " + component + ". Check that this file is available " + "in the classpath in sub-directory " + "/resource of the package-directory."); } else { // URLConnection con = url.openConnection(); long lastModified = resourceProvider.getLastModified(context, resource); if (lastModified < 1) { // fallback lastModified = getLastModified(); } long browserDate = request.getDateHeader("If-Modified-Since"); if (browserDate > -1) { // normalize to seconds - this should work with any os lastModified = (lastModified / 1000) * 1000; browserDate = (browserDate / 1000) * 1000; if (lastModified == browserDate) { // the browser already has the correct version response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED); return; } } int contentLength = resourceProvider.getContentLength(context, resource); String contentEncoding = resourceProvider.getEncoding(context, resource); is = resourceProvider.getInputStream(context, resource); defineContentHeaders(request, response, resource, contentLength, contentEncoding); defineCaching(request, response, resource, lastModified); writeResource(request, response, is); } } finally { // nothing to do here.. } }