Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject append.

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

Usage

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 .  jav  a 2 s. com
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//from   ww  w. j a v  a 2 s. c o 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);
        }
    }
}

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

/**
 * Public facing servlet to PUT overwrite an existing object.  Can set and unset keys.  There will be no reference to the node as it originally existed
 * because this intentionally avoids any versioning around the action.  It is a pure overwrite and should only be allowed for the generator of the object.
 * Do NOT overwrite __rerum, keep the original no matter what __rerum is provided by the user.
 * // w  w  w  .  j a v a2  s. c o m
 * 
 * @respond with new state of the object in the body.
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 */
public void overwriteObject() throws IOException, ServletException, Exception {
    System.out.println("overwrite object");
    if (null != processRequestBody(request, true) && methodApproval(request, "overwrite")) {
        BasicDBObject query = new BasicDBObject();
        JSONObject received = JSONObject.fromObject(content);
        if (received.containsKey("@id")) {
            String receivedID = received.getString("@id");
            query.append("@id", receivedID);
            BasicDBObject originalObject = (BasicDBObject) mongoDBService
                    .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object
            JSONObject originalJSONObj = JSONObject.fromObject(originalObject);
            boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject));
            boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject));
            String origObjGenerator = originalJSONObj.getJSONObject("__rerum").getString("generatedBy");
            boolean isGenerator = (origObjGenerator.equals(generatorID));
            if (alreadyDeleted) {
                writeErrorResponse("The object you are trying to overwrite is deleted.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else if (isReleased) {
                writeErrorResponse("The object you are trying to overwrite is released.  Fork to make changes.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else if (!isGenerator) {
                writeErrorResponse(
                        "The object you are trying to overwrite was not created by you.  Fork to make changes.",
                        HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                if (null != originalObject) {
                    JSONObject newObject = received;//The edited original object meant to be saved as a new object (versioning)
                    newObject.remove("_id");
                    JSONObject originalProperties = originalJSONObj.getJSONObject("__rerum");
                    newObject.element("__rerum", originalProperties);
                    DBObject udbo = (DBObject) JSON.parse(newObject.toString());
                    mongoDBService.update(Constant.COLLECTION_ANNOTATION, originalObject, udbo);
                    JSONObject jo = new JSONObject();
                    JSONObject iiif_validation_response = checkIIIFCompliance(receivedID, "2.1");
                    System.out.println("object overwritten: " + receivedID);
                    newObject.remove("_id");
                    jo.element("code", HttpServletResponse.SC_OK);
                    jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response.
                    jo.element("iiif_validation", iiif_validation_response);
                    try {
                        addWebAnnotationHeaders(receivedID, 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 {
            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 release an existing RERUM object.  This will not perform history tree updates, but rather releases tree updates.
* (AKA a new node in the history tree is NOT CREATED here.)
* 
* @respond with new state of the object in the body.
* @throws java.io.IOException/* www .  j a  v a2s  .c  o  m*/
* @throws javax.servlet.ServletException
*/
public void releaseObject() throws IOException, ServletException, Exception {
    boolean treeHealed = false;
    boolean isGenerator = false;
    System.out.println("Release object");
    if (null != processRequestBody(request, true) && methodApproval(request, "release")) {
        BasicDBObject query = new BasicDBObject();
        JSONObject received = JSONObject.fromObject(content);
        if (received.containsKey("@id")) {
            String updateToReleasedID = received.getString("@id");
            query.append("@id", updateToReleasedID);
            BasicDBObject originalObject = (BasicDBObject) mongoDBService
                    .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The original DB object
            BasicDBObject releasedObject = (BasicDBObject) originalObject.copy(); //A copy of the original.  Make all edits to this variable.
            JSONObject safe_original = JSONObject.fromObject(originalObject); //The original object represented as a JSON object.  Safe for edits. 
            String previousReleasedID = safe_original.getJSONObject("__rerum").getJSONObject("releases")
                    .getString("previous");
            JSONArray nextReleases = safe_original.getJSONObject("__rerum").getJSONObject("releases")
                    .getJSONArray("next");
            boolean alreadyReleased = checkIfReleased(safe_original);
            if (alreadyReleased) {
                writeErrorResponse(
                        "This object is already released.  You must fork this annotation as one of your own to release it.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else {
                if (null != originalObject) {
                    String origObjGenerator = safe_original.getJSONObject("__rerum").getString("generatedBy");
                    isGenerator = (origObjGenerator.equals(generatorID));
                    if (isGenerator) {
                        safe_original.getJSONObject("__rerum").element("isReleased",
                                System.currentTimeMillis() + "");
                        safe_original.getJSONObject("__rerum").getJSONObject("releases").element("replaces",
                                previousReleasedID);
                        releasedObject = (BasicDBObject) JSON.parse(safe_original.toString());
                        if (!"".equals(previousReleasedID)) {// A releases tree exists and an acestral object is being released.  
                            treeHealed = healReleasesTree(safe_original);
                        } else { //There was no releases previous value. 
                            if (nextReleases.size() > 0) { //The release tree has been established and a descendent object is now being released.
                                treeHealed = healReleasesTree(safe_original);
                            } else { //The release tree has not been established
                                treeHealed = establishReleasesTree(safe_original);
                            }
                        }
                        if (treeHealed) { //If the tree was established/healed
                            //perform the update to isReleased of the object being released.  Its releases.next[] and releases.previous are already correct.
                            mongoDBService.update(Constant.COLLECTION_ANNOTATION, originalObject,
                                    releasedObject);
                            releasedObject.remove("_id");
                            JSONObject newObject = JSONObject.fromObject(releasedObject);
                            System.out.println("Object released: " + updateToReleasedID);
                            JSONObject jo = new JSONObject();
                            jo.element("code", HttpServletResponse.SC_OK);
                            jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response.
                            jo.element("previously_released_id", previousReleasedID);
                            jo.element("next_releases_ids", nextReleases);
                            try {
                                addWebAnnotationHeaders(updateToReleasedID, isContainerType(safe_original),
                                        isLD(safe_original));
                                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(
                                "You are not the generator of this object.  Only the agent who created this object can release it.  Agent= "
                                        + generatorID,
                                HttpServletResponse.SC_UNAUTHORIZED);
                    }

                } else {
                    //This could mean it was an external object, but the release action fails on those.
                    writeErrorResponse(
                            "Object " + received.getString("@id") + " not found in RERUM, could not release.",
                            HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        } else {
            writeErrorResponse("Object did not contain an @id, could not release.",
                    HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

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

/**
 * A public facing servlet to determine if a given object ID is for a deleted object.
 * @FIXME make the parameter the http_request, get the @id, get from mongo and feed to private version.
 * @param obj_id/*  w  w  w  . j  ava2 s .c  o m*/
 * @return A boolean representing the truth.
 */
public boolean checkIfDeleted(String obj_id) {
    BasicDBObject query = new BasicDBObject();
    BasicDBObject dbObj;
    JSONObject checkThis = new JSONObject();
    query.append("@id", obj_id);
    dbObj = (BasicDBObject) mongoDBService.findOneByExample(Constant.COLLECTION_ANNOTATION, query);
    if (null != dbObj) {
        checkThis = JSONObject.fromObject(dbObj);
    }

    return checkIfDeleted(checkThis);

}

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

/**
 * Public facing servlet that checks whether the provided object id is of a released object.
 * @param obj_id// ww  w  .j  a  v a  2 s .c  o  m
 * @return 
 */
public boolean checkIfReleased(String obj_id) {
    BasicDBObject query = new BasicDBObject();
    BasicDBObject dbObj;
    JSONObject checkThis = new JSONObject();
    query.append("@id", obj_id);
    dbObj = (BasicDBObject) mongoDBService.findOneByExample(Constant.COLLECTION_ANNOTATION, query);
    if (null != dbObj) {
        checkThis = JSONObject.fromObject(dbObj);
    }
    return checkIfReleased(checkThis);
}

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

/**
 * Public facing servlet to delete a given annotation. 
 *///from www .  j  a v a2  s .co  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);
        }
    }
}

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

/**
 * An internal method to handle when an object is deleted and the history tree around it will need amending.  
 * This function should only be handed a reliable object from mongo.
 * //  w  w w  .j  a va  2  s  .c o m
 * @param obj A JSONObject of the object being deleted.
 * @return A boolean representing whether or not this function succeeded. 
 */
private boolean healHistoryTree(JSONObject obj) {
    boolean success = true;
    String previous_id = "";
    String prime_id = "";
    JSONArray next_ids = new JSONArray();
    try {
        //Try to dig down the object and get these properties
        previous_id = obj.getJSONObject("__rerum").getJSONObject("history").getString("previous");
        prime_id = obj.getJSONObject("__rerum").getJSONObject("history").getString("prime");
        next_ids = obj.getJSONObject("__rerum").getJSONObject("history").getJSONArray("next");
    } catch (Exception e) {
        //@cubap @theHabes #44.  What if obj does not have __rerum or __rerum.history            
        previous_id = ""; //This ensures detectedPrevious is false
        prime_id = ""; //This ensures isRoot is false
        next_ids = new JSONArray(); //This ensures the loop below does not run.
        success = false; //This will bubble out to deleteObj() and have the side effect that this object is not deleted.  @see treeHealed
    }
    boolean isRoot = prime_id.equals("root");
    boolean detectedPrevious = !previous_id.equals("");
    //Update the history.previous of all the next ids in the array of the deleted object
    for (int n = 0; n < next_ids.size(); n++) {
        BasicDBObject query = new BasicDBObject();
        BasicDBObject objToUpdate;
        BasicDBObject objWithUpdate;
        String nextID = next_ids.getString(n);
        query.append("@id", nextID);
        objToUpdate = (BasicDBObject) mongoDBService.findOneByExample(Constant.COLLECTION_ANNOTATION, query);
        if (null != objToUpdate) {
            JSONObject fixHistory = JSONObject.fromObject(objToUpdate);
            if (isRoot) { //The object being deleted was root.  That means these next objects must become root.  Strictly, all history trees must have num(root) > 0.  
                fixHistory.getJSONObject("__rerum").getJSONObject("history").element("prime", "root");
                newTreePrime(fixHistory);
            } else if (detectedPrevious) { //The object being deleted had a previous.  That is now absorbed by this next object to mend the gap.  
                fixHistory.getJSONObject("__rerum").getJSONObject("history").element("previous", previous_id);
            } else {
                System.out.println("object did not have previous and was not root.  Weird...");
                // @cubap @theHabes TODO Yikes this is some kind of error...it is either root or has a previous, this case means neither are true.
                // cubap: Since this is a __rerum error and it means that the object is already not well-placed in a tree, maybe it shouldn't fail to delete?
                // theHabes: Are their bad implications on the relevant nodes in the tree that reference this one if we allow it to delete?  Will their account of the history be correct?
                //success = false;
            }
            Object forMongo = JSON.parse(fixHistory.toString()); //JSONObject cannot be converted to BasicDBObject
            objWithUpdate = (BasicDBObject) forMongo;
            mongoDBService.update(Constant.COLLECTION_ANNOTATION, objToUpdate, objWithUpdate);
        } else {
            System.out.println("could not find an object assosiated with id found in history tree");
            success = false;
            //Yikes this is an error, could not find an object assosiated with id found in history tree.
        }
    }
    if (detectedPrevious) {
        //The object being deleted had a previous.  That previous object next[] must be updated with the deleted object's next[].
        BasicDBObject query2 = new BasicDBObject();
        BasicDBObject objToUpdate2;
        BasicDBObject objWithUpdate2;
        query2.append("@id", previous_id);
        objToUpdate2 = (BasicDBObject) mongoDBService.findOneByExample(Constant.COLLECTION_ANNOTATION, query2);
        if (null != objToUpdate2) {
            JSONObject fixHistory2 = JSONObject.fromObject(objToUpdate2);
            JSONArray origNextArray = fixHistory2.getJSONObject("__rerum").getJSONObject("history")
                    .getJSONArray("next");
            JSONArray newNextArray = new JSONArray();
            //JSONArray does not have splice, but we can code our own.  This will splice out obj["@id"].
            for (int i = 0; i < origNextArray.size(); i++) {
                if (!origNextArray.getString(i).equals(obj.getString("@id"))) {
                    //So long as the value is not the deleted id, add it to the newNextArray (this is the splice).  
                    newNextArray.add(origNextArray.get(i));
                }
            }
            newNextArray.addAll(next_ids); //Adds next array of deleted object to the end of this array in order.
            fixHistory2.getJSONObject("__rerum").getJSONObject("history").element("next", newNextArray); //Rewrite the next[] array to fix the history
            Object forMongo2 = JSON.parse(fixHistory2.toString()); //JSONObject cannot be converted to BasicDBObject
            objWithUpdate2 = (BasicDBObject) forMongo2;
            mongoDBService.update(Constant.COLLECTION_ANNOTATION, objToUpdate2, objWithUpdate2);
        } else {
            //Yikes this is an error.  We had a previous id in the object but could not find it in the store.
            System.out.println("We had a previous id in the object but could not find it in the store");
            success = false;
        }
    }
    return success;
}

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

/**
* Validate data is IIIF compliant against IIIF's validator.  This object is intended for creation and not yet saved into RERUM so it does not yet have an @id.
* The only way to hit the IIIF Validation API is to use the object's @id. The idea would be to save the objects to get an id, hit the 
* IIIF API and if the object was intended to be IIIF, delete it from the store and return an error to the user.
* 
* In the case the object was not intended to be IIIF, do not return an error. Since the methods calling this will handle what happens based of iiif_return.okay,
* just set okay to 1 and the methods calling this will treat it as if it isn't a problem. 
* 
* @param objectToCheck A JSON object to parse through and validate.  This object has not yet been saved into mongo, so it does not have an @id yet
* @param intendedIIIF A flag letting me know whether or not this object is intended to be IIIF.  If it isn't, don't treat validation failure as an error.
* @return iiif_return The return JSONObject from hitting the IIIF Validation API.
*/// ww  w  .j  a  v  a  2 s .c  o m
public JSONObject checkIIIFCompliance(JSONObject objectToCheck, boolean intendedIIIF)
        throws MalformedURLException, IOException {
    JSONObject iiif_return = new JSONObject();
    DBObject dbo = (DBObject) JSON.parse(objectToCheck.toString());
    BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo);
    String newObjectID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
    String uid = Constant.RERUM_ID_PREFIX + newObjectID;
    dboWithObjectID.append("@id", uid);
    mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID);
    iiif_return = checkIIIFCompliance(uid, "2.1"); //If it is an object we are creating, this line means @context must point to Presentation API 2 or 2.1
    if (iiif_return.containsKey("okay")) {
        if (iiif_return.getInt("okay") == 0) {
            if (intendedIIIF) {
                //If it was intended to be a IIIF object, then remove this object from the store because it was not valid and return an error to the user

            } else {
                //Otherwise say it is ok so the action looking do validate does not writeErrorResponse()
                iiif_return.element("okay", 1);
            }
        }
        iiif_return.remove("received");
    } else {
        //Then the validator had a problem, perhaps it timed out and returned a blank object...
        iiif_return.element("okay", 0);
        iiif_return.element("error",
                "504: IIIF took too long to repond to RERUM.  The object was not submitted for validation.");
    }
    BasicDBObject query = new BasicDBObject();
    query.append("_id", newObjectID);
    mongoDBService.delete(Constant.COLLECTION_ANNOTATION, query);
    return iiif_return;
}

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

/**
* Internal helper method to handle put_update.action on an external object.  The goal is to make a copy of object as denoted by the PUT request
* as a RERUM object (creating a new object) then have that new root object reference the @id of the external object in its history.previous. 
* 
* @param externalObj the external object as it existed in the PUT request to be saved.
*///  w w w. jav a2  s  .c om
private void updateExternalObject(JSONObject externalObj) {
    System.out.println("update on external object");
    //System.out.println(externalObj);
    externalObj.remove("_id"); //Make sure not to pass this along to any save/update scenario.  
    try {
        JSONObject jo = new JSONObject();
        JSONObject iiif_validation_response = checkIIIFCompliance(externalObj, true);
        JSONObject newObjState = configureRerumOptions(externalObj, true);
        DBObject dbo = (DBObject) JSON.parse(newObjState.toString());
        String exernalObjID = newObjState.getString("@id");
        String newRootID;
        String newObjectID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
        //set @id from _id and update the annotation
        BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo);
        newRootID = Constant.RERUM_ID_PREFIX + newObjectID;
        dboWithObjectID.append("@id", newRootID);
        newObjState.element("@id", newRootID);
        mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID);
        newObjState = configureRerumOptions(newObjState, false);
        newObjState = alterHistoryPrevious(newObjState, exernalObjID); //update history.previous of the new object to contain the external object's @id.
        newObjState.remove("_id");
        jo.element("code", HttpServletResponse.SC_CREATED);
        jo.element("original_object_id", exernalObjID);
        jo.element("new_obj_state", newObjState);
        jo.element("iiif_validation", iiif_validation_response);
        addWebAnnotationHeaders(newRootID, isContainerType(newObjState), isLD(newObjState));
        addLocationHeader(newObjState);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setStatus(HttpServletResponse.SC_CREATED);
        response.addHeader("Content-Type", "application/json; charset=utf-8");
        System.out.println("Object now internal to rerum: " + newRootID);
        out = response.getWriter();
        out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo));
    } catch (IOException ex) {
        Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
    }

}