Example usage for com.mongodb BasicDBObject copy

List of usage examples for com.mongodb BasicDBObject copy

Introduction

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

Prototype

public Object copy() 

Source Link

Document

Creates a new instance which is a copy of this BasicDBObject.

Usage

From source file:com.avanza.ymer.MirroredObjectLoader.java

License:Apache License

private Optional<LoadedDocument<T>> patchAndConvert(BasicDBObject dbObject) {
    BasicDBObject currentVersion = dbObject;
    boolean patched = false;
    if (this.mirroredObject.requiresPatching(dbObject)) {
        patched = true;/*  w w  w.  java  2 s .com*/
        try {
            currentVersion = (BasicDBObject) dbObject.copy();
            postReadProcessor.postRead(currentVersion);
            currentVersion = this.mirroredObject.patch(currentVersion);
        } catch (RuntimeException e) {
            log.error(
                    "Patch of document failed! document=" + mirroredObject + "currentVersion=" + currentVersion,
                    e);
            throw e;
        }
    } else {
        postReadProcessor.postRead(currentVersion);
    }
    T mirroredObject = documentConverter.convert(this.mirroredObject.getMirroredType(), currentVersion);
    if (!spaceObjectFilter.accept(mirroredObject)) {
        return Optional.empty();
    }
    if (patched) {
        return Optional.of(new LoadedDocument<T>(postProcess(mirroredObject),
                Optional.of(new PatchedDocument(dbObject, currentVersion))));
    }
    return Optional.of(new LoadedDocument<T>(postProcess(mirroredObject), Optional.empty()));
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void insert(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final BasicDBObject doc = (BasicDBObject) ((DocBuilderField) getBoundUnit(Item.insertDoc)).getDBObject();
    final int count = getIntFieldValue(Item.insertCount);
    final boolean bulk = getBooleanFieldValue(Item.insertBulk);

    new DbJob() {
        @Override/*from   w  ww  . j  a v  a  2s  . c om*/
        public Object doRun() throws IOException {
            WriteResult res = null;
            List<DBObject> list = new ArrayList<DBObject>();
            for (int i = 0; i < count; ++i) {
                BasicDBObject newdoc = (BasicDBObject) doc.copy();
                handleSpecialFields(newdoc);
                if (bulk) {
                    list.add(newdoc);
                    if (list.size() >= 1000) {
                        res = col.insert(list);
                        list.clear();
                    }
                } else {
                    res = col.insert(newdoc);
                }
            }
            if (bulk && !list.isEmpty()) {
                return col.insert(list);
            }
            return res;
        }

        @Override
        public String getNS() {
            return col.getFullName();
        }

        @Override
        public String getShortName() {
            return "Insert";
        }

        @Override
        public DBObject getRoot(Object result) {
            BasicDBObject root = new BasicDBObject("doc", doc);
            root.put("count", count);
            root.put("bulk", bulk);
            return root;
        }

        @Override
        public ButtonBase getButton() {
            return button;
        }
    }.addJob();
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void save(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final BasicDBObject doc = (BasicDBObject) ((DocBuilderField) getBoundUnit(Item.saveDoc)).getDBObject();

    new DbJob() {
        @Override/*ww  w . j a  va2 s  . co  m*/
        public Object doRun() throws IOException {
            return col.save((DBObject) doc.copy());
        }

        @Override
        public String getNS() {
            return col.getFullName();
        }

        @Override
        public String getShortName() {
            return "Save";
        }

        @Override
        public DBObject getRoot(Object result) {
            return doc;
        }

        @Override
        public ButtonBase getButton() {
            return button;
        }
    }.addJob();
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void findAndModify(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.famQuery)).getDBObject();
    final DBObject fields = ((DocBuilderField) getBoundUnit(Item.famFields)).getDBObject();
    final DBObject sort = ((DocBuilderField) getBoundUnit(Item.famSort)).getDBObject();
    final BasicDBObject update = (BasicDBObject) ((DocBuilderField) getBoundUnit(Item.famUpdate)).getDBObject();
    final boolean remove = getBooleanFieldValue(Item.famRemove);
    final boolean returnNew = getBooleanFieldValue(Item.famReturnNew);
    final boolean upsert = getBooleanFieldValue(Item.famUpsert);

    BasicDBObject cmd = new BasicDBObject("findandmodify", col.getName());
    if (query != null && !query.keySet().isEmpty()) {
        cmd.append("query", query);
    }//  ww w.  j a v a2  s.  c o  m
    if (fields != null && !fields.keySet().isEmpty()) {
        cmd.append("fields", fields);
    }
    if (sort != null && !sort.keySet().isEmpty()) {
        cmd.append("sort", sort);
    }

    if (remove) {
        cmd.append("remove", remove);
    } else {
        if (update != null && !update.keySet().isEmpty()) {
            // if 1st key doesn't start with $, then object will be inserted as is, need to check it
            String key = update.keySet().iterator().next();
            if (key.charAt(0) != '$') {
                MongoUtils.checkObject(update, false, false);
            }
            cmd.append("update", (DBObject) update.copy());
        }
        if (returnNew) {
            cmd.append("new", returnNew);
        }
        if (upsert) {
            cmd.append("upsert", upsert);
        }
    }

    new DbJobCmd(col.getDB(), cmd, null, button).addJob();
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void update(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.upQuery)).getDBObject();
    final BasicDBObject update = (BasicDBObject) ((DocBuilderField) getBoundUnit(Item.upUpdate)).getDBObject();
    final boolean upsert = getBooleanFieldValue(Item.upUpsert);
    final boolean multi = getBooleanFieldValue(Item.upMulti);
    final boolean safe = getBooleanFieldValue(Item.upSafe);
    col.setWriteConcern(WriteConcern.SAFE);

    new DbJob() {
        @Override/*from w w w . ja  va 2 s.c  o  m*/
        public Object doRun() {
            if (safe) {
                long count = col.getCount(query);
                long toupdate = count > 0 ? 1 : 0;
                if (multi) {
                    toupdate = count;
                }
                String text = "Proceed with updating " + toupdate + " of " + count + " documents?";
                ConfirmDialog confirm = new ConfirmDialog(null, "Confirm Update", null, text);
                if (!confirm.show()) {
                    return null;
                }
            }
            return col.update(query, (DBObject) update.copy(), upsert, multi);
        }

        @Override
        public String getNS() {
            return col.getFullName();
        }

        @Override
        public String getShortName() {
            return "Update";
        }

        @Override
        public DBObject getRoot(Object result) {
            BasicDBObject obj = new BasicDBObject("query", query);
            obj.put("update", update);
            obj.put("upsert", upsert);
            obj.put("multi", multi);
            return obj;
        }

        @Override
        public ButtonBase getButton() {
            return button;
        }
    }.addJob();
}

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   w  w w.j a va 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/*from  ww  w . ja  v a  2 s .c o  m*/
 * @throws javax.servlet.ServletException
 */
