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.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 ww.  j av a 2 s  .com*/
 * 
 * @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/*from   w  ww .j a v  a2 s  . 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

/**
 * Internal helper method to update the releases tree from a given object that is being released.  See code in method for further documentation.
 * https://www.geeksforgeeks.org/find-whether-an-array-is-subset-of-another-array-set-1/
 * //from w ww  .  j a v a2s .co  m
 * This method only receives reliable objects from mongo.
 * 
 * @param obj the RERUM object being released
 * @return Boolean success or some kind of Exception
 */
private boolean healReleasesTree(JSONObject releasingNode) throws Exception {
    Boolean success = true;
    List<DBObject> ls_versions = getAllVersions(releasingNode);
    JSONArray descendents = getAllDescendents(ls_versions, releasingNode, new JSONArray());
    JSONArray anscestors = getAllAncestors(ls_versions, releasingNode, new JSONArray());
    for (int d = 0; d < descendents.size(); d++) { //For each descendent
        JSONObject desc = descendents.getJSONObject(d);
        boolean prevMatchCheck = desc.getJSONObject("__rerum").getJSONObject("releases").getString("previous")
                .equals(releasingNode.getJSONObject("__rerum").getJSONObject("releases").getString("previous"));
        DBObject origDesc = (DBObject) JSON.parse(desc.toString());
        if (prevMatchCheck) {
            //If the descendent's previous matches the node I am releasing's releases.previous, swap the descendent releses.previous with node I am releasing's @id. 
            desc.getJSONObject("__rerum").getJSONObject("releases").element("previous",
                    releasingNode.getString("@id"));
            if (!desc.getJSONObject("__rerum").getString("isReleased").equals("")) {
                //If this descendent is released, it replaces thr node being released
                if (desc.getJSONObject("__rerum").getJSONObject("releases").getString("previous")
                        .equals(releasingNode.getString("@id"))) {
                    desc.getJSONObject("__rerum").getJSONObject("releases").element("replaces",
                            releasingNode.getString("@id"));
                }
            }
            DBObject descToUpdate = (DBObject) JSON.parse(desc.toString());
            mongoDBService.update(Constant.COLLECTION_ANNOTATION, origDesc, descToUpdate);
        }
    }
    JSONArray origNextArray = releasingNode.getJSONObject("__rerum").getJSONObject("releases")
            .getJSONArray("next");
    for (int a = 0; a < anscestors.size(); a++) { //For each ancestor
        JSONArray ancestorNextArray = anscestors.getJSONObject(a).getJSONObject("__rerum")
                .getJSONObject("releases").getJSONArray("next");
        JSONObject ans = anscestors.getJSONObject(a);
        DBObject origAns = (DBObject) JSON.parse(ans.toString());
        if (origNextArray.size() == 0) {
            //The releases.next on the node I am releasing is empty.  This means only other ancestors with empty releases.next[] are between me and the next ancenstral released node
            if (ancestorNextArray.size() == 0) {
                ancestorNextArray.add(releasingNode.getString("@id")); //Add the id of the node I am releasing into the ancestor's releases.next array.
            }
        } else {
            //The releases.next on the node I am releasing has 1 - infinity entries.  I need to check if any of the entries of that array exist in the releases.next of my ancestors and remove them before
            //adding the @id of the released node into the acenstral releases.next array.  
            for (int i = 0; i < origNextArray.size(); i++) { //For each id in the next array of the object I am releasing (will not be []).
                String compareOrigNextID = origNextArray.getString(i);
                for (int j = 0; j < ancestorNextArray.size(); j++) { //For each id in the ancestor's releases.next array
                    String compareAncestorID = ancestorNextArray.getString(j);
                    if (compareOrigNextID.equals(compareAncestorID)) {
                        //If the id is in the next array of the object I am releasing and in the releases.next array of the ancestor
                        ancestorNextArray.remove(j); //remove that id.
                    }
                    //Whether or not the ancestral node replaces the node I am releasing or not happens in releaseObject() when I make the node I am releasing isReleased because I can use the releases.previous there.  
                    if (j == ancestorNextArray.size() - 1) { //Once I have checked against all id's in the ancestor node releases.next[] and removed the ones I needed to
                        ancestorNextArray.add(releasingNode.getString("@id")); //Add the id of the node I am releasing into the ancestor's releases.next array.
                    }
                }
            }
        }
        ans.getJSONObject("__rerum").getJSONObject("releases").element("next", ancestorNextArray);
        DBObject ansToUpdate = (DBObject) JSON.parse(ans.toString());
        mongoDBService.update(Constant.COLLECTION_ANNOTATION, origAns, ansToUpdate);
    }
    return success;
}

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

/**
 * Internal helper method to establish the releases tree from a given object that is being released.  
 * This can probably be collapsed into healReleasesTree.  It contains no checks, it is brute force update ancestors and descendents.
 * It is significantly cleaner and slightly faster than healReleaseTree() which is why I think we should keep them separate. 
 *  //from w ww  .j  a v  a  2 s  .  c om
 * This method only receives reliable objects from mongo.
 * 
 * @param obj the RERUM object being released
 * @return Boolean sucess or some kind of Exception
 */
