Example usage for com.mongodb DBObject removeField

List of usage examples for com.mongodb DBObject removeField

Introduction

In this page you can find the example usage for com.mongodb DBObject removeField.

Prototype

Object removeField(String key);

Source Link

Document

Removes a field with a given name from this object.

Usage

From source file:GeoHazardServices.Inst.java

License:Apache License

@POST
@Path("/copyToUser")
@Produces(MediaType.APPLICATION_JSON)//from   www. j  a  va 2 s  . com
public String copyToUser(@Context HttpServletRequest request, @FormParam("srcId") String srcId,
        @CookieParam("server_cookie") String session) {

    Object[] required = { srcId };

    if (!checkParams(request, required))
        return jsfailure();

    User user = signedIn(session);

    if (user == null)
        return jsdenied();

    /* do not copy the event again if there is already one copy for that user */
    BasicDBObject inQuery = new BasicDBObject("copied", srcId);
    inQuery.put("user", user.objId);
    DBCursor cursor = db.getCollection("eqs").find(inQuery);

    if (cursor.hasNext()) {
        cursor.close();
        return jssuccess(new BasicDBObject("msg", "Copy already exists."));
    }

    cursor.close();

    inQuery = new BasicDBObject("_id", srcId);
    cursor = db.getCollection("eqs").find(inQuery);

    if (!cursor.hasNext())
        return jsfailure();

    DBObject obj = cursor.next();
    cursor.close();

    String id = newRandomId(user.name);
    obj.put("user", user.objId);
    obj.put("_id", id);
    obj.put("id", id);
    obj.put("timestamp", new Date());
    obj.put("copied", srcId);

    db.getCollection("eqs").insert(obj);

    /* copy computation results */
    cursor = db.getCollection("comp").find(new BasicDBObject("EventID", srcId));
    for (DBObject res : cursor) {
        res.put("EventID", id);
        res.removeField("_id");
        db.getCollection("comp").insert(res);
    }
    cursor.close();

    return jssuccess(new BasicDBObject("msg", "Event successfully copied."));
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private List<DBObject> msg(int limit, User user) {

    if (user == null)
        return null;

    DBCollection coll = db.getCollection("messages_sent");

    BasicDBObject inQuery = new BasicDBObject("SenderID", user.objId);

    /* query DB, sort the results by date and limit the number of returned entries */
    DBCursor cursor = coll.find(inQuery).sort(new BasicDBObject("CreatedTime", -1));

    if (limit > 0)
        cursor = cursor.limit(limit);//from   ww  w .j  a  v a 2  s.  c  om

    List<DBObject> result = cursor.toArray();
    cursor.close();

    inQuery = new BasicDBObject("ReceiverID", user.objId);
    coll = db.getCollection("messages_received");
    cursor = coll.find(inQuery).sort(new BasicDBObject("CreatedTime", -1));

    if (limit > 0)
        cursor = cursor.limit(limit);

    for (DBObject obj : cursor) {

        DBCursor csrUser = db.getCollection("users").find(new BasicDBObject("_id", obj.get("SenderID")));

        if (csrUser.hasNext())
            obj.put("From", (String) csrUser.next().get("username"));

        obj.put("To", new String[] { user.name });
        obj.put("Dir", "in");

        result.add(obj);
    }

    cursor.close();

    Collections.sort(result, new DateComparator("CreatedTime", -1));

    /* add parent event as sub-object because we want to show it on click */
    for (DBObject msg : result) {

        DBCursor csr = db.getCollection("eqs").find(new BasicDBObject("_id", msg.get("ParentId")));

        if (csr.hasNext()) {
            DBObject obj = csr.next();
            obj.removeField("image");
            msg.put("parentEvt", obj);
        }
    }

    return result;
}

From source file:gr.ntua.ivml.awareness.persistent.DigitalStory.java

License:Creative Commons License

public DBObject getBsonForSolr() {
    try {/*from ww w . j a va 2  s  .co m*/
        DBObject bsonDs = MongoDB.getMorphia().getMapper().toDBObject(this);
        List<StoryObject> lso = MongoDB.getStoryObjectDAO().getStoryObjectsByPlaceHolders(getStoryObjects());
        BasicDBList bsonStories = new BasicDBList();
        for (StoryObject so : lso) {
            if (so != null) {
                bsonStories.add(so.getBsonForSolr());
            }
        }
        bsonDs.removeField("storyObjects");
        bsonDs.put("storyObjects", bsonStories);

        String themeId = getTheme();
        if (themeId != null && themeId.length() > 0) {
            // replace theme link with json
            Theme th = MongoDB.getThemeDAO().get(new ObjectId(themeId));
            BSONObject themeJson = th.getBsonForSolr();
            bsonDs.removeField("theme");
            bsonDs.put("theme", themeJson);
        }
        return bsonDs;
    } catch (Exception e) {
        log.error("Couldnt get BSON from Morphia", e);
        return new BasicDBObject();
    }
}

From source file:io.github.apfelcreme.LitePortals.Bungee.Database.MongoController.java

License:Open Source License

/**
 * deletes a portal and resets the target of all portals it was connected to
 *
 * @param portal a portal/*from   w  ww.  ja v  a2s  . com*/
 */
public void deletePortal(Portal portal) {
    DBCollection collection = MongoConnector.getInstance().getCollection();

    // find all portals who have this portal as target
    BasicDBObject query = new BasicDBObject("target", portal.getId().toString());
    DBCursor dbCursor = collection.find(query);
    while (dbCursor.hasNext()) {
        DBObject portalObject = dbCursor.next();
        portalObject.removeField("target");
        UUID targetId = UUID.fromString((String) portalObject.get("portal_id"));
        collection.update(query, portalObject);
        Portal p = PortalManager.getInstance().getPortal(targetId);
        if (p != null) {
            p.setTarget(null);
        }
    }

    // remove the object itself
    BasicDBObject portalObject = new BasicDBObject("portal_id", portal.getId().toString());
    collection.remove(portalObject);

    PortalManager.getInstance().getPortals().remove(portal);
}

From source file:it.wami.map.mongodeploy.OsmSaxHandler.java

License:Apache License

/**
 * Try to recover the objects that can be saved inside the DB.
 * //  ww w . j  av a 2s  . c o m
 * @param coll {@link DBCollection} the target collection.
 * @param list {@link List}<{@link DBObject}> the list of objs to save inside the DB.
 */
private void recover(DBCollection coll, List<DBObject> list) {
    for (DBObject o : list) {
        try {
            coll.insert(o, WriteConcern.UNACKNOWLEDGED);
        } catch (MongoInternalException e) {
            System.err.println(o.get("_id"));
            o.removeField("loc");
            coll.insert(o, WriteConcern.UNACKNOWLEDGED);
        }
    }

}

From source file:MDBInt.DBMongo.java

License:Apache License

public ArrayList<String> findALLResourceMate(String dbName, String uuid) {
    ArrayList<String> finalOb = new ArrayList<String>();
    BasicDBObject first = new BasicDBObject();
    first.put("phisicalResourceId", uuid);

    DB database = this.getDB(dbName);
    DBCollection collection = database.getCollection("runTimeInfo");
    DBObject obj = null;//from w ww. ja  v a  2 s .  c o  m
    BasicDBObject query = new BasicDBObject();
    DBCursor cursore = null;
    Iterator<DBObject> it;

    obj = collection.findOne(first);

    if (obj != null) {
        query.put("requestUID", obj.get("requestUID"));
        query.put("uuidTemplate", obj.get("uuidTemplate"));
        query.put("localResourceName", obj.get("localResourceName"));
        query.put("stackName", obj.get("stackName"));
        query.put("resourceName", obj.get("resourceName"));
        query.put("type", obj.get("type"));
        query.put("state", false);

        System.out.println("MONGO QUERY " + query + " in DB:" + dbName + " for UUID:" + uuid);
        DBCursor b = collection.find(query).sort(new BasicDBObject("insertTimestamp", -1));
        Iterator i = b.iterator();
        if (i.hasNext())
            while (i.hasNext()) {
                DBObject tmp = (DBObject) i.next();
                tmp.removeField("_id");
                tmp.removeField("insertTimestamp");
                finalOb.add(tmp.toString());
            }
        else
            return null;
    }
    return finalOb;
}

From source file:MDBInt.DBMongo.java

License:Apache License

public ArrayList<String> findALLResourceMatefromTemplate(String dbName, String uuid) {
    ArrayList<String> finalOb = new ArrayList<String>();
    BasicDBObject first = new BasicDBObject();
    first.put("uuidTemplate", uuid);

    DB database = this.getDB(dbName);
    DBCollection collection = database.getCollection("runTimeInfo");
    DBObject obj = null;//from  w w  w.  ja v a2  s  .c o  m
    BasicDBObject query = new BasicDBObject();
    DBCursor cursore = null;
    Iterator<DBObject> it;

    //obj = collection.findOne(first);

    DBCursor bobj = collection.find(first).sort(new BasicDBObject("insertTimestamp", -1));
    obj = bobj.next();
    if (obj != null) {
        query.put("requestUID", obj.get("requestUID"));
        query.put("uuidTemplate", uuid);
        query.put("localResourceName", obj.get("localResourceName"));
        query.put("stackName", obj.get("stackName"));
        query.put("resourceName", obj.get("resourceName"));
        query.put("type", obj.get("type"));
        //query.put("state", false);

        System.out.println("MONGO QUERY " + query + " in DB:" + dbName + " for UUID:" + uuid);
        DBCursor b = collection.find(query).sort(new BasicDBObject("insertTimestamp", -1));
        Iterator i = b.iterator();
        if (i.hasNext())
            while (i.hasNext()) {
                DBObject tmp = (DBObject) i.next();
                tmp.removeField("_id");
                tmp.removeField("insertTimestamp");
                finalOb.add(tmp.toString());
            }
        else
            return null;
    }
    return finalOb;
}

From source file:me.philnate.textmanager.updates.Update12_12.java

License:Open Source License

private void updateNames() {
    LOG.info("Going to separate Customer name into first and LastName");
    final String contact = "contactName";
    DBCollection customers = ds.getCollection(Customer.class);
    for (DBObject customer : customers.find()) {
        if (customer.containsField(contact)) {
            String name = (String) customer.get(contact);
            LOG.info(String.format("Customer with contactName '%s' found", name));
            if (name.contains(" ")) {
                // customer has first and last name set so lets split it. We
                // consider that the first name has only one name and not
                // multiple
                String[] parts = name.split(" ", 2);
                customer.put("firstName", parts[0]);
                customer.put("lastName", parts[1]);
                LOG.info(String.format("Updated customer %s, firstName: '%s', lastName: '%s'",
                        customer.get("_id"), parts[0], parts[1]));
            } else {
                customer.put("firstName", "");
                customer.put("lastName", name);
            }//from w w  w.  j av a 2  s .co  m
        } else {
            customer.put("firstName", "");
            customer.put("lastName", "");
            LOG.warn(String.format("Customer %s has no contactName", customer.get("_id")));
        }
        // finally remove the legacy contactName and save the customer
        customer.removeField(contact);
        customers.save(customer);
    }
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewProfile(int requesterID, int profileOwnerID, HashMap<String, ByteIterator> result,
        boolean insertImage, boolean testMode) {

    int retVal = 0;
    if (requesterID < 0 || profileOwnerID < 0)
        return -1;

    com.mongodb.DB db = null;/*from w ww  .j  av a 2s .  co m*/
    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("users");
        DBObject q = new BasicDBObject().append("_id", profileOwnerID);
        q.removeField("tpic");
        BasicDBObject attrs = new BasicDBObject("tpic", 0);

        DBObject queryResult = null;
        queryResult = collection.findOne(q, attrs);

        if (queryResult.get("pic") != null) {
            byte[] myPic = (byte[]) queryResult.get("pic");
            result.put("pic", new ObjectByteIterator(myPic));
            if (testMode) {
                // Save loaded image from database into new image file
                FileOutputStream fos = new FileOutputStream(profileOwnerID + "--proimage.bmp");
                fos.write(myPic);
                fos.close();
            }
            queryResult.removeField("pic");
        }

        String x = queryResult.get("ConfFriends").toString();
        int frndCount = 0;
        if (x.equals("") || (!x.equals("") && (x.substring(2, x.length() - 1)).equals("")))
            frndCount = 0;
        else {
            x = x.substring(2, x.length() - 1);
            frndCount = x.split(",").length;
        }

        int pendCount = 0;
        if (requesterID == profileOwnerID) {
            x = queryResult.get("PendFriends").toString();
            if (x.equals("") || (!x.equals("") && (x.substring(2, x.length() - 1)).equals("")))
                pendCount = 0;
            else {
                x = x.substring(2, x.length() - 1);
                pendCount = x.split(",").length;
            }
        }

        // find number of resources posted for the user
        // queryResult = null;
        // queryResult = collection.findOne(q);
        x = queryResult.get("wallResources").toString();
        int resCount = 0;
        if (x.equals(""))
            resCount = 0;
        else {
            resCount = x.split(",").length;
        }

        if (queryResult != null) {
            // remove the ConfFriends and PendFriends and Resources
            // replace them with counts
            queryResult.removeField("ConfFriends");
            queryResult.removeField("PendFriends");
            queryResult.removeField("wallResources");
            result.putAll(queryResult.toMap());
            result.put("friendcount", new ObjectByteIterator(Integer.toString(frndCount).getBytes()));
            if (requesterID == profileOwnerID) {
                result.put("pendingcount", new ObjectByteIterator(Integer.toString(pendCount).getBytes()));
            }
            result.put("resourcecount", new ObjectByteIterator(Integer.toString(resCount).getBytes()));
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int listFriends(int requesterID, int profileOwnerID, Set<String> fields,
        Vector<HashMap<String, ByteIterator>> result, boolean insertImage, boolean testMode) {
    int retVal = 0;
    if (requesterID < 0 || profileOwnerID < 0)
        return -1;

    // first get all confirmed friendids for profileOwnerID
    com.mongodb.DB db = null;/*from ww w. j av a2 s.co  m*/
    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("users");
        DBObject q = new BasicDBObject().append("_id", profileOwnerID);
        q.removeField("pic");
        BasicDBObject attrs = new BasicDBObject("pic", 0);

        DBObject queryResult = null;
        queryResult = collection.findOne(q, attrs);

        String x = queryResult.get("ConfFriends").toString();

        if (!x.equals("")) {
            x = x.substring(2, x.length() - 1);
            if (!x.equals("")) {
                String friendIds[] = x.split(",");
                BasicDBObject query = new BasicDBObject();
                if (!friendListReq) {
                    List<Integer> list = new ArrayList<Integer>();
                    for (int i = 0; i < friendIds.length; i++) {
                        // add to list
                        list.add(Integer.parseInt(friendIds[i].trim()));
                        int cnt = 0;
                        if (i == friendIds.length - 1 || ((i + 1) % 10) == 0) {
                            // query
                            query.put("_id", new BasicDBObject("$in", list));
                            query.removeField("pic");
                            // DBCursor cursor = collection.find(query,
                            // fieldsObj);
                            DBCursor cursor = collection.find(query, attrs);
                            while (cursor.hasNext()) {
                                cnt++;
                                // System.out.println(cursor.next());
                                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                                DBObject curs = cursor.next();
                                if (curs.get("tpic") != null) {
                                    byte[] myPic = (byte[]) curs.get("tpic");
                                    vals.put("tpic", new ObjectByteIterator(myPic));
                                    if (testMode) {
                                        // Save loaded image from database
                                        // into new image file
                                        FileOutputStream fos = new FileOutputStream(
                                                profileOwnerID + "-" + cnt + "-mthumbimage.bmp");
                                        fos.write(myPic);
                                        fos.close();
                                    }
                                    curs.removeField("tpic");
                                }
                                vals.putAll(curs.toMap());
                                vals.remove("ConfFriends");
                                vals.remove("PendFriends");
                                vals.remove("wallResources");
                                // needed to do this so the coreworkload
                                // will not need to know the datastore typr
                                if (vals.get("_id") != null) {
                                    String tmp = vals.get("_id") + "";
                                    vals.remove("_id");
                                    vals.put("userid", new ObjectByteIterator(tmp.getBytes()));
                                }
                                result.add(vals);
                            }
                            cursor.close();
                            // empty list
                            list.clear();
                        }
                    }
                } else if (friendListReq) {// retrive one list
                    List<Integer> list = new ArrayList<Integer>();
                    for (int i = 0; i < friendIds.length; i++) {
                        // put all in one list and retrieve instead of
                        // retrieving one by one
                        list.add(Integer.parseInt(friendIds[i].trim()));
                    }
                    query.put("_id", new BasicDBObject("$in", list));
                    query.removeField("pic");
                    // DBCursor cursor = collection.find(query, fieldsObj);
                    DBCursor cursor = collection.find(query, attrs);

                    int cnt = 0;
                    while (cursor.hasNext()) {
                        cnt++;
                        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                        DBObject curs = cursor.next();
                        if (curs.get("tpic") != null) {
                            byte[] myPic = (byte[]) curs.get("tpic");
                            vals.put("tpic", new ObjectByteIterator(myPic));
                            if (testMode) {
                                // Save loaded image from database into new
                                // image file
                                FileOutputStream fos = new FileOutputStream(
                                        profileOwnerID + "-" + cnt + "-mthumbimage.bmp");
                                fos.write(myPic);
                                fos.close();
                            }
                            curs.removeField("tpic");
                        }

                        vals.putAll(curs.toMap());
                        vals.remove("ConfFriends");
                        vals.remove("PendFriends");
                        vals.remove("wallResurces");
                        // needed to do this so the coreworkload will not
                        // need to know the datastore typr
                        if (vals.get("_id") != null) {
                            String tmp = vals.get("_id") + "";
                            vals.remove("_id");
                            vals.put("userid", new ObjectByteIterator(tmp.getBytes()));
                        }
                        result.add(vals);
                    }
                    cursor.close();
                }
            }
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}