List of usage examples for javax.servlet.http HttpServletResponse SC_NO_CONTENT
int SC_NO_CONTENT
To view the source code for javax.servlet.http HttpServletResponse SC_NO_CONTENT.
Click Source Link
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * @param req/* w w w . j a v a2s . com*/ * @param resp * @throws IOException * @throws FileNotFoundException */ void putResource(HttpServletRequest req, HttpServletResponse resp) throws IOException, FileNotFoundException { String path = getInnerPath(req, PATH_FILES); try { path = URLDecoder.decode(path, "UTF-8"); } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } if (logger.isDebugEnabled()) logger.debug("Updating resource: " + path); final User user = getUser(req); User owner = getOwner(req); boolean exists = true; Object resource = null; FileHeader fileLocal = null; try { resource = getService().getResourceAtPath(owner.getId(), path, false); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (exists) if (resource instanceof FileHeader) fileLocal = (FileHeader) resource; else { resp.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder"); return; } boolean result = true; // Temporary content file used to support partial PUT. File contentFile = null; Range range = parseContentRange(req, resp); InputStream resourceInputStream = null; // Append data specified in ranges to existing content for this // resource - create a temporary file on the local filesystem to // perform this operation. // Assume just one range is specified for now if (range != null) { try { contentFile = executePartialPut(req, range, path); } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } resourceInputStream = new FileInputStream(contentFile); } else resourceInputStream = req.getInputStream(); try { Folder folderLocal = null; Object parent = getService().getResourceAtPath(owner.getId(), getParentPath(path), true); if (!(parent instanceof Folder)) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } folderLocal = (Folder) parent; final String name = getLastElement(path); final String mimeType = context.getMimeType(name); File uploadedFile = null; try { uploadedFile = getService().uploadFile(resourceInputStream, user.getId()); } catch (IOException ex) { throw new GSSIOException(ex, false); } FileHeader fileTemp = null; final File uploadedf = uploadedFile; final Folder parentf = folderLocal; final FileHeader f = fileLocal; if (exists) fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().updateFileContents(user.getId(), f.getId(), mimeType, uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath()); } }); else fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().createFile(user.getId(), parentf.getId(), name, mimeType, uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath()); } }); updateAccounting(owner, new Date(), fileTemp.getCurrentBody().getFileSize()); getService().removeFileUploadProgress(user.getId(), fileTemp.getName()); } catch (ObjectNotFoundException e) { result = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (IOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (GSSIOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (DuplicateNameException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } catch (QuotaExceededException e) { resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage()); return; } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (result) { if (exists) resp.setStatus(HttpServletResponse.SC_NO_CONTENT); else resp.setStatus(HttpServletResponse.SC_CREATED); } else resp.sendError(HttpServletResponse.SC_CONFLICT); }
From source file:edu.slu.action.ObjectAction.java
/** * Public facing servlet to PATCH set values of an existing RERUM object. * @respond with state of new object in the body * @throws java.io.IOException/*w ww . ja v a 2 s.c o m*/ * @throws javax.servlet.ServletException */ public void patchSetUpdate() throws IOException, ServletException, Exception { Boolean historyNextUpdatePassed = false; System.out.println("patch set update"); if (null != processRequestBody(request, true) && methodApproval(request, "set")) { BasicDBObject query = new BasicDBObject(); JSONObject received = JSONObject.fromObject(content); if (received.containsKey("@id")) { String updateHistoryNextID = received.getString("@id"); query.append("@id", updateHistoryNextID); BasicDBObject originalObject = (BasicDBObject) mongoDBService .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object. Make all edits to this variable. boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject)); boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject)); if (alreadyDeleted) { writeErrorResponse("The object you are trying to update is deleted.", HttpServletResponse.SC_FORBIDDEN); } else if (isReleased) { writeErrorResponse("The object you are trying to update is released. Fork to make changes.", HttpServletResponse.SC_FORBIDDEN); } else { if (null != originalObject) { Set<String> update_anno_keys = received.keySet(); int updateCount = 0; //If the object already in the database contains the key found from the object recieved from the user... for (String key : update_anno_keys) { if (originalObject.containsKey(key)) { //Keys matched. Ignore it, set only works for new keys. //@cubap @theHabes do we want to build that this happened into the response at all? } else { //this is a new key, this is a set. Allow null values. updatedObject.append(key, received.get(key)); updateCount += 1; } } if (updateCount > 0) { JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning) newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set. //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject); DBObject dbo = (DBObject) JSON.parse(newObject.toString()); String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo); String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID; BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo); dboWithObjectID.append("@id", newNextAtID); newObject.element("@id", newNextAtID); newObject.remove("_id"); mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID); historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id if (historyNextUpdatePassed) { System.out.println("object patch set updated: " + newNextAtID); JSONObject jo = new JSONObject(); JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1"); jo.element("code", HttpServletResponse.SC_OK); jo.element("original_object_id", updateHistoryNextID); jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response. jo.element("iiif_validation", iiif_validation_response); try { addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject)); addLocationHeader(newObject); response.addHeader("Content-Type", "application/json; charset=utf-8"); response.setContentType("UTF-8"); response.addHeader("Access-Control-Allow-Origin", "*"); response.setStatus(HttpServletResponse.SC_OK); out = response.getWriter(); out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo)); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } } else { //The error is already written to response.out, do nothing. } } else { // Nothing could be patched addLocationHeader(received); writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT); } } else { //This could means it was an external object, but those fail for PATCH updates. writeErrorResponse("Object " + received.getString("@id") + " not found in RERUM, could not update. PUT update to make this object a part of RERUM.", HttpServletResponse.SC_BAD_REQUEST); } } } else { writeErrorResponse("Object did not contain an @id, could not update.", HttpServletResponse.SC_BAD_REQUEST); } } }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public @Nonnull String post(@Nonnull String action, @Nonnull String endpoint, @Nullable String contentType, @Nullable String payload) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + vCloudMethod.class.getName() + ".post(" + endpoint + ")"); }//from w w w .j a v a 2s .co m try { HttpClient client = null; if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { Org org = authenticate(false); client = getClient(false); HttpPost post = new HttpPost(endpoint); post.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(post, org.token); if (contentType != null) { post.addHeader("Content-Type", contentType); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } if (payload != null) { try { //noinspection deprecation post.setEntity( new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "POST " + action); response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code == HttpServletResponse.SC_NOT_FOUND) { throw new CloudException("No action match for " + endpoint); } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { authenticate(true); return post(action, endpoint, contentType, payload); } else if (code == HttpServletResponse.SC_NO_CONTENT) { return ""; } else if (code == HttpServletResponse.SC_OK || code == HttpServletResponse.SC_CREATED || code == HttpServletResponse.SC_ACCEPTED) { String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } return xml; } else { logger.error("Expected OK or CREATED or NO_CONTENT or ACCEPTED for POST request, got " + code); String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(code, errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, code, response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + code + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (wire.isDebugEnabled()) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + vCloudMethod.class.getName() + ".post()"); } } }
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * Delete a resource./*from w w w .j ava 2 s .c om*/ * * @param req The servlet request we are processing * @param resp The servlet response we are processing * @throws IOException if the response cannot be sent */ void deleteResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = getInnerPath(req, PATH_FILES); if (logger.isDebugEnabled()) logger.debug("Deleting resource '" + path); path = URLDecoder.decode(path, "UTF-8"); final User user = getUser(req); User owner = getOwner(req); boolean exists = true; Object object = null; try { object = getService().getResourceAtPath(owner.getId(), path, false); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (!exists) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Folder folderLocal = null; FileHeader fileLocal = null; if (object instanceof Folder) folderLocal = (Folder) object; else fileLocal = (FileHeader) object; if (fileLocal != null) try { final FileHeader f = fileLocal; new TransactionHelper<Void>().tryExecute(new Callable<Void>() { @Override public Void call() throws Exception { getService().deleteFile(user.getId(), f.getId()); return null; } }); } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } catch (ObjectNotFoundException e) { // Although we had already found the object, it was // probably deleted from another thread. resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } else if (folderLocal != null) try { final Folder fo = folderLocal; new TransactionHelper<Void>().tryExecute(new Callable<Void>() { @Override public Void call() throws Exception { getService().deleteFolder(user.getId(), fo.getId()); return null; } }); } catch (InsufficientPermissionsException e) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } catch (ObjectNotFoundException e) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } catch (RpcException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } catch (Exception e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } resp.setStatus(HttpServletResponse.SC_NO_CONTENT); return; }
From source file:edu.slu.action.ObjectAction.java
/** * Public facing servlet to PATCH unset values of an existing RERUM object. * @respond with state of new object in the body * @throws java.io.IOException//from w ww .j a v a 2 s .c o m * @throws javax.servlet.ServletException */ public void patchUnsetUpdate() throws IOException, ServletException, Exception { Boolean historyNextUpdatePassed = false; System.out.println("Patch unset update"); if (null != processRequestBody(request, true) && methodApproval(request, "unset")) { BasicDBObject query = new BasicDBObject(); JSONObject received = JSONObject.fromObject(content); if (received.containsKey("@id")) { String updateHistoryNextID = received.getString("@id"); query.append("@id", updateHistoryNextID); BasicDBObject originalObject = (BasicDBObject) mongoDBService .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object. Make all edits to this variable. boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject)); boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject)); if (alreadyDeleted) { writeErrorResponse("The object you are trying to update is deleted.", HttpServletResponse.SC_FORBIDDEN); } else if (isReleased) { writeErrorResponse("The object you are trying to update is released. Fork to make changes.", HttpServletResponse.SC_FORBIDDEN); } else { if (null != originalObject) { Set<String> update_anno_keys = received.keySet(); int updateCount = 0; //If the object already in the database contains the key found from the object recieved from the user... for (String key : update_anno_keys) { if (originalObject.containsKey(key)) { if (key.equals("@id") || key.equals("__rerum") || key.equals("objectID") || key.equals("_id")) { // Ignore these in a PATCH. DO NOT update, DO NOT count as an attempt to update } else { if (null != received.get(key)) { //Found matching keys and value is not null. Ignore these. //@cubap @theHabes do we want to build that this happened into the response at all? } else { //Found matching keys and value is null, this is an unset updatedObject.remove(key); updateCount += 1; } } } else { //Original object does not contain this key, perhaps the user meant set. //@cubap @theHabes do we want to build that this happened into the response at all? } } if (updateCount > 0) { JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning) newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set. //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject); DBObject dbo = (DBObject) JSON.parse(newObject.toString()); String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo); String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID; BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo); dboWithObjectID.append("@id", newNextAtID); newObject.element("@id", newNextAtID); newObject.remove("_id"); mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID); historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id if (historyNextUpdatePassed) { System.out.println("Patch unset updated: " + newNextAtID); JSONObject jo = new JSONObject(); JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1"); jo.element("code", HttpServletResponse.SC_OK); jo.element("original_object_id", updateHistoryNextID); jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response. jo.element("iiif_validation", iiif_validation_response); try { addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject)); addLocationHeader(newObject); response.addHeader("Access-Control-Allow-Origin", "*"); response.setStatus(HttpServletResponse.SC_OK); response.addHeader("Content-Type", "application/json; charset=utf-8"); response.setContentType("UTF-8"); out = response.getWriter(); out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo)); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } } else { //The error is already written to response.out, do nothing. } } else { // Nothing could be patched addLocationHeader(received); writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT); } } else { //This could means it was an external object, but those fail for PATCH updates. writeErrorResponse("Object " + received.getString("@id") + " not found in RERUM, could not update. PUT update to make this object a part of RERUM.", HttpServletResponse.SC_BAD_REQUEST); } } } else { writeErrorResponse("Object did not contain an @id, could not update.", HttpServletResponse.SC_BAD_REQUEST); } } }
From source file:edu.slu.action.ObjectAction.java
/** * Update a given annotation. Cannot set or unset keys. * @respond with state of new object in the body *//*from w w w . j a v a 2s . c o m*/ public void patchUpdateObject() throws ServletException, Exception { Boolean historyNextUpdatePassed = false; System.out.println("trying to patch"); if (null != processRequestBody(request, true) && methodApproval(request, "patch")) { BasicDBObject query = new BasicDBObject(); JSONObject received = JSONObject.fromObject(content); if (received.containsKey("@id")) { String updateHistoryNextID = received.getString("@id"); query.append("@id", updateHistoryNextID); BasicDBObject originalObject = (BasicDBObject) mongoDBService .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject)); boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject)); if (alreadyDeleted) { writeErrorResponse("The object you are trying to update is deleted.", HttpServletResponse.SC_FORBIDDEN); } else if (isReleased) { writeErrorResponse("The object you are trying to update is released. Fork to make changes.", HttpServletResponse.SC_FORBIDDEN); } else { if (null != originalObject) { BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object. Make all edits to this variable. Set<String> update_anno_keys = received.keySet(); boolean triedToSet = false; int updateCount = 0; //If the object already in the database contains the key found from the object recieved from the user, update it barring a few special keys //Users cannot update the __rerum property, so we ignore any update action to that particular field. for (String key : update_anno_keys) { if (originalObject.containsKey(key)) { //Skip keys we want to ignore and keys that match but have matching values if (!(key.equals("@id") || key.equals("__rerum") || key.equals("objectID") || key.equals("_id")) && received.get(key) != originalObject.get(key)) { updatedObject.remove(key); updatedObject.append(key, received.get(key)); updateCount += 1; } } else { triedToSet = true; // break; } } if (triedToSet) { System.out.println("Patch meh 1"); //@cubap @theHabes We continued with what we could patch. Do we tell the user at all? //writeErrorResponse("A key you are trying to update does not exist on the object. You can set with the patch_set or put_update action.", HttpServletResponse.SC_BAD_REQUEST); } else if (updateCount == 0) { System.out.println("Patch meh 2"); addLocationHeader(received); writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT); } else { JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning) newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set. //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject); DBObject dbo = (DBObject) JSON.parse(newObject.toString()); String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo); String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID; BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo); dboWithObjectID.append("@id", newNextAtID); newObject.element("@id", newNextAtID); newObject.remove("_id"); mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID); historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id if (historyNextUpdatePassed) { System.out.println("Patch updated object: " + newNextAtID); JSONObject jo = new JSONObject(); JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1"); jo.element("code", HttpServletResponse.SC_OK); jo.element("original_object_id", updateHistoryNextID); jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response. jo.element("iiif_validation", iiif_validation_response); try { addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject)); addLocationHeader(newObject); response.addHeader("Access-Control-Allow-Origin", "*"); response.setStatus(HttpServletResponse.SC_OK); response.addHeader("Content-Type", "application/json; charset=utf-8"); response.setContentType("UTF-8"); out = response.getWriter(); out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo)); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } } else { //The error is already written to response.out, do nothing. } } } else { writeErrorResponse( "Object " + received.getString("@id") + " not found in RERUM, could not patch update.", HttpServletResponse.SC_BAD_REQUEST); } } } else { writeErrorResponse("Object did not contain an @id, could not patch update.", HttpServletResponse.SC_BAD_REQUEST); } } }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public @Nonnull String put(@Nonnull String action, @Nonnull String endpoint, @Nullable String contentType, @Nullable String payload) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + vCloudMethod.class.getName() + ".put(" + endpoint + ")"); }//from w w w . j a v a 2s. c o m try { HttpClient client = null; if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [PUT (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { Org org = authenticate(false); client = getClient(false); HttpPut put = new HttpPut(endpoint); put.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(put, org.token); if (contentType != null) { put.addHeader("Content-Type", contentType); } if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } if (payload != null) { try { //noinspection deprecation put.setEntity( new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } try { wire.debug(EntityUtils.toString(put.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "PUT " + action); response = client.execute(put); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code == HttpServletResponse.SC_NOT_FOUND) { throw new CloudException("No action match for " + endpoint); } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { authenticate(true); return post(action, endpoint, contentType, payload); } else if (code == HttpServletResponse.SC_NO_CONTENT) { return ""; } else if (code == HttpServletResponse.SC_OK || code == HttpServletResponse.SC_CREATED || code == HttpServletResponse.SC_ACCEPTED) { String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } return xml; } else { logger.error("Expected OK or CREATED or NO_CONTENT or ACCEPTED for POST request, got " + code); String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(code, errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, code, response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + code + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (wire.isDebugEnabled()) { wire.debug("<<< [PUT (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + vCloudMethod.class.getName() + ".put()"); } } }
From source file:org.opencastproject.adminui.endpoint.AbstractEventEndpoint.java
@POST @Path("new/conflicts") @RestQuery(name = "checkNewConflicts", description = "Checks if the current scheduler parameters are in a conflict with another event", returnDescription = "Returns NO CONTENT if no event are in conflict within specified period or list of conflicting recordings in JSON", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "No conflicting events found"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "There is a conflict"), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid parameters") }) public Response getNewConflicts(@FormParam("metadata") String metadata) throws NotFoundException { if (StringUtils.isBlank(metadata)) { logger.warn("Metadata is not specified"); return Response.status(Status.BAD_REQUEST).build(); }// w w w . j a v a 2 s.c o m JSONObject metadataJson; try { metadataJson = (JSONObject) parser.parse(metadata); } catch (Exception e) { logger.warn("Unable to parse metadata {}", metadata); return RestUtil.R.badRequest("Unable to parse metadata"); } String device; String startDate; String endDate; try { device = (String) metadataJson.get("device"); startDate = (String) metadataJson.get("start"); endDate = (String) metadataJson.get("end"); } catch (Exception e) { logger.warn("Unable to parse metadata {}", metadata); return RestUtil.R.badRequest("Unable to parse metadata"); } if (StringUtils.isBlank(device) || StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) { logger.warn("Either device, start date or end date were not specified"); return Response.status(Status.BAD_REQUEST).build(); } Date start; try { start = new Date(DateTimeSupport.fromUTC(startDate)); } catch (Exception e) { logger.warn("Unable to parse start date {}", startDate); return RestUtil.R.badRequest("Unable to parse start date"); } Date end; try { end = new Date(DateTimeSupport.fromUTC(endDate)); } catch (Exception e) { logger.warn("Unable to parse end date {}", endDate); return RestUtil.R.badRequest("Unable to parse end date"); } String rrule = (String) metadataJson.get("rrule"); String timezone = null; String durationString = null; if (StringUtils.isNotEmpty(rrule)) { try { RRule rule = new RRule(rrule); rule.validate(); } catch (Exception e) { logger.warn("Unable to parse rrule {}: {}", rrule, e.getMessage()); return Response.status(Status.BAD_REQUEST).build(); } durationString = (String) metadataJson.get("duration"); if (StringUtils.isBlank(durationString)) { logger.warn("If checking recurrence, must include duration."); return Response.status(Status.BAD_REQUEST).build(); } Agent agent = getCaptureAgentStateService().getAgent(device); timezone = agent.getConfiguration().getProperty("capture.device.timezone"); if (StringUtils.isBlank(timezone)) { timezone = TimeZone.getDefault().getID(); logger.warn( "No 'capture.device.timezone' set on agent {}. The default server timezone {} will be used.", device, timezone); } } try { DublinCoreCatalogList events = null; if (StringUtils.isNotEmpty(rrule)) { events = getSchedulerService().findConflictingEvents(device, rrule, start, end, Long.parseLong(durationString), timezone); } else { events = getSchedulerService().findConflictingEvents(device, start, end); } if (!events.getCatalogList().isEmpty()) { List<JValue> eventsJSON = new ArrayList<JValue>(); for (DublinCoreCatalog event : events.getCatalogList()) { eventsJSON.add(j(f("time", v(event.getFirst(DublinCoreCatalog.PROPERTY_TEMPORAL))), f("title", v(event.getFirst(DublinCoreCatalog.PROPERTY_TITLE))))); } return conflictJson(a(eventsJSON)); } else { return Response.noContent().build(); } } catch (Exception e) { logger.error("Unable to find conflicting events for {}, {}, {}: {}", new String[] { device, startDate, endDate, ExceptionUtils.getStackTrace(e) }); return RestUtil.R.serverError(); } }
From source file:edu.slu.action.ObjectAction.java
/** * Public facing servlet to delete a given annotation. *//*from ww w .ja v a 2s . c o m*/ public void deleteObject() throws IOException, ServletException, Exception { System.out.println("Delete object"); if (null != processRequestBody(request, true) && methodApproval(request, "delete")) { BasicDBObject query = new BasicDBObject(); BasicDBObject originalObject; //processRequestBody will always return a stringified JSON object here, even if the ID provided was a string in the body. JSONObject received = JSONObject.fromObject(content); JSONObject safe_received; JSONObject updatedWithFlag = new JSONObject(); BasicDBObject updatedObjectWithDeletedFlag; if (received.containsKey("@id")) { query.append("@id", received.getString("@id")); BasicDBObject mongo_obj = (BasicDBObject) mongoDBService .findOneByExample(Constant.COLLECTION_ANNOTATION, query); safe_received = JSONObject.fromObject(mongo_obj); //We can trust this is the object as it exists in mongo boolean alreadyDeleted = checkIfDeleted(safe_received); boolean permission = false; boolean isReleased = false; boolean passedAllChecks = false; if (alreadyDeleted) { writeErrorResponse("Object for delete is already deleted.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else { isReleased = checkIfReleased(safe_received); if (isReleased) { writeErrorResponse("This object is in a released state and cannot be deleted.", HttpServletResponse.SC_METHOD_NOT_ALLOWED); } else { String origObjGenerator = safe_received.getJSONObject("__rerum").getString("generatedBy"); boolean isGenerator = (origObjGenerator.equals(generatorID)); if (isGenerator) { passedAllChecks = true; } else { writeErrorResponse( "Only the agent that created this object can delete it. Agent= " + generatorID, HttpServletResponse.SC_UNAUTHORIZED); } } } if (passedAllChecks) { //If all checks have passed. If not, we want to make sure their writeErrorReponse() don't stack. originalObject = (BasicDBObject) JSON.parse(safe_received.toString()); //The original object out of mongo for persistance //Found the @id in the object, but does it exist in RERUM? if (null != originalObject) { String preserveID = safe_received.getString("@id"); JSONObject deletedFlag = new JSONObject(); //The __deleted flag is a JSONObject deletedFlag.element("object", originalObject); deletedFlag.element("deletor", generatorID); deletedFlag.element("time", System.currentTimeMillis()); updatedWithFlag.element("@id", preserveID); updatedWithFlag.element("__deleted", deletedFlag); //We want everything wrapped in deleted except the @id. Object forMongo = JSON.parse(updatedWithFlag.toString()); //JSONObject cannot be converted to BasicDBObject updatedObjectWithDeletedFlag = (BasicDBObject) forMongo; boolean treeHealed = healHistoryTree(JSONObject.fromObject(originalObject)); if (treeHealed) { mongoDBService.update(Constant.COLLECTION_ANNOTATION, originalObject, updatedObjectWithDeletedFlag); response.setStatus(HttpServletResponse.SC_NO_CONTENT); System.out.println("Object deleted:" + preserveID); } else { //@cubap @theHabes FIXME By default, objects that don't have the history property will fail to this line. writeErrorResponse( "We could not update the history tree correctly. The delete failed.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { writeErrorResponse( "The '@id' string provided for DELETE could not be found in RERUM: " + safe_received.getString("@id") + ". \n DELETE failed.", HttpServletResponse.SC_NOT_FOUND); } } } else { writeErrorResponse("Object for delete did not contain an '@id'. Could not delete.", HttpServletResponse.SC_BAD_REQUEST); } } }