private boolean establishReleasesTree(JSONObject obj) throws Exception {
    Boolean success = true;
    List<DBObject> ls_versions = getAllVersions(obj);
    JSONArray descendents = getAllDescendents(ls_versions, obj, new JSONArray());
    JSONArray anscestors = getAllAncestors(ls_versions, obj, new JSONArray());
    for (int d = 0; d < descendents.size(); d++) {
        JSONObject desc = descendents.getJSONObject(d);
        DBObject origDesc = (DBObject) JSON.parse(desc.toString());
        desc.getJSONObject("__rerum").getJSONObject("releases").element("previous", obj.getString("@id"));
        DBObject descToUpdate = (DBObject) JSON.parse(desc.toString());
        mongoDBService.update(Constant.COLLECTION_ANNOTATION, origDesc, descToUpdate);
    }
    for (int a = 0; a < anscestors.size(); a++) {
        JSONObject ans = anscestors.getJSONObject(a);
        DBObject origAns = (DBObject) JSON.parse(ans.toString());
        ans.getJSONObject("__rerum").getJSONObject("releases").getJSONArray("next").add(obj.getString("@id"));
        DBObject ansToUpdate = (DBObject) JSON.parse(ans.toString());
        mongoDBService.update(Constant.COLLECTION_ANNOTATION, origAns, ansToUpdate);
    }
    return success;
}

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

/**
 * Public facing servlet to delete a given annotation. 
 *//*from  www.  j a v  a 2s  . c  om*/
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 ww  .  j  av a 2s  .  c  om*/
 * @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

/**
* An internal method to make all descendents of this JSONObject take on a new history.prime = this object's @id
* This should only be fed a reliable object from mongo
* @param obj A new prime object whose descendents must take on its id
*///from w  ww  .jav  a  2  s .  c om
private boolean newTreePrime(JSONObject obj) {
    boolean success = true;
    String primeID = obj.getString("@id");
    JSONArray descendents = new JSONArray();
    for (int n = 0; n < descendents.size(); n++) {
        JSONObject descendentForUpdate = descendents.getJSONObject(n);
        JSONObject originalDescendant = descendents.getJSONObject(n);
        BasicDBObject objToUpdate = (BasicDBObject) JSON.parse(originalDescendant.toString());
        ;
        descendentForUpdate.getJSONObject("__rerum").getJSONObject("history").element("prime", primeID);
        BasicDBObject objWithUpdate = (BasicDBObject) JSON.parse(descendentForUpdate.toString());
        mongoDBService.update(Constant.COLLECTION_ANNOTATION, objToUpdate, objWithUpdate);
    }
    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.
*///from w ww. j av 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.
*///from   www  . jav  a  2s .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);
    }

}

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

private JSONObject generateAgentForLegacyUser(JSONObject legacyUserObj) {
    System.out.println(//from   w  w  w. jav a 2 s. com
            "Detected a legacy registration.  Creating an agent and storing it with this legacy object.");
    //System.out.println(legacyUserObj);
    JSONObject newAgent = new JSONObject();
    DBObject originalToUpdate = (DBObject) JSON.parse(legacyUserObj.toString());
    JSONObject orig = JSONObject.fromObject(originalToUpdate);
    String mbox = "Not Provided";
    String label = "Not Provided";
    String homepage = "Not Provided";
    if (legacyUserObj.containsKey("name") && !"".equals(legacyUserObj.getString("name"))) {
        label = legacyUserObj.getString("name");
    }
    if (legacyUserObj.containsKey("contact") && !"".equals(legacyUserObj.getString("contact"))) {
        mbox = legacyUserObj.getString("contact");
    }
    if (legacyUserObj.containsKey("website") && !"".equals(legacyUserObj.getString("website"))) {
        homepage = legacyUserObj.getString("website");
    }
    newAgent.element("@type", "foaf:Agent");
    newAgent.element("@context", Constant.RERUM_PREFIX + "context.json");
    newAgent.element("mbox", mbox);
    newAgent.element("label", label);
    newAgent.element("homepage", homepage);
    DBObject dbo = (DBObject) JSON.parse(newAgent.toString());
    String newObjectID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
    orig.element("agent", Constant.RERUM_ID_PREFIX + newObjectID);
    newAgent.element("@id", Constant.RERUM_ID_PREFIX + newObjectID);
    newAgent.element("agent", Constant.RERUM_ID_PREFIX + newObjectID);
    generatorID = Constant.RERUM_ID_PREFIX + newObjectID;
    DBObject updatedOrig = (DBObject) JSON.parse(orig.toString());
    DBObject idOnAgent = (DBObject) JSON.parse(newAgent.toString());
    mongoDBService.update(Constant.COLLECTION_ACCEPTEDSERVER, originalToUpdate, updatedOrig); //This update does not appear to work every time...
    mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, idOnAgent);
    System.out.println("Agent created and stored with accepted server...");
    System.out.println(updatedOrig);
    return newAgent;
}