List of usage examples for javax.servlet.http HttpServletResponse SC_PRECONDITION_FAILED
int SC_PRECONDITION_FAILED
To view the source code for javax.servlet.http HttpServletResponse SC_PRECONDITION_FAILED.
Click Source Link
From source file:org.dataconservancy.dcs.util.http.RequestHeaderUtil.java
/** * Implementation of RFC 2616 14.26// w w w .j a v a 2 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:org.openmrs.module.patientnarratives.web.servlet.FileServlet.java
/** * Process the actual request./*from w ww. j a v a 2 s . c om*/ * @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./*from w w w. jav a 2 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:io.github.gsteckman.rpi_rest.SubscriptionManager.java
/** * Processes a UPnP UNSUBSCRIBE request and removes a subscription. * //from ww w . j a va 2 s .c o m * @param key * The key identifies the resource to which the subscription applies. * @param req * HTTP request * @param res * Response to the request * @throws IOException * Thrown by HttpServletResponse.sendError if an error occurs writing the response. */ public void processUnsubscribe(String key, HttpServletRequest req, HttpServletResponse res) throws IOException { String timeoutHdr = req.getHeader("TIMEOUT"); String callbackHdr = req.getHeader("CALLBACK"); String sidHdr = req.getHeader("SID"); // Perform error checking: // 1. Method must be UNSUBSCRIBE // 2. SID header must be present // 3. NT and CALLBACK headers not present if (!"UNSUBSCRIBE".equalsIgnoreCase(req.getMethod())) { // Return 405 status res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Method " + req.getMethod() + " not allowed for this resource."); return; } if (sidHdr == null || sidHdr.length() == 0) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "SID header field is missing or empty."); } if (timeoutHdr != null || callbackHdr != null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "An SID header field and one of NT or CALLBACK header fields are present."); return; } Map<UUID, SubscriptionInfo> m = subscriptions.get(key); if (m == null) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "SID doesn't correspond to a known subscription."); return; } // parse SID & remove subscription String ss = sidHdr.substring(5).trim(); UUID sid = new UUID(ss); if (m.remove(sid) == null) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "SID doesn't correspond to a known subscription."); return; } }
From source file:org.purl.sword.server.DepositServlet.java
/** * Process a post request.// w w w . j av a2 s . co m */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create the Deposit request Deposit d = new Deposit(); Date date = new Date(); log.debug("Starting deposit processing at " + date.toString() + " by " + request.getRemoteAddr()); // Are there any authentication details? String usernamePassword = getUsernamePassword(request); if ((usernamePassword != null) && (!usernamePassword.equals(""))) { int p = usernamePassword.indexOf(':'); if (p != -1) { d.setUsername(usernamePassword.substring(0, p)); d.setPassword(usernamePassword.substring(p + 1)); } } else if (authenticateWithBasic()) { String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(401); return; } // Set up some variables String filename = null; // Do the processing try { // Write the file to the temp directory filename = tempDirectory + "SWORD-" + request.getRemoteAddr() + "-" + counter.addAndGet(1); log.debug("Package temporarily stored as: " + filename); InputStream inputstream = request.getInputStream(); OutputStream outputstream = new FileOutputStream(new File(filename)); try { byte[] buf = new byte[1024]; int len; while ((len = inputstream.read(buf)) > 0) { outputstream.write(buf, 0, len); } } finally { inputstream.close(); outputstream.close(); } // Check the size is OK File file = new File(filename); long fLength = file.length() / 1024; if ((maxUploadSize != -1) && (fLength > maxUploadSize)) { this.makeErrorDocument(ErrorCodes.MAX_UPLOAD_SIZE_EXCEEDED, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "The uploaded file exceeded the maximum file size this server will accept (the file is " + fLength + "kB but the server will only accept files as large as " + maxUploadSize + "kB)", request, response); return; } // Check the MD5 hash String receivedMD5 = ChecksumUtils.generateMD5(filename); log.debug("Received filechecksum: " + receivedMD5); d.setMd5(receivedMD5); String md5 = request.getHeader("Content-MD5"); log.debug("Received file checksum header: " + md5); if ((md5 != null) && (!md5.equals(receivedMD5))) { // Return an error document this.makeErrorDocument(ErrorCodes.ERROR_CHECKSUM_MISMATCH, HttpServletResponse.SC_PRECONDITION_FAILED, "The received MD5 checksum for the deposited file did not match the checksum sent by the deposit client", request, response); log.debug("Bad MD5 for file. Aborting with appropriate error message"); return; } else { // Set the file to be deposited d.setFile(file); // Set the X-On-Behalf-Of header String onBehalfOf = request.getHeader(HttpHeaders.X_ON_BEHALF_OF.toString()); if ((onBehalfOf != null) && (onBehalfOf.equals("reject"))) { // user name is "reject", so throw a not know error to allow the client to be tested throw new SWORDErrorException(ErrorCodes.TARGET_OWNER_UKNOWN, "unknown user \"reject\""); } else { d.setOnBehalfOf(onBehalfOf); } // Set the X-Packaging header d.setPackaging(request.getHeader(HttpHeaders.X_PACKAGING)); // Set the X-No-Op header String noop = request.getHeader(HttpHeaders.X_NO_OP); log.error("X_NO_OP value is " + noop); if ((noop != null) && (noop.equals("true"))) { d.setNoOp(true); } else if ((noop != null) && (noop.equals("false"))) { d.setNoOp(false); } else if (noop == null) { d.setNoOp(false); } else { throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST, "Bad no-op"); } // Set the X-Verbose header String verbose = request.getHeader(HttpHeaders.X_VERBOSE); if ((verbose != null) && (verbose.equals("true"))) { d.setVerbose(true); } else if ((verbose != null) && (verbose.equals("false"))) { d.setVerbose(false); } else if (verbose == null) { d.setVerbose(false); } else { throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST, "Bad verbose"); } // Set the slug String slug = request.getHeader(HttpHeaders.SLUG); if (slug != null) { d.setSlug(slug); } // Set the content disposition d.setContentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION)); // Set the IP address d.setIPAddress(request.getRemoteAddr()); // Set the deposit location d.setLocation(getUrl(request)); // Set the content type d.setContentType(request.getContentType()); // Set the content length String cl = request.getHeader(HttpHeaders.CONTENT_LENGTH); if ((cl != null) && (!cl.equals(""))) { d.setContentLength(Integer.parseInt(cl)); } // Get the DepositResponse DepositResponse dr = myRepository.doDeposit(d); // Echo back the user agent if (request.getHeader(HttpHeaders.USER_AGENT.toString()) != null) { dr.getEntry().setUserAgent(request.getHeader(HttpHeaders.USER_AGENT.toString())); } // Echo back the packaging format if (request.getHeader(HttpHeaders.X_PACKAGING.toString()) != null) { dr.getEntry().setPackaging(request.getHeader(HttpHeaders.X_PACKAGING.toString())); } // Print out the Deposit Response response.setStatus(dr.getHttpResponse()); if ((dr.getLocation() != null) && (!dr.getLocation().equals(""))) { response.setHeader("Location", dr.getLocation()); } response.setContentType("application/atom+xml; charset=UTF-8"); PrintWriter out = response.getWriter(); out.write(dr.marshall()); out.flush(); } } catch (SWORDAuthenticationException sae) { // Ask for credentials again if (authN.equals("Basic")) { String s = "Basic realm=\"SWORD\""; response.setHeader("WWW-Authenticate", s); response.setStatus(401); } } catch (SWORDErrorException see) { // Get the details and send the right SWORD error document log.error(see.toString()); this.makeErrorDocument(see.getErrorURI(), see.getStatus(), see.getDescription(), request, response); return; } catch (SWORDException se) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error(se.toString()); } catch (NoSuchAlgorithmException nsae) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error(nsae.toString()); } finally { // Try deleting the temp file if (filename != null) { File f = new File(filename); if (f != null && !f.delete()) { log.error("Unable to delete file: " + filename); } } } }
From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java
@Override public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, IFileStore file) throws ServletException { try {//from w w w . j a va2s . c o m String receivedETag = request.getHeader(ProtocolConstants.HEADER_IF_MATCH); if (receivedETag != null && !receivedETag.equals(generateFileETag(file))) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return true; } String parts = IOUtilities.getQueryParameter(request, "parts"); if (parts == null || "body".equals(parts)) { //$NON-NLS-1$ switch (getMethod(request)) { case DELETE: file.delete(EFS.NONE, null); break; case PUT: handlePutContents(request, request.getReader(), response, file); break; case POST: if ("PATCH".equals(request.getHeader(ProtocolConstants.HEADER_METHOD_OVERRIDE))) { handlePatchContents(request, request.getReader(), response, file); } break; default: return handleFileContents(request, response, file); } return true; } if ("meta".equals(parts)) { //$NON-NLS-1$ switch (getMethod(request)) { case GET: response.setCharacterEncoding("UTF-8"); handleGetMetadata(request, response, response.getWriter(), file); return true; case PUT: handlePutMetadata(request.getReader(), null, file); response.setStatus(HttpServletResponse.SC_NO_CONTENT); return true; } return false; } if ("meta,body".equals(parts) || "body,meta".equals(parts)) { //$NON-NLS-1$ //$NON-NLS-2$ switch (getMethod(request)) { case GET: handleMultiPartGet(request, response, file); return true; case PUT: handleMultiPartPut(request, response, file); return true; } return false; } } catch (JSONException e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Syntax error in request", e)); } catch (Exception e) { if (!handleAuthFailure(request, response, e)) throw new ServletException(NLS.bind("Error retrieving file: {0}", file), e); } return false; }
From source file:org.eclipse.orion.internal.server.servlets.file.DirectoryHandlerV1.java
/** * Perform a copy or move as specified by the request. * @return <code>true</code> if the operation was successful, and <code>false</code> otherwise. *///from w w w. j ava 2 s . c om private boolean performCopyMove(HttpServletRequest request, HttpServletResponse response, JSONObject requestObject, IFileStore toCreate, boolean isCopy, int options) throws ServletException, CoreException { String locationString = requestObject.optString(ProtocolConstants.KEY_LOCATION, null); if (locationString == null) { statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Copy or move request must specify source location", null)); return false; } try { IFileStore source = resolveSourceLocation(request, locationString); if (source == null) { statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("Source does not exist: ", locationString), null)); return false; } boolean allowOverwrite = (options & CREATE_NO_OVERWRITE) == 0; int efsOptions = allowOverwrite ? EFS.OVERWRITE : EFS.NONE; try { if (isCopy) source.copy(toCreate, efsOptions, null); else source.move(toCreate, efsOptions, null); } catch (CoreException e) { if (!source.fetchInfo(EFS.NONE, null).exists()) { statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("Source does not exist: ", locationString), e)); return false; } if (e.getStatus().getCode() == EFS.ERROR_EXISTS) { statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_PRECONDITION_FAILED, "A file or folder with the same name already exists at this location", null)); return false; } //just rethrow if we can't do something more specific throw e; } } catch (URISyntaxException e) { statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Bad source location in request: ", locationString), e)); return false; } return true; }
From source file:org.messic.server.facade.controllers.rest.SongController.java
@ApiMethod(path = "/services/songs/{songSid}/audio", verb = ApiVerb.GET, description = "Get the audio binary from a song resource of an album", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE }) @ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"), @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"), @ApiError(code = IOMessicRESTException.VALUE, description = "IO error trying to get the audio resource") }) @RequestMapping(value = "/{songSid}/audio", method = { RequestMethod.GET, RequestMethod.HEAD }) @ResponseStatus(HttpStatus.OK)/*from w w w .j av a 2 s .c o m*/ public void getSongWithRanges( @ApiParam(name = "songSid", description = "SID of the song resource we want to download", paramType = ApiParamType.PATH, required = true) @PathVariable Long songSid, HttpServletRequest request, HttpServletResponse response) throws NotAuthorizedMessicRESTException, IOMessicRESTException, UnknownMessicRESTException { User user = SecurityUtil.getCurrentUser(); try { //http://balusc.blogspot.com.es/2009/02/fileservlet-supporting-resume-and.html // Whether the request body should be written (GET) or not (HEAD). boolean content = request.getMethod().equalsIgnoreCase("GET"); APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid); // Validate and process Range and If-Range headers. String eTag = songSid + "_" + ass.contentLength + "_" + ass.lastModified; long expires = System.currentTimeMillis() + Range.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 && Range.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 > ass.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 && !Range.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 <= ass.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, ass.contentLength - 1, ass.contentLength); List<Range> ranges = new ArrayList<Range>(); 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 */" + ass.contentLength); // 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 < ass.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 = Range.sublong(part, 0, part.indexOf("-")); long end = Range.sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = ass.contentLength - end; end = ass.contentLength - 1; } else if (end == -1 || end > ass.contentLength - 1) { end = ass.contentLength - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + ass.contentLength); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, ass.contentLength)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = "audio/mpeg"; 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 && Range.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 && Range.accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(Range.DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + ass.songFileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", ass.lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. OutputStream output = null; try { // Open streams. 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, Range.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. Range.copy(ass.raf, 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. Range.copy(ass.raf, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + Range.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("--" + Range.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. Range.copy(ass.raf, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + Range.MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. Range.close(output); Range.close(ass.is); Range.close(ass.raf); } return; } catch (IOException ioe) { log.error("failed!", ioe); throw new IOMessicRESTException(ioe); } catch (Exception e) { throw new UnknownMessicRESTException(e); } }
From source file:com.epam.catgenome.controller.util.MultipartFileSender.java
private boolean validateHeadersResume(String fileName, long lastModified) throws IOException { // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; }//from w w w . j a v a2 s.c o m // 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 + CONSTANT_1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } return true; }
From source file:jp.aegif.alfresco.online_webdav.GetMethod.java
/** * Checks the If header conditions//from w w w . j a va 2s.c om * * @param nodeInfo the node to check * @throws WebDAVServerException if a pre-condition is not met */ private void checkPreConditions(FileInfo nodeInfo) throws WebDAVServerException { // Make an etag for the node String strETag = getDAVHelper().makeQuotedETag(nodeInfo); TypeConverter typeConv = DefaultTypeConverter.INSTANCE; // Check the If-Match header, don't send any content back if none of the tags in // the list match the etag, and the wildcard is not present if (ifMatchTags != null) { if (ifMatchTags.contains(WebDAV.ASTERISK) == false && ifMatchTags.contains(strETag) == false) { throw new WebDAVServerException(HttpServletResponse.SC_PRECONDITION_FAILED); } } // Check the If-None-Match header, don't send any content back if any of the tags // in the list match the etag, or the wildcard is present if (ifNoneMatchTags != null) { if (ifNoneMatchTags.contains(WebDAV.ASTERISK) || ifNoneMatchTags.contains(strETag)) { throw new WebDAVServerException(HttpServletResponse.SC_NOT_MODIFIED); } } // Check the modified since list, if the If-None-Match header was not specified if (m_ifModifiedSince != null && ifNoneMatchTags == null) { Date lastModifiedDate = nodeInfo.getModifiedDate(); long fileLastModified = lastModifiedDate != null ? typeConv.longValue(lastModifiedDate) : 0L; long modifiedSince = m_ifModifiedSince.getTime(); if (fileLastModified != 0L && fileLastModified <= modifiedSince) { throw new WebDAVServerException(HttpServletResponse.SC_NOT_MODIFIED); } } // Check the un-modified since list if (m_ifUnModifiedSince != null) { Date lastModifiedDate = nodeInfo.getModifiedDate(); long fileLastModified = lastModifiedDate != null ? typeConv.longValue(lastModifiedDate) : 0L; long unModifiedSince = m_ifUnModifiedSince.getTime(); if (fileLastModified >= unModifiedSince) { throw new WebDAVServerException(HttpServletResponse.SC_PRECONDITION_FAILED); } } }