Example usage for com.mongodb.util JSON parse

List of usage examples for com.mongodb.util JSON parse

Introduction

In this page you can find the example usage for com.mongodb.util JSON parse.

Prototype

public static Object parse(final String jsonString) 

Source Link

Document

Parses a JSON string and returns a corresponding Java object.

Usage

From source file:edu.sjsu.cohort6.openstack.db.mongodb.TaskDAO.java

License:Open Source License

@Override
public List<Task> fetch(String query) throws DBException {
    List<Task> tasks = new ArrayList<>();
    DBObject dbObjQuery;/* w w  w. j av a  2  s  .com*/
    DBCursor cursor;
    if (!(query == null)) {
        dbObjQuery = (DBObject) JSON.parse(query);
        cursor = this.getCollection().find(dbObjQuery);
    } else {
        cursor = this.getCollection().find();
    }

    List<DBObject> dbObjects = cursor.toArray();
    for (DBObject dbObject : dbObjects) {
        Task task = morphia.fromDBObject(Task.class, dbObject);
        tasks.add(task);
    }
    return tasks;
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Internal helper method to update the history.previous property of a root object.  This will occur because a new root object can be created
 * by put_update.action on an external object.  It must mark itself as root and contain the original ID for the object in history.previous.
 * This method only receives reliable objects from mongo.
 * //from  ww  w .  j av a  2s.  c o m
 * @param newRootObj the RERUM object whose history.previous needs to be updated
 * @param externalObjID the @id of the external object to go into history.previous
 * @return JSONObject of the provided object with the history.previous alteration
 */
private JSONObject alterHistoryPrevious(JSONObject newRootObj, String externalObjID) {
    DBObject myAnnoWithHistoryUpdate;
    DBObject myAnno = (BasicDBObject) JSON.parse(newRootObj.toString());
    try {
        newRootObj.getJSONObject("__rerum").getJSONObject("history").element("previous", externalObjID); //write back to the anno from mongo
        myAnnoWithHistoryUpdate = (DBObject) JSON.parse(newRootObj.toString()); //make the JSONObject a DB object
        mongoDBService.update(Constant.COLLECTION_ANNOTATION, myAnno, myAnnoWithHistoryUpdate); //update in mongo
    } catch (Exception e) {
        writeErrorResponse(
                "This object does not contain the proper history property.  It may not be from RERUM, the update failed.",
                HttpServletResponse.SC_CONFLICT);
    }
    return newRootObj;
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Internal helper method to update the history.next property of an object.  This will occur because updateObject will create a new object from a given object, and that
 * given object will have a new next value of the new object.  Watch out for missing __rerum or malformed __rerum.history
 * /*from   w  w  w.j  av a 2 s. c  om*/
 * @param idForUpdate the @id of the object whose history.next needs to be updated
 * @param newNextID the @id of the newly created object to be placed in the history.next array.
 * @return Boolean altered true on success, false on fail
 */
private boolean alterHistoryNext(String idForUpdate, String newNextID) {
    //TODO @theHabes As long as we trust the objects we send to this, we can take out the lookup and pass in objects as parameters
    System.out.println("Trying to alter history...");
    Boolean altered = false;
    BasicDBObject query = new BasicDBObject();
    query.append("@id", idForUpdate);
    DBObject myAnno = mongoDBService.findOneByExample(Constant.COLLECTION_ANNOTATION, query);
    DBObject myAnnoWithHistoryUpdate;
    JSONObject annoToUpdate = JSONObject.fromObject(myAnno);
    if (null != myAnno) {
        try {
            annoToUpdate.getJSONObject("__rerum").getJSONObject("history").getJSONArray("next").add(newNextID); //write back to the anno from mongo
            myAnnoWithHistoryUpdate = (DBObject) JSON.parse(annoToUpdate.toString()); //make the JSONObject a DB object
            System.out.println("Update in Mongo");
            mongoDBService.update(Constant.COLLECTION_ANNOTATION, myAnno, myAnnoWithHistoryUpdate); //update in mongo
            System.out.println("Done");
            altered = true;
        } catch (Exception e) {
            //@cubap @theHabes #44.  What if obj does not have __rerum or __rerum.history
            System.out.println("This object did not have a propery history...");
            writeErrorResponse(
                    "This object does not contain the proper history property.  It may not be from RERUM, the update failed.",
                    HttpServletResponse.SC_CONFLICT);
        }
    } else { //THIS IS A 404
        System.out.println("Couldnt find the object to alter history...");
        writeErrorResponse("Object for update not found...", HttpServletResponse.SC_NOT_FOUND);
    }
    return altered;
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Internal private method to loads all derivative versions from the `root` object. It should always receive a reliable object, not one from the user.
 * Used to resolve the history tree for storing into memory.
 * @param  obj A JSONObject to find all versions of.  If it is root, make sure to prepend it to the result.  If it isn't root, query for root from the ID
 * found in prime using that result as a reliable root object. 
 * @return All versions from the store of the object in the request
 * @throws Exception /*from   w  w  w .  j  av a2  s  .co  m*/
 */
private List<DBObject> getAllVersions(JSONObject obj) throws Exception {
    List<DBObject> ls_versions = null;
    BasicDBObject rootObj;
    BasicDBObject query = new BasicDBObject();
    BasicDBObject queryForRoot = new BasicDBObject();
    String primeID;
    //@cubap @theHabes #44.  What if obj does not have __rerum or __rerum.history
    if (obj.getJSONObject("__rerum").getJSONObject("history").getString("prime").equals("root")) {
        primeID = obj.getString("@id");
        //Get all objects whose prime is this things @id
        query.append("__rerum.history.prime", primeID);
        ls_versions = mongoDBService.findByExample(Constant.COLLECTION_ANNOTATION, query);
        for (int i = 0; i < ls_versions.size(); i++) {
            BasicDBObject version = (BasicDBObject) ls_versions.get(i);
            version.remove("_id");
            ls_versions.set(i, version);
        }
        rootObj = (BasicDBObject) JSON.parse(obj.toString());
        rootObj.remove("_id");
        //Prepend the rootObj we know about
        ls_versions.add(0, rootObj);
    } else {
        primeID = obj.getJSONObject("__rerum").getJSONObject("history").getString("prime");
        //Get all objects whose prime is equal to this ID
        query.append("__rerum.history.prime", primeID);
        ls_versions = mongoDBService.findByExample(Constant.COLLECTION_ANNOTATION, query);
        for (int i = 0; i < ls_versions.size(); i++) {
            BasicDBObject version = (BasicDBObject) ls_versions.get(i);
            version.remove("_id");
            ls_versions.set(i, version);
        }
        queryForRoot.append("@id", primeID);
        rootObj = (BasicDBObject) mongoDBService.findOneByExample(Constant.COLLECTION_ANNOTATION, queryForRoot);
        //Prepend the rootObj whose ID we knew and we queried for
        rootObj.remove("_id");
        ls_versions.add(0, rootObj);
    }
    return ls_versions;
}

From source file:edu.slu.action.ObjectAction.java

/** 
* TODO @see batchSaveMetadataForm.  Do both methods need to exist?  Combine if possible. This is the method we use for generic bulk saving.
* Each canvas has an annotation list with 0 - infinity annotations.  A copy requires a new annotation list with the copied annotations and a new @id.
* Mongo allows us to bulk save.  /*from   ww  w. j a  v  a2s  .c o  m*/
* The content is from an HTTP request posting in an array filled with annotations to copy.  
* @throws java.io.UnsupportedEncodingException
* @throws javax.servlet.ServletException
* @see MongoDBAbstractDAO.bulkSaveFromCopy(String collectionName, BasicDBList entity_array);
* @see MongoDBAbstractDAO.bulkSetIDProperty(String collectionName, BasicDBObject[] entity_array);
*/
public void batchSaveFromCopy() throws UnsupportedEncodingException, IOException, ServletException, Exception {
    System.out.println("batch save");
    if (null != processRequestBody(request, false) && methodApproval(request, "create")) {
        JSONArray received_array = JSONArray.fromObject(content);
        for (int b = 0; b < received_array.size(); b++) { //Configure __rerum on each object
            JSONObject configureMe = received_array.getJSONObject(b);
            configureMe = configureRerumOptions(configureMe, false); //configure this object
            received_array.set(b, configureMe); //Replace the current iterated object in the array with the configured object
        }
        BasicDBList dbo = (BasicDBList) JSON.parse(received_array.toString()); //tricky cause can't use JSONArray here
        JSONArray newResources = new JSONArray();
        //if the size is 0, no need to bulk save.  Nothing is there.
        if (dbo.size() > 0) {
            //System.out.println("batch save from copy off to bulk save from copy sending");
            //System.out.println(dbo.toString());
            newResources = mongoDBService.bulkSaveFromCopy(Constant.COLLECTION_ANNOTATION, dbo);
        } else {
            // empty array
        }
        //bulk save will automatically call bulk update 

        JSONObject jo = new JSONObject();
        jo.element("code", HttpServletResponse.SC_CREATED);
        jo.element("new_resources", newResources);
        addLocationHeader(newResources);
        try {
            response.setStatus(HttpServletResponse.SC_CREATED);
            response.addHeader("Content-Type", "application/json; charset=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);
        }
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Save a new annotation provided by the user. 
 * @throws java.io.IOException//from www  .j  a  v  a2  s. c o  m
 * @throws javax.servlet.ServletException
 * @respond with new @id in Location header and the new annotation in the body.
 */
public void saveNewObject() throws IOException, ServletException, Exception {
    System.out.println("create object");
    if (null != processRequestBody(request, false) && methodApproval(request, "create")) {
        //System.out.println("process and approval over.  actually save now");
        JSONObject received = JSONObject.fromObject(content);
        if (received.containsKey("@id") && !received.getString("@id").isEmpty()) {
            writeErrorResponse("Object already contains an @id " + received.containsKey("@id")
                    + ".  Either remove this property for saving or if it is a RERUM object update instead.",
                    HttpServletResponse.SC_BAD_REQUEST);
        } else {
            JSONObject iiif_validation_response = checkIIIFCompliance(received, true); //This boolean should be provided by the user somehow.  It is a intended-to-be-iiif flag
            received = configureRerumOptions(received, false);
            received.remove("_id");
            DBObject dbo = (DBObject) JSON.parse(received.toString());
            if (null != request.getHeader("Slug")) {
                // Slug is the user suggested ID for the annotation. This could be a cool RERUM thing.
                // cubap: if we want, we can just copy the Slug to @id, warning
                // if there was some mismatch, since versions are fine with that.
            }
            String newObjectID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
            //set @id from _id and update the annotation
            BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo);
            String newid = Constant.RERUM_ID_PREFIX + newObjectID;
            dboWithObjectID.put("@id", newid);
            mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID);
            JSONObject jo = new JSONObject();
            JSONObject newObjWithID = JSONObject.fromObject(dboWithObjectID);
            jo.element("code", HttpServletResponse.SC_CREATED);
            newObjWithID.remove("_id");
            jo.element("new_obj_state", newObjWithID);
            jo.element("iiif_validation", iiif_validation_response);
            //try {
            System.out.println("Object created: " + newid);
            response.addHeader("Access-Control-Allow-Origin", "*");
            addWebAnnotationHeaders(newObjectID, isContainerType(received), isLD(received));
            addLocationHeader(newObjWithID);
            response.addHeader("Content-Type", "application/json; charset=utf-8");
            response.setContentType("UTF-8");
            response.setStatus(HttpServletResponse.SC_CREATED);
            out = response.getWriter();
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo));
            // }
            //catch (IOException ex) {
            //   System.out.println("Save new obj failed on IO Exception.");
            //    Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
            //}
        }
    }
}

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//from ww w.  j  av a  2s.  c om
 * @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: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/*  www  . ja  v  a 2  s .c om*/
 * @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  ww . j a v  a 2 s  .  co  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:edu.slu.action.ObjectAction.java

/**
* Public facing servlet to PUT replace an existing object.  Can set and unset keys.
* @respond with new state of the object in the body.
* @throws java.io.IOException// w  w  w.  j  a v  a 2 s.  co  m
* @throws javax.servlet.ServletException
*/
public void putUpdateObject() throws IOException, ServletException, Exception {
    //@webanno The client should use the If-Match header with a value of the ETag it received from the server before the editing process began, 
    //to avoid collisions of multiple users modifying the same Annotation at the same time
    //cubap: I'm not sold we have to do this. Our versioning would allow multiple changes. 
    //The application might want to throttle internally, but it can.
    Boolean historyNextUpdatePassed = false;
    System.out.println("put update object");
    if (null != processRequestBody(request, true) && methodApproval(request, "update")) {
        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) JSON.parse(received.toString()); //A copy of the original, this will be saved as a new object.  Make all edits to this variable.
            JSONObject originalJSONObj = JSONObject.fromObject(originalObject);
            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) {
                    JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning)
                    JSONObject originalProperties = originalJSONObj.getJSONObject("__rerum");
                    newObject.element("__rerum", originalProperties);
                    //Since this is a put update, it is possible __rerum is not in the object provided by the user.  We get a reliable copy oof the original out of mongo
                    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.
                    newObject.remove("_id");
                    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 put 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 {
                    updateExternalObject(received);
                }
            }
        } else {
            writeErrorResponse("Object did not contain an @id, could not update.",
                    HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}