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:au.org.ala.biocache.web.DownloadController.java
/** * Add a download to the offline queue//from w ww . j a v a 2 s . c o m * @param requestParams * @param ip * @param apiKey * @param type * @param response * @param request * @return * @throws Exception */ @RequestMapping(value = "occurrences/offline/{type}/download*", method = RequestMethod.GET) public String occurrenceDownload(DownloadRequestParams requestParams, @RequestParam(value = "ip", required = false) String ip, @RequestParam(value = "apiKey", required = false) String apiKey, @PathVariable("type") String type, HttpServletResponse response, HttpServletRequest request) throws Exception { boolean sensitive = false; if (apiKey != null) { if (shouldPerformOperation(apiKey, response, false)) { sensitive = true; } } else if (StringUtils.isEmpty(requestParams.getEmail())) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "Unable to perform an offline download without an email address"); } ip = ip == null ? request.getRemoteAddr() : ip; DownloadType downloadType = "index".equals(type.toLowerCase()) ? DownloadType.RECORDS_INDEX : DownloadType.RECORDS_DB; //create a new task DownloadDetailsDTO dd = new DownloadDetailsDTO(requestParams, ip, downloadType); dd.setIncludeSensitive(sensitive); persistentQueueDAO.addDownloadToQueue(dd); return null; }
From source file:com.almende.eve.transport.http.EveServlet.java
/** * Handle hand shake./*from w w w . j a v a 2 s . co m*/ * * @param req * the req * @param res * the res * @return true, if successful * @throws IOException * Signals that an I/O exception has occurred. */ private boolean handleHandShake(final HttpServletRequest req, final HttpServletResponse res) throws IOException { final String time = req.getHeader("X-Eve-requestToken"); if (time == null) { return false; } final String url = req.getRequestURI(); final String id = getId(url); final HttpTransport transport = HttpService.get(myUrl, id); if (transport != null) { final String token = transport.getTokenstore().get(time); if (token == null) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); } else { res.setHeader("X-Eve-replyToken", token); res.setStatus(HttpServletResponse.SC_OK); res.flushBuffer(); } } return true; }
From source file:org.dataconservancy.dcs.util.http.RequestHeaderUtil.java
/** * * @param req - the HttpServletRequest//from w w w. ja v a2 s . c o m * @param res - the HttpServletResponse * @param ifMatch - the match string * @param requestUtil - the request util * @param objectToMatch - the object to match * @param objectToMatchEtag - the etag to match * @param objectToMatchId - the id to match * @param objectToMatchClassname - the class name to match * @return true if the response has been committed * @throws java.io.IOException an IO exception */ public boolean handleIfMatch(HttpServletRequest req, HttpServletResponse res, RequestUtil requestUtil, String ifMatch, Object objectToMatch, String objectToMatchEtag, String objectToMatchId, String objectToMatchClassname) throws IOException { if (ifMatch == null || ifMatch.trim().length() == 0) { return false; } if (objectToMatch == null) { if (ifMatch.contains("*")) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "Unable to resolve " + objectToMatchClassname + " '" + requestUtil.buildRequestUrl(req) + "'"); } return true; } // Split the values String[] ifMatchValues = ifMatch.split(","); boolean match = false; for (String ifMatchValue : ifMatchValues) { ifMatchValue = ifMatchValue.trim(); if (ifMatchValue.equals("*") || ifMatchValue.equals(objectToMatchEtag)) { match = true; } } if (!match) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "If-Match header '" + ifMatch + "' " + "did not match the requested " + objectToMatchClassname + " representation: '" + objectToMatchId + "' ('" + objectToMatchEtag + "')"); return true; } return false; }
From source file:com.almende.eve.transport.http.DebugServlet.java
/** * Handle hand shake./* w ww .ja v a 2s . c om*/ * * @param req * the req * @param res * the res * @return true, if successful * @throws IOException * Signals that an I/O exception has occurred. */ private boolean handleHandShake(final HttpServletRequest req, final HttpServletResponse res) throws IOException { final String time = req.getHeader("X-Eve-requestToken"); if (time == null) { return false; } final String url = req.getRequestURI(); final String id = getId(url); final HttpTransport transport = HttpService.get(myUrl, id); if (transport != null) { final String token = transport.getTokenstore().get(time); if (token == null) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); } else { res.setHeader("X-Eve-replyToken", token); res.setStatus(HttpServletResponse.SC_OK); res.flushBuffer(); } } return true; }
From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletCopyTest.java
public void testCopyNodeAbsoluteBelowDest() throws IOException { final String testPath = TEST_BASE_PATH + "/abs/" + System.currentTimeMillis(); Map<String, String> props = new HashMap<String, String>(); props.put("text", "Hello"); testClient.createNode(HTTP_BASE_URL + testPath + "/src", props); // first test: failure because dest (parent) does not exist List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(); nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_COPY)); nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/")); assertPostStatus(HTTP_BASE_URL + testPath + "/src", HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs, "Expecting Copy Failure (dest must exist)"); // create dest as parent testClient.createNode(HTTP_BASE_URL + testPath + "/dest", null); // copy now succeeds to below dest assertPostStatus(HTTP_BASE_URL + testPath + "/src", HttpServletResponse.SC_CREATED, nvPairs, "Expecting Copy Success"); // assert content at new location String content = getContent(HTTP_BASE_URL + testPath + "/dest.-1.json", CONTENT_TYPE_JSON); assertJavascript("Hello", content, "out.println(data.src.text)"); // assert content at old location content = getContent(HTTP_BASE_URL + testPath + "/src.json", CONTENT_TYPE_JSON); assertJavascript("Hello", content, "out.println(data.text)"); }
From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletMoveTest.java
public void testMoveNodeAbsoluteBelowDest() throws IOException { final String testPath = TEST_BASE_PATH + "/abs/" + System.currentTimeMillis(); Map<String, String> props = new HashMap<String, String>(); props.put("text", "Hello"); testClient.createNode(HTTP_BASE_URL + testPath + "/src", props); // first test: failure because dest (parent) does not exist List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(); nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_MOVE)); nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/")); assertPostStatus(HTTP_BASE_URL + testPath + "/src", HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs, "Expecting Move Failure (dest must exist)"); // create dest as parent testClient.createNode(HTTP_BASE_URL + testPath + "/dest", null); // move now succeeds to below dest assertPostStatus(HTTP_BASE_URL + testPath + "/src", HttpServletResponse.SC_CREATED, nvPairs, "Expecting Move Success"); // assert content at new location String content = getContent(HTTP_BASE_URL + testPath + "/dest.-1.json", CONTENT_TYPE_JSON); assertJavascript("Hello", content, "out.println(data.src.text)"); // assert content at old location assertHttpStatus(HTTP_BASE_URL + testPath + "/src.json", HttpServletResponse.SC_NOT_FOUND); }
From source file:org.sakaiproject.nakamura.resource.lite.servlet.post.operations.ImportOperation.java
@Override protected void doRun(SlingHttpServletRequest request, HtmlResponse response, ContentManager contentManager, final List<Modification> changes, String contentPath) throws StorageClientException, AccessDeniedException, IOException { Resource resource = request.getResource(); String path = null;/*w w w.j a v a2 s . c o m*/ { Content content = resource.adaptTo(Content.class); if (content != null) { path = content.getPath(); } else { // for some reason, if the operation posts to a path that does not exist and the // operation is create tree the SparseCreateServlet.doPost() operation is // bypassed. This is an ugly fix that works wound that problem. I suspect // somethings up in Sling. path = (String) request.getAttribute(SparseCreateServlet.CONTENT_TARGET_PATH_ATTRIBUTE); } } if (path == null) { throw new StorageClientException("No Path suppleid to create json tree at"); } String contentType = request.getParameter(SlingPostConstants.RP_CONTENT_TYPE); if (contentType == null) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Required :contentType parameter is missing"); return; } // import options passed as request parameters. final boolean replace = "true".equalsIgnoreCase(request.getParameter(SlingPostConstants.RP_REPLACE)); final boolean replaceProperties = "true" .equalsIgnoreCase(request.getParameter(SlingPostConstants.RP_REPLACE_PROPERTIES)); final boolean removeTree = "true".equalsIgnoreCase(request.getParameter(":removeTree")); String basePath = getItemPath(request); if (basePath.endsWith("/")) { // remove the trailing slash basePath = basePath.substring(0, basePath.length() - 1); } response.setCreateRequest(true); try { InputStream contentStream = null; String content = request.getParameter(SlingPostConstants.RP_CONTENT); if (content == null) { RequestParameter contentFile = request.getRequestParameter(SlingPostConstants.RP_CONTENT_FILE); if (contentFile != null) { contentStream = contentFile.getInputStream(); content = IOUtils.toString(contentStream, "UTF-8"); } } if (content == null) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Missing content for import"); return; } else { JSONObject json = new JSONObject(content); if (LOGGER.isDebugEnabled()) { LOGGER.debug("to {} importing {} ", basePath, json.toString(3)); } LiteJsonImporter simpleJsonImporter = new LiteJsonImporter(); Session session = StorageClientUtils .adaptToSession(request.getResourceResolver().adaptTo(javax.jcr.Session.class)); AccessControlManager accessControlManager = session.getAccessControlManager(); simpleJsonImporter.importContent(contentManager, json, basePath, replace, replaceProperties, removeTree, accessControlManager); response.setLocation(externalizePath(request, basePath)); response.setPath(basePath); int lastSlashIndex = basePath.lastIndexOf('/'); if (lastSlashIndex != -1) { String parentPath = basePath.substring(0, lastSlashIndex); response.setParentLocation(externalizePath(request, parentPath)); } } } catch (IOException e) { LOGGER.error(e.getMessage(), e); throw new StorageClientException(e.getMessage(), e); } catch (JSONException e) { LOGGER.error(e.getMessage(), e); throw new StorageClientException(e.getMessage(), e); } }
From source file:io.github.gsteckman.rpi_rest.SubscriptionManager.java
/** * Processes a UPnP SUBSCRIBE request and creates or renews a subscription. * /*from w ww .ja va 2 s .c om*/ * @param key * The key identifies the resource to which this subscription applies. * @param req * Subscription request * @param res * Response to the subscription request * @throws IOException * Thrown by HttpServletResponse.sendError if an error occurs writing the response. */ public void processSubscribe(String key, HttpServletRequest req, HttpServletResponse res) throws IOException { String timeoutHdr = req.getHeader("TIMEOUT"); String callbackHdr = req.getHeader("CALLBACK"); String sidHdr = req.getHeader("SID"); List<URL> callbackUrls = new LinkedList<URL>(); // Perform error checking: // 1. Method must be SUBSCRIBE // 2. If no SID header // a. CALLBACK header must be present & properly formatted as a correct URL // b. NT header must be present with a value of "upnp:event" // 3. If there is a SID header, CALLBACK and NT headers not present if (!"SUBSCRIBE".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 && (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; } else { if (callbackHdr == null) { // CALLBACK is a required header. Return status 412 res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "CALLBACK header is missing."); return; } else { // parse callback header and ensure proper format callbackUrls = parseCallbackHeader(callbackHdr); if (callbackUrls.size() == 0) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "CALLBACK header doesn't contain a valid HTTP URL."); return; } } if (!"upnp:event".equals(req.getHeader("NT"))) { // NT is a required header. Return status 412 res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "NT header field does not equal upnp:event."); return; } } // parse timeout header long timeout = DEFAULT_TIMEOUT; try { timeout = Long.parseLong(timeoutHdr.substring(7)) * 1000; } catch (NumberFormatException e) { // ignore, use default LOG.info("Using default timeout", e); } // check if new subscription or a renewal if (sidHdr != null) { // subscription renewal 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 String ss = sidHdr.substring(5).trim(); UUID sid = new UUID(ss); SubscriptionInfo si = m.get(sid); if (si == null) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "SID doesn't correspond to a known subscription."); return; } si.renew(timeout); } else { // new subscription // create subscription identifier UUID sid = new UUID(); addSubscription(key, sid, new SubscriptionInfo(sid, timeout, callbackUrls)); // Create response res.setStatus(HttpServletResponse.SC_OK); res.addHeader("SERVER", System.getProperty("os.name") + "/" + System.getProperty("os.version") + ", UPnP/1.1, rpi-rest/0.1"); res.addHeader("SID", "uuid:" + sid.toString()); res.addHeader("TIMEOUT", "Second-" + (timeout / 1000)); } }
From source file:net.dorokhov.pony.web.server.common.StreamingViewRenderer.java
@Override protected void renderMergedOutputModel(Map objectMap, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream dataStream = (InputStream) objectMap.get(DownloadConstants.INPUT_STREAM); if (dataStream == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;//from ww w. ja v a 2 s . c o m } long length = (Long) objectMap.get(DownloadConstants.CONTENT_LENGTH); String fileName = (String) objectMap.get(DownloadConstants.FILENAME); Date lastModifiedObj = (Date) objectMap.get(DownloadConstants.LAST_MODIFIED); if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } long lastModified = lastModifiedObj.getTime(); String contentType = (String) objectMap.get(DownloadConstants.CONTENT_TYPE); // 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, fileName)) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); 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.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); 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, fileName)) { 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<>(); // 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; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1) { 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 content disposition. 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"; } else if (!contentType.startsWith("image")) { // 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. 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", fileName); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; try { // Open streams. input = new BufferedInputStream(dataStream); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total); response.setHeader("Content-Length", String.valueOf(full.length)); copy(input, output, length, full.start, full.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. // Copy single part range. copy(input, output, length, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // 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, length, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } finally { // Gently close streams. close(output); close(input); close(dataStream); } }
From source file:com.almende.eve.transport.http.AgentServlet.java
/** * Handle hand shake.//ww w . j ava 2 s .c om * * @param req * the req * @param res * the res * @return true, if successful * @throws IOException * Signals that an I/O exception has occurred. */ private boolean handleHandShake(final HttpServletRequest req, final HttpServletResponse res) throws IOException { final String time = req.getHeader("X-Eve-requestToken"); if (time == null) { return false; } final String token = TokenStore.get(time); if (token == null) { res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); } else { res.setHeader("X-Eve-replyToken", token); res.setStatus(HttpServletResponse.SC_OK); res.flushBuffer(); } return true; }