public void patchUnsetUpdate() throws IOException, ServletException, Exception {
    Boolean historyNextUpdatePassed = false;
    System.out.println("Patch unset update");
    if (null != processRequestBody(request, true) && methodApproval(request, "unset")) {
        BasicDBObject query = new BasicDBObject();
        JSONObject received = JSONObject.fromObject(content);
        if (received.containsKey("@id")) {
            String updateHistoryNextID = received.getString("@id");
            query.append("@id", updateHistoryNextID);
            BasicDBObject originalObject = (BasicDBObject) mongoDBService
                    .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object
            BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object.  Make all edits to this variable.
            boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject));
            boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject));
            if (alreadyDeleted) {
                writeErrorResponse("The object you are trying to update is deleted.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else if (isReleased) {
                writeErrorResponse("The object you are trying to update is released.  Fork to make changes.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else {
                if (null != originalObject) {
                    Set<String> update_anno_keys = received.keySet();
                    int updateCount = 0;
                    //If the object already in the database contains the key found from the object recieved from the user...
                    for (String key : update_anno_keys) {
                        if (originalObject.containsKey(key)) {
                            if (key.equals("@id") || key.equals("__rerum") || key.equals("objectID")
                                    || key.equals("_id")) {
                                // Ignore these in a PATCH.  DO NOT update, DO NOT count as an attempt to update
                            } else {
                                if (null != received.get(key)) { //Found matching keys and value is not null.  Ignore these.
                                    //@cubap @theHabes do we want to build that this happened into the response at all?
                                } else { //Found matching keys and value is null, this is an unset
                                    updatedObject.remove(key);
                                    updateCount += 1;
                                }
                            }
                        } else { //Original object does not contain this key, perhaps the user meant set.
                                 //@cubap @theHabes do we want to build that this happened into the response at all?
                        }
                    }
                    if (updateCount > 0) {
                        JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning)
                        newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action
                        newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set.
                        //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject);
                        DBObject dbo = (DBObject) JSON.parse(newObject.toString());
                        String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
                        String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID;
                        BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo);
                        dboWithObjectID.append("@id", newNextAtID);
                        newObject.element("@id", newNextAtID);
                        newObject.remove("_id");
                        mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID);
                        historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id
                        if (historyNextUpdatePassed) {
                            System.out.println("Patch unset updated: " + newNextAtID);
                            JSONObject jo = new JSONObject();
                            JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1");
                            jo.element("code", HttpServletResponse.SC_OK);
                            jo.element("original_object_id", updateHistoryNextID);
                            jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response.
                            jo.element("iiif_validation", iiif_validation_response);
                            try {
                                addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject));
                                addLocationHeader(newObject);
                                response.addHeader("Access-Control-Allow-Origin", "*");
                                response.setStatus(HttpServletResponse.SC_OK);
                                response.addHeader("Content-Type", "application/json; charset=utf-8");
                                response.setContentType("UTF-8");
                                out = response.getWriter();
                                out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo));
                            } catch (IOException ex) {
                                Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } else {
                            //The error is already written to response.out, do nothing.
                        }
                    } else {
                        // Nothing could be patched
                        addLocationHeader(received);
                        writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT);
                    }
                } else {
                    //This could means it was an external object, but those fail for PATCH updates.
                    writeErrorResponse("Object " + received.getString("@id")
                            + " not found in RERUM, could not update.  PUT update to make this object a part of RERUM.",
                            HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        } else {
            writeErrorResponse("Object did not contain an @id, could not update.",
                    HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

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

/**
 * Update a given annotation. Cannot set or unset keys.  
 * @respond with state of new object in the body
 *//*from  ww  w .j  av a 2s  .c o m*/
public void patchUpdateObject() throws ServletException, Exception {
    Boolean historyNextUpdatePassed = false;
    System.out.println("trying to patch");
    if (null != processRequestBody(request, true) && methodApproval(request, "patch")) {
        BasicDBObject query = new BasicDBObject();
        JSONObject received = JSONObject.fromObject(content);
        if (received.containsKey("@id")) {
            String updateHistoryNextID = received.getString("@id");
            query.append("@id", updateHistoryNextID);
            BasicDBObject originalObject = (BasicDBObject) mongoDBService
                    .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object
            boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject));
            boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject));
            if (alreadyDeleted) {
                writeErrorResponse("The object you are trying to update is deleted.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else if (isReleased) {
                writeErrorResponse("The object you are trying to update is released.  Fork to make changes.",
                        HttpServletResponse.SC_FORBIDDEN);
            } else {
                if (null != originalObject) {
                    BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object.  Make all edits to this variable.
                    Set<String> update_anno_keys = received.keySet();
                    boolean triedToSet = false;
                    int updateCount = 0;
                    //If the object already in the database contains the key found from the object recieved from the user, update it barring a few special keys
                    //Users cannot update the __rerum property, so we ignore any update action to that particular field.  
                    for (String key : update_anno_keys) {
                        if (originalObject.containsKey(key)) {
                            //Skip keys we want to ignore and keys that match but have matching values
                            if (!(key.equals("@id") || key.equals("__rerum") || key.equals("objectID")
                                    || key.equals("_id")) && received.get(key) != originalObject.get(key)) {
                                updatedObject.remove(key);
                                updatedObject.append(key, received.get(key));
                                updateCount += 1;
                            }
                        } else {
                            triedToSet = true;
                            // break;
                        }
                    }
                    if (triedToSet) {
                        System.out.println("Patch meh 1");
                        //@cubap @theHabes We continued with what we could patch.  Do we tell the user at all?
                        //writeErrorResponse("A key you are trying to update does not exist on the object.  You can set with the patch_set or put_update action.", HttpServletResponse.SC_BAD_REQUEST);
                    } else if (updateCount == 0) {
                        System.out.println("Patch meh 2");
                        addLocationHeader(received);
                        writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT);
                    } else {
                        JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning)
                        newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action
                        newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set.
                        //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject);
                        DBObject dbo = (DBObject) JSON.parse(newObject.toString());
                        String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo);
                        String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID;
                        BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo);
                        dboWithObjectID.append("@id", newNextAtID);
                        newObject.element("@id", newNextAtID);
                        newObject.remove("_id");
                        mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID);
                        historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id
                        if (historyNextUpdatePassed) {
                            System.out.println("Patch updated object: " + newNextAtID);
                            JSONObject jo = new JSONObject();
                            JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1");
                            jo.element("code", HttpServletResponse.SC_OK);
                            jo.element("original_object_id", updateHistoryNextID);
                            jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response.
                            jo.element("iiif_validation", iiif_validation_response);
                            try {
                                addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject));
                                addLocationHeader(newObject);
                                response.addHeader("Access-Control-Allow-Origin", "*");
                                response.setStatus(HttpServletResponse.SC_OK);
                                response.addHeader("Content-Type", "application/json; charset=utf-8");
                                response.setContentType("UTF-8");
                                out = response.getWriter();
                                out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo));
                            } catch (IOException ex) {
                                Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } else {
                            //The error is already written to response.out, do nothing.
                        }
                    }
                } else {
                    writeErrorResponse(
                            "Object " + received.getString("@id")
                                    + " not found in RERUM, could not patch update.",
                            HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        } else {
            writeErrorResponse("Object did not contain an @id, could not patch update.",
                    HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file: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/* w  w w  . ja  v  a 2  s  .c  om*/
* @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:fr.eolya.crawler.queue.mongodb.MongoDBSourceItemsQueue.java

License:Apache License

/** 
 * Get the older item (FIFO)/*from   ww  w  . j  a v  a2s .  co m*/
 * 
 * @return the item or null
 */
public Map<String, Object> pop(String extraSortField) {

    String query;
    if (!rescan) {
        if (startDepth == 0) {
            if (checkDeletionMode) {
                String query1 = "{\"" + timestampFieldName + "\": {\"$gt\": " + String.valueOf(startTime)
                        + "}}";
                String query2_1 = "{\"" + timestampFieldName + "\": {\"$lt\": " + String.valueOf(startTime)
                        + "}}";
                String query2_2 = "{\"crawl_status\":200}";
                String query_2 = "{\"$and\": [" + query2_1 + ", " + query2_2 + "]}";
                query = "{\"$or\": [" + query1 + ", " + query_2 + "]}";
            } else {
                query = "{\"" + timestampFieldName + "\": {\"$gt\": " + String.valueOf(startTime) + "}}";
            }
        } else {
            String query1 = "{\"" + timestampFieldName + "\": {\"$gt\": " + String.valueOf(startTime) + "}}";
            String query2_1 = "{\"" + timestampFieldName + "\": {\"$lt\": " + String.valueOf(startTime) + "}}";
            String query2_2 = "{\"depth\":" + String.valueOf(startDepth) + "}";
            String query2_3 = "{\"crawl_status\":200}";
            String query_2 = "{\"$and\": [" + query2_1 + ", " + query2_2 + ", " + query2_3 + "]}";
            query = "{\"$or\": [" + query1 + ", " + query_2 + "]}";
        }
    } else {
        String queryTimeStamp = "{\"" + timestampFieldName + "\": {\"$ne\": " + String.valueOf(startTime)
                + "}}";
        String queryMode = "{\"crawl_mode\":\"a\"}";
        String query200 = "{\"crawl_status\":200}";
        query = "{\"$and\": [" + queryTimeStamp + ", " + queryMode + ", " + query200 + "]}";
    }
    BasicDBObject docsearch = MongoDBHelper.JSON2BasicDBObject(query);

    DBCursor cur = null;
    synchronized (collMonitor) {
        if (extraSortField != null) {
            cur = coll.getColl().find(docsearch).sort(new BasicDBObject(extraSortField, 1));
        } else {
            cur = coll.getColl().find(docsearch);
        }
        if (cur.hasNext()) {
            BasicDBObject doc = (BasicDBObject) cur.next();
            BasicDBObject doc2 = (BasicDBObject) doc.copy();
            doc2.put(timestampFieldName, startTime);
            coll.update(doc, doc2);
            size--;
            doneCount++;
            //return doc.toMap();
            return MongoDBHelper.BasicDBObject2Map(doc2);
        }
    }
    return null;
}